কম্পিউটার বিজ্ঞান · বই 3 · স্নাতক প্রথম বর্ষ

University Computer Science — Year 1

এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।

University Computer Science — Year 1 · স্নাতক প্রথম বর্ষ

28Sequential Circuits and Finite-State Machines

A traffic light changes every thirty seconds, and it knows which colour comes next. The circuits of Chapter 27 cannot do that: their outputs depend only on their inputs of the moment, and two identical inputs give identical outputs, whatever happened before. A light, a counter, a lock and a processor all need memory. This chapter builds memory from gates by letting them feed back on themselves, tames it with a clock, and arrives at the finite-state machine, the model behind every controller, whose most important example is the control unit of a processor. The last section builds one for the toy machine and checks it, instruction by instruction, against the toy machine’s simulator.

You already know

The second book met the flip-flop and the state machine, and its toy machine runs a fetch–decode–execute cycle; combinational circuits, Karnaugh maps, the ALU and propagation delay are in Chapter 27.

28.1 Feedback and memory

Definition 28.1 (Sequential circuit)

A sequential circuit is a circuit whose outputs depend on the past inputs as well as the present ones. Its gates form a graph with cycles, or it contains elements that store bits.

The simplest has two NOR gates, each fed by the other. The simulator for such circuits cannot evaluate the gates in a topological order, since there is none; it moves time forward one gate delay at a time, every gate taking the values its inputs had one unit before.

def sr_latch():
    n = Net("S", "R")
    n.gate("Q", "NOR", "R", "Qn")  # Qn is Q', the complement
    n.gate("Qn", "NOR", "S", "Q")
    return n
Listing 28.1. Two NOR gates feeding each other code/bachelor-1/28-sequential-circuits/listings/sr_latch.py
$ python sr_latch.py
phase      S R   Q Q' after each time unit
set        1 0   00 10 10 10 10 10
hold       0 0   10 10 10 10 10 10
reset      0 1   00 01 01 01 01 01
hold       0 0   01 01 01 01 01 01
forbidden  1 1   00 00 00 00 00 00
release    0 0   11 00 11 00 11 00
Output 28.1. The latch traced one gate delay at a time. After set and reset it holds its bit; released from S=R=1S = R = 1 it oscillates.

Definition 28.2 (Latch, SR latch, D latch)

A latch is a circuit with two stable states that stores one bit. An SR latch has inputs SS (set) and RR (reset): S=1S = 1 makes its output QQ 1, R=1R = 1 makes it 0, and S=R=0S = R = 0 keeps it. The input S=R=1S = R = 1 is forbidden. A D latch has a data input DD and an enable EE: while E=1E = 1 its output follows DD (it is transparent), and while E=0E = 0 it keeps the last value.

An SR latch: the output of each NOR gate is an input of the other. The loop is what remembers.
SSRRQQ next
00QQ (hold)
101 (set)
010 (reset)
11forbidden
An SR latch: the output of each NOR gate is an input of the other. The loop is what remembers.

With S=R=0S = R = 0 each NOR gate is an inverter, and two inverters in a loop are stable in two ways, Q=1,Q′=0Q = 1, Q' = 0 and Q=0,Q′=1Q = 0, Q' = 1: that is the stored bit. S=1S = 1 forces Q′=0Q' = 0, hence Q=1Q = 1; R=1R = 1 forces the opposite. With S=R=1S = R = 1 both outputs are 0, which is not a pair of complements; releasing both inputs at once lets the two gates race, and in a model with exactly equal delays they oscillate for ever. In real gates one wins, but nobody can say which: that is why the input is forbidden.

A D latch puts two AND gates in front: S=DES = DE and R=D′ER = D'E, so the forbidden input cannot happen. Its transparency is a problem, however. If the output of a latch feeds, through some logic, back to its own input, a change can run round the loop many times while the latch is enabled, and the result depends on how long the enable lasts. The cure is to let the stored value change only at an instant.

28.2 Flip-flops and the clock

Definition 28.3 (Flip-flop, edge-triggered D flip-flop)

A flip-flop stores one bit and changes it only at an edge of a control signal. An edge-triggered D flip-flop copies its input DD to its output QQ at each rising edge (a change from 0 to 1) of its clock input, and keeps QQ the rest of the time.

Two D latches make one. The first, the master, is enabled while the clock is 0 and follows DD; the second, the slave, is enabled while the clock is 1 and copies the master. At the rising edge the master closes, holding the value DD had at that moment, and the slave opens and shows it; while the clock is 1, DD may change, but the master is closed.

def d_latch(n, name, d, enable):
    """S = D and E, R = D' and E, into an SR latch of two NOR gates."""
    n.gate(name + "d'", "NOT", d)
    n.gate(name + "s", "AND", d, enable)
    n.gate(name + "r", "AND", name + "d'", enable)
    n.gate(name + "Q", "NOR", name + "r", name + "Q'")
    n.gate(name + "Q'", "NOR", name + "s", name + "Q")
    return name + "Q"


def d_flipflop():
    n = Net("clk", "D")
    n.gate("clk'", "NOT", "clk")
    d_latch(n, "m", "D", "clk'")  # the master follows D while the clock is 0
    d_latch(n, "s", "mQ", "clk")  # the slave copies the master while it is 1
    return n
Listing 28.2. A master–slave D flip-flop from two D latches code/bachelor-1/28-sequential-circuits/listings/d_flipflop.py
$ python d_flipflop.py
clk __________----------__________----------__________----------__________----------
D   _____--------------------_____________________-------____------_________________
Q   ____________-------------------_____________________-------------------_________
D goes 0 -> 1 at edge + k, k = -4..4; stored: 1 1 1 1 1 0 0 0 0
D goes 1 -> 0 at edge + k, k = -4..4; stored: 0 0 0 1 1 1 1 1 1
setup time 2 units, hold time 0 units
clock edge to Q: 2 time units
Output 28.2. The flip-flop under a clock of period 20 time units: QQ changes only after rising edges. Then DD is changed at kk units from an edge, to find the window in which it must not move.

Definition 28.4 (Clock signal, clock period, synchronous circuit)

A clock signal is a signal that alternates between 0 and 1 at a fixed rate; the time between two rising edges is the clock period, and its inverse the clock frequency. A synchronous circuit is made of flip-flops, all driven by the same clock, and of combinational logic between them, with no loop that does not pass through a flip-flop.

In a synchronous circuit the state, the contents of the flip-flops, changes only at the edges; between two edges the combinational logic computes, from the state and the inputs, the next state, which the flip-flops load at the next edge. Every loop is cut by a flip-flop, so the logic between edges is combinational, and Chapter 27 applies to it.

Definition 28.5 (Setup time, hold time)

The setup time of a flip-flop is how long before the clock edge its input must be stable; the hold time, how long after the edge it must stay stable. The clock-to-output delay is the time from the edge to the new output.

The measurement in Output 28.2 finds a setup time of 2 units: a DD that falls one unit before the edge is missed, because the path from DD through the NOT gate into the master is one gate longer than the path of a rising DD. Its hold time is 0, and the clock-to-output delay 2 units. The figure below draws the run.

The run of . Q takes the value D had at each rising edge, two time units later; the shaded windows are the setup times, in which D must not change.
The run of Output 28.2. QQ takes the value DD had at each rising edge, two time units later; the shaded windows are the setup times, in which DD must not change.

The clock period is bounded below. After an edge, the new state appears at the flip-flop outputs a clock-to-output delay later, crosses the combinational logic along its longest delay path (Definition 27.12), and must arrive a setup time before the next edge:

T≥tclock-to-output+tlogic+tsetup.T \geq t_{\text{clock-to-output}} + t_{\text{logic}} + t_{\text{setup}}.

The hold time puts a bound on the shortest path: the new values must not reach the next flip-flops before their hold time has passed. A processor’s clock frequency is set by the slowest path between two of its registers.

28.3 Registers, counters and memory

Definition 28.6 (Register, shift register, counter)

A register is a row of flip-flops on the same clock that store a word; with an enable input, each loads its input when enable is 1 and keeps its value otherwise. A shift register moves its bits one place at each edge, a new bit entering at one end. A counter is a register whose value goes through 0,1,2,…0, 1, 2, \dots at successive edges.

The enable is a multiplexer in front of each flip-flop, choosing between its own output and the new input: a register with enable is a synchronous circuit, its clock never stopped.

def mux(s, x0, x1):
    return ((1 - s) & x0) | (s & x1)  # s' x0 + s x1


def register_next(q, d, enable):
    """Load d when enable is 1, keep q otherwise."""
    return [mux(enable, qi, di) for qi, di in zip(q, d)]


def shift_next(q, serial_in):
    """q[0] is the left bit; every bit moves one place right, serial_in enters left."""
    return [serial_in] + q[:-1]
Listing 28.3. A register with enable and a shift register, one clock edge at a time code/bachelor-1/28-sequential-circuits/listings/shift.py
$ python shift.py
register: D = 1011, enable 0 -> Q = 0000
register: D = 1011, enable 1 -> Q = 1011
register: D = 0110, enable 0 -> Q = 1011
register: D = 0110, enable 1 -> Q = 0110
shift register, edge 1: in 1 -> 1000
shift register, edge 2: in 1 -> 1100
shift register, edge 3: in 0 -> 0110
shift register, edge 4: in 1 -> 1011
shift register, edge 5: in 0 -> 0101
shift register, edge 6: in 0 -> 0010
Output 28.3. Loading only when enabled; four bits entering one by one, then moving on.

A shift register turns a stream of bits into a word (after four edges the bits 1, 1, 0, 1 sit side by side) and back: that is how a serial line, such as a USB cable, carries bytes one bit at a time.

A counter can be built two ways. In a synchronous counter every flip-flop is on the clock, and gates compute the next value: bit 0 flips at every edge, bit 1 when bit 0 is 1, bit 2 when bits 0 and 1 are both 1. In a ripple counter only the first flip-flop sees the clock; each of the others flips when the one before it falls from 1 to 0. It needs no gates, but its bits change one after the other.

def synchronous_next(q):
    """q = (q0, q1, q2), q0 the low bit: add 1 with gates."""
    q0, q1, q2 = q
    return (1 - q0, q1 ^ q0, q2 ^ (q1 & q0))


def synchronous(cycles, d=2):
    """The value seen at each time unit; the clock rises every 10 units."""
    q, seen = (0, 0, 0), []
    for t in range(10 * cycles):
        if t % 10 == d:  # every flip-flop changes d units after the shared edge
            q = synchronous_next(q)
        seen.append(q[0] + 2 * q[1] + 4 * q[2])
    return seen


def ripple(cycles, d=2, n=3):
    """Flip-flop i toggles d units after flip-flop i - 1 falls from 1 to 0."""
    q, seen, changes = [0] * n, [], {}  # changes: time -> the flip-flops to toggle
    for t in range(10 * cycles):
        if t % 10 == 0:
            changes.setdefault(t + d, []).append(0)
        for i in changes.pop(t, []):
            q[i] ^= 1
            if q[i] == 0 and i + 1 < n:  # it fell: the next one toggles d later
                changes.setdefault(t + d, []).append(i + 1)
        seen.append(sum(b << i for i, b in enumerate(q)))
    return seen
Listing 28.4. Two 3-bit counters, watched at every time unit; each flip-flop takes dd units code/bachelor-1/28-sequential-circuits/listings/counter.py
$ python counter.py
synchronous 0 1 | 1 2 | 2 3 | 3 4 | 4 5 | 5 6 | 6 7 | 7 0
            values that are neither the old count nor the new: 0
ripple      0 1 | 1 0 2 | 2 3 | 3 2 0 4 | 4 5 | 5 4 6 | 6 7 | 7 6 4 0
            values that are neither the old count nor the new: 6
ripple, 3 bits: settled 6 units after the edge; synchronous: 2
ripple, 4 bits: settled 8 units after the edge; synchronous: 2
Output 28.4. The values seen between two clock edges. The ripple counter passes through wrong values: from 3 to 4 it shows 2 and 0 on the way.

A circuit that reads the ripple counter while it settles may see 2 or 0 between 3 and 4: a glitch. The synchronous counter has none, and settles in one flip-flop delay whatever its width, where the ripple counter needs nn.

A memory is many registers and a way to choose one. A kk-to-2k2^k decoder (Definition 27.10) turns the address into one selected row; a write loads the row whose decoder output is 1; a read sends the selected row through a multiplexer to the output.

Definition 28.7 (Memory cell)

A memory cell is the circuit that stores one bit of a memory, with an input that selects it for writing and an output that the read logic selects.

def decoder(k):
    """k address bits in, 2^k outputs, exactly one of them 1."""
    c = Circuit(*[f"a{i}" for i in range(k)])
    inv = [c.gate("NOT", f"a{i}") for i in range(k)]
    for row in range(2 ** k):
        lits = [f"a{i}" if row >> i & 1 else inv[i] for i in range(k)]
        c.outputs[row] = c.gate("AND", *lits)
    return c


def multiplexer(k):
    """2^k data inputs, k select inputs: a tree of 2-to-1 multiplexers."""
    c = Circuit(*[f"x{j}" for j in range(2 ** k)], *[f"a{i}" for i in range(k)])
    level = [f"x{j}" for j in range(2 ** k)]
    for i in range(k):
        s, s_inv = f"a{i}", c.gate("NOT", f"a{i}")
        level = [c.gate("OR", c.gate("AND", s_inv, x0), c.gate("AND", s, x1))
                 for x0, x1 in zip(level[::2], level[1::2])]
    c.outputs["out"] = level[0]
    return c
Listing 28.5. The decoder and the multiplexer of a 16-word memory code/bachelor-1/28-sequential-circuits/listings/ram.py
$ python ram.py
write  9 at address  3
write  5 at address 12
write 14 at address  3
read: [3] = 14, [12] = 5, [7] = 0
gates: decoder 20, write enables 16, cells 320, read multiplexers 196; total 552
Output 28.5. A 16×416 \times 4 memory: writes and reads, and its gates.

More than half of the gates are cells, and the share grows with the size: a memory of 2k2^k words of ww bits needs 5⋅2kw5 \cdot 2^k w gates of cells against about 2k2^k for the decoder. Real memories make the cell as small as possible: six transistors in a static memory cell, one transistor and a capacitor, refreshed every few hundredths of a second, in a dynamic one.

History — Magnetic cores

Before memories were made of transistors, the main memory of computers was a plane of tiny rings of magnetic material, threaded on a grid of wires: each ring held one bit as the direction of its magnetisation, and the current in one row wire and one column wire together selected a single ring, a decoder made of physics. Jay Forrester described the three-dimensional arrangement in 1951, and core memory was the main memory of most computers until the 1970s.

A plane of core memory holding 1024 bits: 32 rows and 32 columns of ferrite rings, each threaded by the wires of its row and its column. Photograph: Konstantin Lanzet, CC BY-SA 3.0.
A plane of core memory holding 1024 bits: 32 rows and 32 columns of ferrite rings, each threaded by the wires of its row and its column. Photograph: Konstantin Lanzet, CC BY-SA 3.0.

28.4 Finite-state machines

Every synchronous circuit is the same object seen from far: a state, kept in flip-flops; an input at each clock cycle; a next state and an output computed from them. Mathematics names it.

Definition 28.8 (Finite-state machine)

A finite-state machine has a finite set of states, one of them initial, a finite input alphabet Σ\Sigma, an output alphabet, and a transition function that gives, for each state qq and input symbol aa, the next state δ(q,a)\delta(q, a). It reads one symbol per step and produces one output per step.

Definition 28.9 (Moore machine, Mealy machine, state diagram, state encoding)

In a Moore machine the output is a function λ(q)\lambda(q) of the state; in a Mealy machine it is a function λ(q,a)\lambda(q, a) of the state and the input, attached to the transition. A state diagram draws the states as circles and each transition as an arrow labelled by its input (and, for a Mealy machine, its output, as a/oa/o). A state encoding gives each state a distinct word of bits, to be stored in flip-flops.

For an input word a1…ana_1 \dots a_n a Mealy machine outputs λ(q0,a1)…λ(qn−1,an)\lambda(q_0, a_1) \dots \lambda(q_{n-1}, a_n) and a Moore machine λ(q1)…λ(qn)\lambda(q_1) \dots \lambda(q_n), where qiq_i is the state after ii symbols. Two machines are equivalent if they give the same output word for every input word. Both kinds compute the same things:

Proposition 28.10 (Moore and Mealy are equivalent)

For every Moore machine there is an equivalent Mealy machine with the same states, and for every Mealy machine with state set QQ and output alphabet OO there is an equivalent Moore machine with at most ∣Q∣⋅∣O∣|Q| \cdot |O| states.

Proof. Moore to Mealy: put on each transition the output of the state it enters, λ′(q,a)=λ(δ(q,a))\lambda'(q, a) = \lambda(\delta(q, a)). Mealy to Moore: take the pairs (q,o)(q, o) as states, meaning “in qq, having just output oo”, with δ′((q,o),a)=(δ(q,a),λ(q,a))\delta'((q, o), a) = (\delta(q, a), \lambda(q, a)) and output oo. Both machines go through the same states qiq_i, and the output read after step ii is λ(qi−1,ai)\lambda(q_{i-1}, a_i) in both; Exercise 28.10 writes the induction out. ∎

def mealy_to_moore(m, alphabet):
    """A Moore state (q, o): in q, having just output o. Only the reachable ones."""
    first = (m.start, 0)
    states, todo, delta = {first}, [first], {}
    while todo:
        q, o = todo.pop()
        for a in alphabet:
            nxt = m.delta[q, a]
            delta[(q, o), a] = nxt
            if nxt not in states:
                states.add(nxt)
                todo.append(nxt)
    return Moore(first, delta, {s: s[1] for s in states})


def moore_to_mealy(m):
    """Output, on a transition, the output of the state it enters."""
    return Mealy(m.start, {(q, a): (r, m.out[r]) for (q, a), r in m.delta.items()})
Listing 28.6. The two conversions, keeping only the reachable pairs code/bachelor-1/28-sequential-circuits/listings/moore_mealy.py

The example is a sequence detector: it reads bits and outputs 1 exactly when the last three were 1,0,11, 0, 1. Overlaps count: in 1010110101 it fires twice. Its Mealy states remember the longest end of the input that is a beginning of 101101: nothing, 11, or 1010.

$ python moore_mealy.py
Moore ( -, 0) --0--> ( -, 0)
Moore ( -, 0) --1--> ( 1, 0)
Moore ( 1, 0) --0--> (10, 0)
Moore ( 1, 0) --1--> ( 1, 0)
Moore ( 1, 1) --0--> (10, 0)
Moore ( 1, 1) --1--> ( 1, 0)
Moore (10, 0) --0--> ( -, 0)
Moore (10, 0) --1--> ( 1, 1)
Mealy states: 3, Moore states: 4
Mealy and Moore agree on all 2047 words of length <= 10: True
and the Mealy machine made back from it: True
on 0110101101: [0, 0, 0, 0, 1, 0, 1, 0, 0, 1]
Output 28.6. The Moore machine made from the Mealy detector of 101: the state (1,1)(1, 1) is new, the state 11 entered with an output of 1. Both agree on every word of up to ten bits.
The detector of 101. Left, the Mealy machine: the 1 is output on the transition from 10 on input 1. Right, the Moore machine: the 1 is the output of the state 1/1, which splits the state 1 in two.
The detector of 101. Left, the Mealy machine: the 1 is output on the transition from 1010 on input 1. Right, the Moore machine: the 1 is the output of the state 1/11/1, which splits the state 11 in two.

From a state diagram to a circuit. Four steps make a machine into a synchronous circuit. Encode the states in ⌈log⁡2∣Q∣⌉\lceil \log_2 |Q| \rceil bits, one flip-flop per bit; write the truth tables of the next-state bits and of the output, as functions of the state bits and the input; simplify them (Section 27.2); and connect the logic’s outputs to the flip-flops’ inputs. Unused codes are don’t-cares.

$ python detector.py
A+ = Bx' + AB'x
B+ = x
z  = AB
gates: 6, flip-flops: 2
circuit = machine on all 8191 words of length <= 12: True
Output 28.7. The Moore detector with (ε,0)=00(\varepsilon, 0) = 00, (1,0)=01(1, 0) = 01, (10,0)=10(10, 0) = 10, (1,1)=11(1, 1) = 11; AA is the high state bit, BB the low one, xx the input. The circuit is checked against the machine.

B+=xB^+ = x says that the low state bit is just the last input, a one-bit shift register; z=ABz = AB needs one gate. A different encoding gives different equations, sometimes better ones; one-hot encoding, one flip-flop per state, spends flip-flops to make the logic trivial (Exercise 28.9).

28.5 The control of a small processor

The toy machine of the earlier books executes an instruction in one step of its simulator. Hardware cannot: reading the two bytes of the instruction, reading or writing memory, and changing registers take several clock cycles, and something must order them. A processor is two parts.

Definition 28.11 (Datapath, control unit)

The datapath of a processor is the part that holds and transforms data: registers, the ALU, the buses and multiplexers between them, and the connection to memory. The control unit is a finite-state machine that, at each clock cycle, sends the datapath the signals that choose which register transfer happens: which register is loaded, from which source, with which ALU operation.

The datapath of the toy machine has the four registers, the program counter PC, the stack pointer SP, the flags, and two instruction registers IR0 and IR1 for the two bytes of the current instruction; its ALU is that of Definition 27.11 on eight bits, which the program computes with integer arithmetic, except that, as in the toy machine, the flag C after a subtraction is the borrow. The control unit is a Moore machine: each state names the register transfers it orders. Its next state depends on the state, on the operation code in IR0, and, for a conditional jump, on the flags.

CONTROL = {
    "FETCH0": ("IR0 <- M[PC]", "PC <- PC+1"),
    "FETCH1": ("IR1 <- M[PC]", "PC <- PC+1"),
    "DECODE": (),
    "LOADI": ("R <- IR1",), "LOAD": ("R <- M[IR1]",), "STORE": ("M[IR1] <- R",),
    "ALU_RR": ("R <- ALU(R, S)",), "ALU_RI": ("R <- ALU(R, IR1)",),
    "ALU_R": ("R <- ALU(R)",), "CMP": ("FLAGS <- ALU(R, S)",),
    "JUMP": ("PC <- IR1",), "IN": ("R <- IN",), "OUT": ("OUT <- R",),
    "LOADR": ("R <- M[S]",), "STORER": ("M[S] <- R",),
    "PUSH1": ("SP <- SP-1",), "PUSH2": ("M[SP] <- R",),
    "POP": ("R <- M[SP]", "SP <- SP+1"),
    "CALL1": ("SP <- SP-1",), "CALL2": ("M[SP] <- PC", "PC <- IR1"),
    "RET": ("PC <- M[SP]", "SP <- SP+1"),
    "HALT": ("PC <- PC-2",), "STOP": (),
}
GROUP = {"ADD": "ALU_RR", "SUB": "ALU_RR", "AND": "ALU_RR", "OR": "ALU_RR",
         "XOR": "ALU_RR", "ADDI": "ALU_RI", "NOT": "ALU_R", "SHL": "ALU_R",
         "SHR": "ALU_R", "JMP": "JUMP", "PUSH": "PUSH1", "CALL": "CALL1",
         "NOP": "FETCH0"}
TAKEN = {"JZ": ("Z", 1), "JNZ": ("Z", 0), "JN": ("N", 1), "JC": ("C", 1)}
AFTER = {"FETCH0": "FETCH1", "FETCH1": "DECODE", "PUSH1": "PUSH2", "CALL1": "CALL2",
         "HALT": "STOP", "STOP": "STOP"}


def next_state(state, op, flags):
    """The control unit's next state, from its state, the opcode and the flags."""
    if state != "DECODE":
        return AFTER.get(state, "FETCH0")
    if op in TAKEN:
        flag, value = TAKEN[op]
        return "JUMP" if flags[flag] == value else "FETCH0"
    return GROUP.get(op, op)
Listing 28.7. The control unit of the toy machine: the transfers each state orders, and the next-state function code/bachelor-1/28-sequential-circuits/listings/toy_control.py

R is the register named in the first byte, S the one named in the second, and M[...] the memory. FETCH0 and FETCH1 read the two bytes of the instruction; DECODE chooses the execute state from the operation code; each execute state goes back to FETCH0. A jump not taken goes straight back too.

def run(mem, inputs, trace=None, max_cycles=100_000):
    """Clock the control unit and the datapath; compare with the shared simulator after
    every instruction. Returns (instructions, cycles)."""
    d, ref, state = Datapath(mem, inputs), Machine(mem, inputs), "FETCH0"
    instructions = cycles = 0
    while state != "STOP" and cycles < max_cycles:
        for transfer in CONTROL[state]:
            d.do(transfer)
        if trace:
            trace(cycles, state, d)
        cycles += 1
        state = next_state(state, OPS[d.ir0 // 4][0], d.flags)
        if state in ("FETCH0", "STOP"):  # an instruction is over
            instructions += 1
            ref.step()
            assert d.snapshot() == (ref.pc, ref.sp, ref.reg, ref.flags, ref.mem,
                                    ref.outputs)
    return instructions, cycles
Listing 28.8. Clocking the two parts, and comparing the datapath with the simulator after every instruction code/bachelor-1/28-sequential-circuits/listings/toy_control.py
$ python toy_control.py
abs_value         7 instructions   28 cycles, as the simulator after each one
call_square      19 instructions   77 cycles, as the simulator after each one
count_down       12 instructions   47 cycles, as the simulator after each one
divide           78 instructions  298 cycles, as the simulator after each one
gcd              26 instructions   98 cycles, as the simulator after each one
max2              6 instructions   24 cycles, as the simulator after each one
max3             12 instructions   47 cycles, as the simulator after each one
max_array        53 instructions  206 cycles, as the simulator after each one
multiply         41 instructions  162 cycles, as the simulator after each one
self_modify       5 instructions   20 cycles, as the simulator after each one
shift_multiply   35 instructions  135 cycles, as the simulator after each one
sum              17 instructions   67 cycles, as the simulator after each one
sum_array        35 instructions  139 cycles, as the simulator after each one
times_ten         9 instructions   36 cycles, as the simulator after each one
in all: 355 instructions, 1384 cycles, 3.90 cycles per instruction
Output 28.8. The programs of the earlier books, run by the control unit and its datapath; after every instruction the registers, flags, memory and outputs are those of the toy machine’s simulator.
The control unit of , some execute states left out: four states per instruction for most (two fetch states, decode, one execute state), three for a jump not taken, five for PUSH and CALL. The program counts 3.9 cycles per instruction on average.
The control unit of Listing 28.7, some execute states left out: four states per instruction for most (two fetch states, decode, one execute state), three for a jump not taken, five for PUSH and CALL. The program counts 3.9 cycles per instruction on average.

The control unit has 23 states, so five flip-flops encode it, and its next-state and output functions are combinational logic of the state, six bits of operation code and three flags, which Section 28.4 turns into gates. Large instruction sets made those functions unmanageable; the answer, microprogrammed control, stores the control signals of each state as a word in a small read-only memory, the microprogram, addressed by the state, so that the control unit is itself a tiny computer reading a table. Many processors since have been built that way, and many have gone back to gates when speed mattered more than the size of the instruction set.

28.6 Exercises

Exercise 28.1 ★

An SR latch starts with Q=0Q = 0. Its inputs (S,R)(S, R) take the values 1010, 0000, 0101, 1010, 0000, each held long enough for the latch to settle. Give QQ after each.

Solution

Solution of Exercise 28.1.

Q=1Q = 1 (set), 11 (hold), 00 (reset), 11 (set), 11 (hold).

Exercise 28.2 ★

The synchronous 3-bit counter of Listing 28.4 holds 5. Give its value after each of the next five clock edges, and which bits flip at each.

Solution

Solution of Exercise 28.2.

6, 7, 0, 1, 2. From 5 (101101) bits 0 and 1 flip; from 6 bit 0; from 7 all three; from 0 bit 0; from 1 bits 0 and 1. Bit ii flips when all the bits below it are 1.

Exercise 28.3 ★

What does the Moore detector of Output 28.6 output on the input word 1101011011010110? Give the states it goes through.

Solution

Solution of Exercise 28.3.

The states are ε/0\varepsilon/0, then 1/01/0, 1/01/0, 10/010/0, 1/11/1, 10/010/0, 1/11/1, 1/01/0, 10/010/0, and the output word 0001010000010100: the detector fires at the fourth and the sixth bit, the second 101101 overlapping the first.

Exercise 28.4 ★

A 4-bit shift register as in Listing 28.3 holds 10101010. The bits 1,1,0,01, 1, 0, 0 enter at four edges. Give its contents after each.

Solution

Solution of Exercise 28.4.

11011101, 11101110, 01110111, 00110011: each bit enters on the left and the rightmost one leaves.

Exercise 28.5 ★★

A circuit compares the 3-bit ripple counter of Output 28.4 with 2, and sounds a bell when they are equal. The counter goes from 0 to 7 once. How many times does the bell sound, and when? Repair the design.

Solution

Solution of Exercise 28.5.

Twice. Once rightly, while the count is 2; once wrongly, between 3 and 4, where the counter shows 2 for dd time units (Output 28.4). Two repairs: use the synchronous counter, whose bits change together; or feed the comparator’s output into a flip-flop on the same clock, so that the bell sees it only at the edges, after the value has settled.

Exercise 28.6 ★★

This traffic light stops with an error on the second input word. Explain why, and complete the machine.

DELTA = {("green", 0): "green", ("green", 1): "amber",
         ("amber", 0): "red", ("amber", 1): "red",
         ("red", 0): "green"}
SHOWS = {"green": "cars go", "amber": "cars slow", "red": "people cross"}


def run(word, state="green"):
    shown = []
    for button in word:
        state = DELTA[state, button]
        shown.append(SHOWS[state])
    return shown
Listing 28.9. A traffic light code/bachelor-1/28-sequential-circuits/listings/exo_incomplete.py
$ python exo_incomplete.py
['cars go', 'cars slow', 'people cross', 'cars go', 'cars go']
KeyError: ('red', 1)
Output 28.9. The two runs.
Solution

Solution of Exercise 28.6.

The pair ("red", 1) has no transition: the state diagram leaves out what happens when someone presses the button while people cross, and the first word never does that. A finite-state machine must have a transition for every state and every input symbol. Add ("red", 1): "green" (the press is ignored, the light goes on), or keep the light red one more period; either is a decision, and the test should check that the table has 3×23 \times 2 entries.

Exercise 28.7 ★★

Build the Mealy detector of 01100110, overlaps allowed, and test it on every word of up to 12 bits against the definition.

Solution

Solution of Exercise 28.7.

def check(longest=12):
    m = detector([0, 1, 1, 0])
    for w in all_words((0, 1), longest):
        want = [int(w[i - 3:i + 1] == (0, 1, 1, 0)) if i >= 3 else 0
                for i in range(len(w))]
        if m.run(w) != want:
            return False
    return True
The detector, checked against the definition code/bachelor-1/28-sequential-circuits/exercises/detect_0110.py

The detector of Listing 28.10, built for 01100110, has the states ee, 00, 0101, 011011; after 01100110 it goes to 00, since the last 0 begins a new pattern. It agrees with the definition on all 8191 words.

Exercise 28.8 ★★

Design a synchronous counter modulo 6 on three D flip-flops: the next-state equations, simplified with the codes 6 and 7 as don’t-cares, and a check that it counts 0,1,…,5,0,…0, 1, \dots, 5, 0, \dots.

Solution

Solution of Exercise 28.8.

def equations():
    """A+, B+, C+ as functions of (A, B, C)."""
    return [minimal_sop([q for q in range(6) if (q + 1) % 6 >> bit & 1], [6, 7], 3)
            for bit in (2, 1, 0)]
The next-state equations code/bachelor-1/28-sequential-circuits/exercises/mod6.py

The program finds A+=BC+AC′A^+ = BC + AC', B+=BC′+A′B′CB^+ = BC' + A'B'C, C+=C′C^+ = C': 9 gates. From 5 (101101): A+=0+0=0A^+ = 0 + 0 = 0, B+=0+0=0B^+ = 0 + 0 = 0, C+=0C^+ = 0, back to 0; without the don’t-cares the equations are longer. The run prints 0,1,…,5,0,…0, 1, \dots, 5, 0, \dots.

Exercise 28.9 ★★

How many flip-flops does a machine with kk states need with a binary encoding? With one-hot encoding? For the control unit of Listing 28.7, compare, and say what one-hot encoding buys.

Solution

Solution of Exercise 28.9.

⌈log⁡2k⌉\lceil \log_2 k \rceil with a binary encoding, kk with one-hot. The control unit has 23 states: 5 flip-flops against 23. One-hot buys simple logic: the output signals are ORs of the states that order them, with no decoding of the state, and the next-state input of each flip-flop is an OR of the transitions entering its state. Hardware designers often pay the flip-flops for that speed.

Exercise 28.10 ★★★

Prove by induction on the length of the input word that the conversions of Proposition 28.10 give equivalent machines.

Solution

Solution of Exercise 28.10.

Mealy MM to Moore M′M': let qiq_i be the state of MM after a1…aia_1 \dots a_i and oi=λ(qi−1,ai)o_i = \lambda(q_{i-1}, a_i) its ii-th output. Claim: M′M' is in (qi,oi)(q_i, o_i) after ii symbols (i≥1i \geq 1). For i=1i = 1, δ′((q0,0),a1)=(δ(q0,a1),λ(q0,a1))=(q1,o1)\delta'((q_0, 0), a_1) = (\delta(q_0, a_1), \lambda(q_0, a_1)) = (q_1, o_1). If it holds for ii, then δ′((qi,oi),ai+1)=(qi+1,oi+1)\delta'((q_i, o_i), a_{i+1}) = (q_{i+1}, o_{i+1}). So the ii-th output of M′M', the output of the state entered, is oio_i. Moore MM to Mealy M′M': both machines go through the same states, by induction since they have the same δ\delta; the ii-th output of M′M' is λ(δ(qi−1,ai))=λ(qi)\lambda(\delta(q_{i-1}, a_i)) = \lambda(q_i), the ii-th output of MM. In both directions the output is not delayed: the Mealy output on the transition into qiq_i and the Moore output of qiq_i are read after the same symbol.

Exercise 28.11 ★★★

In a synchronous circuit the flip-flops have a clock-to-output delay of 50 ps, a setup time of 30 ps and a hold time of 10 ps; every gate takes 25 ps. Between two registers the longest path has 12 gates and the shortest 2. What is the highest clock frequency? Is the hold time respected? What if the shortest path had no gate?

Solution

Solution of Exercise 28.11.

T≥50+12×25+30=380T \geq 50 + 12 \times 25 + 30 = 380 ps, so at most 1/380 ps≈2.631 / 380\,\text{ps} \approx 2.63 GHz. The earliest change at a flip-flop input comes 50+2×25=10050 + 2 \times 25 = 100 ps after the edge, well after the 10 ps hold time. With no gate it comes after 50 ps, still enough: the clock-to-output delay itself protects the hold time, unless the clock reaches the two flip-flops at different times.

Exercise 28.12 ★★★

A vending machine sells an item for 3; at each clock cycle a coin of 1 or 2, or none, is inserted. Draw its Mealy machine (outputs: give the item, give back 1), derive simplified next-state and output equations, and simulate the circuit against the machine on every sequence of up to eight coins.

Solution

Solution of Exercise 28.12.

def machine(credit, coin):
    """The state diagram, as a function: (next credit, v, r)."""
    total = credit + coin
    return (0, 1, total - 3) if total >= 3 else (total, 0, 0)
The state diagram, as a function code/bachelor-1/28-sequential-circuits/exercises/vending.py

The credit is 0, 1 or 2 (AB=00,01,10AB = 00, 01, 10); with coins c1c0=00,01,10c_1 c_0 = 00, 01, 10, the code 11 and the credit 3 are don’t-cares. The program finds A+=Bc0+A′B′c1+Ac1′c0′A^+ = Bc_0 + A'B'c_1 + Ac_1'c_0', B+=Bc1′c0′+A′B′c0B^+ = Bc_1'c_0' + A'B'c_0, v=Bc1+Ac0+Ac1v = Bc_1 + Ac_0 + Ac_1, r=Ac1r = Ac_1: 16 gates, and the circuit agrees with the machine on all 9841 sequences of up to eight coins.

28.7 Problem: A combination lock

Problem 28.1

Weekend problem — A combination lock

A lock has two keys, 0 and 1, and opens when the last four keys pressed are 1,0,1,11, 0, 1, 1. The program builds its Mealy machine from the pattern, converts it to a Moore machine, finds for each pair of states a word that tells them apart, and turns both machines into circuits, checked on every word of up to 12 keys.

def detector(pattern):
    """Mealy machine: the state is the longest prefix of the pattern that ends the
    keys pressed so far; output 1 when the whole pattern has just been pressed."""
    prefixes = [tuple(pattern[:i]) for i in range(len(pattern))]
    delta = {}
    for p in prefixes:
        for a in KEYS:
            w = p + (a,)
            done = int(w == tuple(pattern))
            nxt = next(w[i:] for i in range(len(w) + 1) if w[i:] in prefixes)
            delta[p, a] = (nxt, done)
    return Mealy((), delta)
Listing 28.10. The detector of any pattern: states are the prefixes of the pattern code/bachelor-1/28-sequential-circuits/listings/lock.py
$ python lock.py
Mealy: 4 states: e, 1, 10, 101
  6 pairs of states, each with a word telling them apart:
    e~1 '011', e~10 '11', e~101 '1', 1~10 '11', 1~101 '1'
    10~101 '1'
  A+ = Bx' + AB'x
  B+ = x
  z  = ABx
  flip-flops 2, gates 6; circuit = machine on all words of up to 12 keys: True
Moore: 5 states: e/0, 1/0, 10/0, 101/0, 1/1
  10 pairs of states, each with a word telling them apart:
    e/0~1/0 '011', e/0~10/0 '11', e/0~101/0 '1', e/0~1/1 '', 1/0~10/0 '11'
    1/0~101/0 '1', 1/0~1/1 '', 10/0~101/0 '1', 10/0~1/1 '', 101/0~1/1 ''
  A+ = BCx
  B+ = Cx' + BC'x + Ax'
  C+ = C'x + B'x
  z  = A
  flip-flops 3, gates 11; circuit = machine on all words of up to 12 keys: True
Output 28.10. The two machines, the words that distinguish their states (ee is the empty prefix; in the Moore machine p/op/o is the prefix pp entered with output oo), and their circuits.

Part I — The Mealy machine.

  1. Draw the Mealy machine of the output: four states, eight transitions.
  2. Why is the next state of 101101 on key 1 the state 11, and not ee?
  3. Which line of the listing finds that next state, and how?
  4. Run the machine by hand on 10110111011011. When does the lock open?
  5. Why is the machine complete: why does every state have a transition for both keys?
  6. The output is 1 on a transition. When, exactly, should the bolt move?

Part II — The Moore machine.

  1. Draw the Moore machine; which state is new?
  2. Why does the conversion give five states and not 4×2=84 \times 2 = 8?
  3. On the same word 10110111011011, compare the outputs of the two machines step by step.
  4. Why do the pairs involving 1/11/1 need only the empty word?
  5. Explain why a word that tells two states apart proves that no equivalent machine can merge them.
  6. Conclude that four Mealy states and five Moore states are each the fewest possible.

Part III — Circuits.

  1. Give the binary encodings the program uses, in the order of the output.
  2. Check the Mealy equation B+=xB^+ = x on two transitions.
  3. Why may the Moore equations use the codes 5, 6 and 7 freely?
  4. Why is the Moore output z=Az = A, with no gate at all?
  5. Count the gates of each circuit from its equations, as the program does.
  6. Which circuit is faster from key to output, and why does the answer not depend only on gates?

Part IV — Checking.

  1. How many words of up to 12 keys are there?
  2. Show that if a circuit and a machine have the same output and next state on every reachable state and key, they agree on every word, of any length.
  3. Every state is reachable in at most four keys. Why do the words of up to 12 keys check every state and key, and more?
  4. What would a wrong encoding (two states with the same code) do to the check?
  5. A real keypad has ten keys. How does the machine change, and how many words of up to 12 keys are there now?
  6. State the named result, Mealy saves a state, with the counts of states, flip-flops and gates.
Solution

Solution of Problem 28.1.

1. States e,1,10,101e, 1, 10, 101. From ee: 0→e0 \to e, 1→11 \to 1. From 11: 0→100 \to 10, 1→11 \to 1. From 1010: 0→e0 \to e, 1→1011 \to 101. From 101101: 0→100 \to 10, 1/1→11/\mathbf{1} \to 1. Every other output is 0.

2. After 10111011, the longest end of the input that begins the pattern is the last 11: a new attempt has begun. ee would forget it, and miss the lock opening on 10110111011011.

3. Line 22: it tries the ends of ww from the longest to the empty one, and keeps the first that is a prefix.

4. The outputs are 00010010001001: the lock opens after the fourth and the seventh keys, the second 10111011 sharing a 1 with the first.

5. The double loop over prefixes and keys makes one entry per pair, and next always finds an end, the empty one at worst.

6. As the fourth key is pressed: the output is 1 during the clock cycle of that key, before the next edge.

7. e/0,1/0,10/0,101/0e/0, 1/0, 10/0, 101/0 and the new 1/11/1, the state 11 entered by the opening transition.

8. Only reachable pairs are kept: only 11 is ever entered with an output of 1.

9. Both print 00010010001001, as Proposition 28.10 says; the Moore machine shows each 1 as the output of the state 1/11/1.

10. 1/11/1 is the only state with output 1, so its own output already differs from every other’s.

11. If two states differ on a word ww, two inputs leading to them (here the prefixes that name them) followed by ww give different outputs; a machine in the same state after both would give the same.

12. The printed words separate all (42)=6\binom{4}{2} = 6 Mealy pairs and all (52)=10\binom{5}{2} = 10 Moore pairs, so no two states can be merged: in a Moore machine, after the words 11 and 10111011 the futures are equal but the current outputs differ.

13. Mealy: e=00e = 00, 1=011 = 01, 10=1010 = 10, 101=11101 = 11. Moore: e/0=000e/0 = 000, 1/0=0011/0 = 001, 10/0=01010/0 = 010, 101/0=011101/0 = 011, 1/1=1001/1 = 100.

14. From 1010 (AB=10AB = 10) on 1 to 101101 (1111): B+=1B^+ = 1. From 101101 on 0 to 1010: B+=0B^+ = 0. The low bit records whether the last key was 1.

15. No state has them, so their rows never occur: don’t-cares.

16. Only 1/11/1 has A=1A = 1, and the codes 5 to 7 are don’t-cares.

17. Mealy: NOT xx, NOT BB, ANDs Bx′Bx', AB′xAB'x, ABxABx, one OR: 6. Moore: NOTs of BB, CC and xx, six ANDs and two ORs: 11.

18. The Mealy output is one AND gate away from the key, within the same cycle; the Moore output comes from a flip-flop, one clock edge later but free of the input’s glitches. Timing depends on the clock as much as on gates.

19. 213−1=81912^{13} - 1 = 8191, the empty word included.

20. By induction on the length: they start in the same state, and if they are in the same state after ii keys, equal next-state functions put them in the same state after i+1i + 1, with the same output.

21. Every state followed by every key appears within the first five keys of some word, so the check covers every reachable (state, key) pair, and 20 extends it to every length.

22. Two states with one code would merge them, and some word in the check, such as the distinguishing word following the two prefixes, would show a difference.

23. Keys 2 to 9 send every state back to ee (they begin no attempt); the states stay the same. There are (1013−1)/9≈1.1×1012(10^{13} - 1) / 9 \approx 1.1 \times 10^{12} words of up to 12 keys; 20 and 21 make a check of all states and keys enough.

24. Mealy saves a state: the lock needs 4 Mealy states and 5 Moore states, each number minimal by the distinguishing words; the circuits need 2 flip-flops and 6 gates against 3 flip-flops and 11 gates.

এই অধ্যায়ে সংজ্ঞায়িত পরিভাষা-শব্দ

পরিভাষায় সব 1050 টি শব্দ দেখো