Memory and Time
How can a circuit of gates remember, and what does remembering cost?
The part opens with two NAND gates in a loop, which hold a bit where every circuit of Part 3 forgot. Seen as voltages, the cross-coupled inverters are a dynamical system with two stable states and a saddle between them, and the time to leave the saddle grows like the logarithm of one over the starting imbalance. Latches become edge-triggered flip-flops, the clock brings setup and hold times and a top frequency, and 40,000 simulated arrivals show metastability's exponential tail and the two-flip-flop synchronizer that makes it rare. Then the machines that remember are read as mathematics: a state machine is a finite automaton, Myhill and Nerode count its necessary states, and a shift register with feedback multiplies by x over the field with two elements. The part builds Pebble's register file from 480 flip-flops, then static and dynamic memory cells. It ends with Rowhammer, where hammering one DRAM row flips bits in its neighbours, and with what a counting defence can and cannot promise.
What you need. Gates and unit delays from Part 3, the adder of Part 4. Chapter 2 uses a derivative and an eigenvalue, both explained on screen.
- Mathematics, ideas and history
- latches as bistable dynamics, timing, metastability, FSMs, Myhill–Nerode, LFSRs over GF(2), SRAM/DRAM
- What we build or compute
- the register file and memory; a metastability histogram
What you will be able to do
Degree
- Trace an SR latch, a D latch and a master-slave flip-flop through a waveform.
- Compute a circuit's maximum clock frequency from clock-to-Q, logic and setup delays.
- Design a Moore machine for a pattern and build a counter and a register from flip-flops.
Graduate
- Linearize the cross-coupled inverters at the saddle and derive the resolution time.
- Prove the Myhill-Nerode theorem and minimize a DFA by partition refinement.
- Explain an LFSR as multiplication by x modulo a polynomial and say when its period is 2^n - 1.
Research
- Bound the failure probability of a probabilistic Rowhammer defence with a union bound over windows.
- State the Misra-Gries undercount bound and which physical assumptions a counting defence still needs.
Industry
- Compute a synchronizer's MTBF and explain why a single-bit synchronizer does not make a bus coherent.
- Explain DRAM refresh, why Rowhammer breaks the memory abstraction, and what TRR and ECC do about it.
Contents
Each chapter has a home level. Choose a track to see what to read and watch: Degree 28 min · Graduate 45 min · Research 52 min · Industry 31 min.
- 0A circuit that remembersDegree2 min
- 1FeedbackDegree3 min
- 2Two wells and a saddleGraduate3 min
- 3Latches, flip-flops and the clockDegree3 min
- 4How fast can the clock go?Degree3 min
- 5MetastabilityGraduate5 min
- 6Finite-state machinesDegree2 min
- 7Machines and languagesGraduate4 min
- 8Counters and shift registersDegree3 min
- 9Pebble's register fileDegree3 min
- 10Static memoryDegree3 min
- 11Dynamic memoryDegree2 min
- 12When memory leaksIndustry3 min
- 13Clocks, and memory as logicGraduate2 min
- 14Remembering, before chipsDegree2 min
- 15Frontier: defending memoryResearch6 min
- Recap, problems, and where this comes backAll tracks3 min
Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · 中文 · Build the film.
Lecture
The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.
A circuit that remembersDegree2 min
Every circuit in Parts 3 and 4 had the same limitation. Its output depends only on its inputs right now. Change an input, and a few gate delays later the old answer is gone without a trace. An adder cannot remember the last sum, and a circuit like that cannot count, wait, or follow the steps of a program. A computer must remember: the program, the data, where it is in the program. This part is about how a circuit made of the same gates can hold on to a bit, and about what remembering costs.
The trick is a loop. Take two NAND gates, and wire each one's output into the other's input. Every circuit so far flowed from inputs to outputs; this one feeds back on itself, and that changes everything. Push it one way and it stays that way; push it the other way and it stays the other way. With its inputs left alone, it remembers which way it was pushed last. This bistable feedback is the basis of latches and static memory. Dynamic memory will use a different mechanism: stored charge that must be refreshed.
Memory brings something else into the story: time, and a strange risk. A latch is like a ball in a landscape with two valleys. Left is zero, right is one, and the ball rests in one of them. Between them is a ridge. In the ideal symmetric model, a ball can balance on top indefinitely. A real latch can hover near its unstable decision point before noise and imbalance resolve it. There is no fixed settling-time bound that works for every possible input arrival. It is called metastability, and every computer that listens to the outside world has to live with it.
1FeedbackDegree3 min
Here is the latch again, with its inputs named S bar and R bar, for set and reset; the bars mean they act when they are zero. A NAND gate outputs one whenever either of its inputs is zero. So pull S bar to zero, and Q becomes one. Then the lower gate sees R bar equal to one and Q equal to one, so its output, Q bar, becomes zero, and that zero feeds back to hold Q at one. Now let S bar go back to one. Nothing changes: Q bar, still zero, keeps Q at one. The latch remembers that it was set. Pull R bar to zero, and the same story runs the other way: Q becomes zero, and stays zero when R bar is released. One input pattern is forbidden: both at zero forces both outputs to one, which is not a stored value at all, and releasing both at once leaves the latch with no idea which way to fall.
Simulated in this series' library, with every gate taking one tick to respond, here is the whole story. Set, and Q rises one tick later, Q bar one tick after that. Hold, and nothing moves. Reset, and the pair flips back. Then the forbidden input: both outputs go to one. And when both inputs are released on the same tick, something new happens. Each gate sees the other's one, and flips to zero; then each sees the other's zero, and flips back to one. In this perfectly symmetric model they chase each other forever. Real gates are never perfectly matched, so a real latch eventually falls into one state or the other. Which one, and when, is the subject of the next chapter and of chapter five.
Two gates in a loop make a memory. Three inverters in a loop make something else. Each inverter wants its output to be the opposite of its input, and with an odd number of them, going all the way round contradicts itself: there is no consistent binary state. In this unit-delay model, the ring oscillates. A physical ring needs sufficient gain and suitable delays; it also has an unstable analog operating point. A change runs round and round it, and each signal flips every three gate delays, repeating every six. This ring oscillator is how chip makers measure the speed of a new manufacturing process, it is a cheap on-chip clock, and the jitter of free-running rings is one of the sources of true random numbers inside processors. Loops, it turns out, are where circuits get interesting.
2Two wells and a saddleGraduate3 min
To see what really happens inside a latch, stop thinking in zeros and ones. The heart of it is two inverters, each driving the other, and each output is a voltage, v one and v two. An inverter's output does not jump; as Part 3 showed, it charges its wire towards the value its transfer curve f says, with a time constant tau. So the voltages obey two differential equations: each one relaxes towards f of the other. Here f is a smooth inverter curve, a little gentler than a real one so that the picture is easy to see. The latch is now a dynamical system with two variables, and we can draw its whole behaviour at once.
Every point of this square is a possible state of the latch: a voltage on each wire. At every point, the equations give a direction of motion, drawn as a small arrow. The two curves where one voltage stops changing cross in three places, and those are the equilibria. Start the latch anywhere and follow the arrows. Almost every start ends in one of two corners: v one low and v two high, or the reverse. Those are the two stable states, the zero and the one. The third crossing, in the middle, is a saddle: the arrows lead into it along the diagonal and away from it in every other direction. The diagonal is the watershed between the two basins. A latch that starts exactly on it, as an exactly symmetric analog release would, unlike the digital model's oscillation, slides into the saddle and has no reason to leave.
Zoom in on the saddle, where everything about metastability is decided. Near it the equations are almost linear, and their matrix has the inverter's slope off the diagonal. Its two eigenvalues, measured in units of the gate RC time, tell the story. Along the diagonal, where both voltages move together, the eigenvalue is minus four: any common motion dies out. Across the diagonal, along the difference of the voltages, it is plus two: any imbalance grows exponentially. So an imbalance delta grows like delta times e to the lambda t, and the time to reach a clean zero or one is the logarithm of one over delta, divided by lambda. A latch that starts a little off balance resolves quickly. One that starts very nearly balanced takes longer, and as the imbalance shrinks to zero the time grows without bound. A steeper inverter, a larger lambda, makes it faster, but never instant.
3Latches, flip-flops and the clockDegree3 min
An SR latch needs two inputs and has a forbidden one. Gate the data and its complement into the set and reset inputs. Feed the latch from a data input D and an enable E, so that set is D and E, and reset is not D and E. While the enable is one, the latch is transparent: Q follows D, a few gate delays behind. While the enable is zero, the door is shut, and Q holds whatever D was at the moment it closed, no matter what D does afterwards. For stable Boolean inputs, those set and reset requests are mutually exclusive. Real transitions still have gate delays, and data must meet setup and hold around closing. This is the D latch, simulated here gate by gate.
A latch is transparent for as long as its enable is high, and that is a problem when its output feeds logic that feeds back into its input: the signal can race round the loop many times while the door is open. The cure is two latches in a row, enabled by opposite phases of a clock. While the clock is low, the first, the master, follows D, and the second, the slave, holds. When the clock rises, the master shuts, capturing D, and the slave opens, passing the captured value to Q. In the ideal opposite-phase model, the two are not transparent together. Real designs must control phase overlap and satisfy their timing constraints. Here it is, simulated: With data stable around the sampling edge, Q takes the captured value after the rising edge. This is the edge-triggered D flip-flop, and it turns continuous time into discrete steps.
Put flip-flops side by side on the same clock and you have a register. Eight flip-flops make an eight-bit register; each bit samples on the same rising edge and its output settles after its clock-to-Q delay. Now the shape of almost every digital system: registers hold the state; combinational logic, the circuits of Parts 3 and 4, computes the next state from the current state and the inputs; and at each clock edge the registers load it. Between edges the combinational outputs may glitch, but the values sampled by registers must settle for their setup and hold windows. Outputs used asynchronously need separate care. This series' hardware library simulates exactly this picture, one clock cycle at a time, and Pebble is built in it.
4How fast can the clock go?Degree3 min
A flip-flop makes a promise, but only if it is treated well. Around each rising edge there is a small window. D must be steady for a short time before the edge, the setup time, and for a short time after it, the hold time. Inside the window, the flip-flop's master latch is in the middle of closing, and a change there is exactly the balanced push that can leave it on the saddle. And the flip-flop is not instant either: the new value appears at Q a little after the edge, the clock-to-Q delay. These three numbers, from the datasheet of every flip-flop, set the speed limit of a whole processor.
Now the clock. Between two registers sits some combinational logic. At a rising edge, the first register launches new values; they appear after the clock-to-Q delay, ripple through the logic, and must arrive at the second register at least a setup time before the next edge. So one clock period has to hold three things end to end: clock-to-Q, the slowest path through the logic, and the setup time. The fastest clock the circuit can take is one over their sum. For a toy budget, assume a worst-case logic delay of two hundred and ninety picoseconds, forty picoseconds clock-to-Q and thirty for setup. The total is three hundred and sixty picoseconds, or about two point eight gigahertz. Part 4 observed twenty-nine gate delays on tested ALU inputs; that measurement does not certify a worst-case delay or a silicon clock rate. Every gate delay saved in Part 4 shows up here, and Part 7 will cut the path into pieces to go faster still.
One more effect, because a clock signal is a wire too. It reaches different registers at slightly different times; call the difference delta, the clock skew. A late clock at the second register gives the data more time to arrive, which helps the setup inequality. But it hurts the second one, the hold condition: the fastest path from the first register must not change the second register's input before that register has finished capturing its old value. Notice what is missing from that inequality: the clock period. In this timing model, a longer period relaxes setup. It does not relax hold. Use maximum clock-to-Q and logic delays for setup, and minimum delays for hold; a hold failure needs a path or clocking change. So design tools insert extra delay into paths that are too fast, and engineers build balanced trees of wires that deliver the clock to billions of transistors within a few picoseconds of each other.
5MetastabilityGraduate5 min
Inside a single clocked circuit, designers choose the period and paths to meet setup and hold over the specified operating conditions. But signals from outside, a key press, a network packet, a sensor, arrive whenever they like. Here is the flip-flop of chapter three again, simulated gate by gate, with D changing on the very tick of the clock edge. The master latch is caught half shut, with its two halves fighting, and they oscillate for several gate delays before the slave copies out a value. For that time, the binary waveform is not a stable value that downstream logic can safely sample. In a real circuit the voltages hover near the saddle instead of oscillating, but the effect is the same: an output that is late by an amount nobody chose.
How late? Use the dynamical system of chapter two. A data edge arrives at a random moment near the clock edge and leaves the latch with a small random imbalance. Here are forty thousand uniformly sampled initial imbalances, integrated through the analog model until they resolve. Most decide quickly. But the histogram has a long tail. Plot the fraction still undecided on a logarithmic scale, and the tail is a straight line: the probability of taking longer than T falls like e to the minus lambda T, with lambda the saddle's unstable eigenvalue. Waiting one more unit of time makes failure e squared, about seven, times less likely; The analytic saddle model has an unbounded tail; these finite samples illustrate it without validating astronomical failure rates.
Engineers turn this into a single number. The mean time between failures grows exponentially with the time t r allowed for resolving, divided by the latch's time constant tau, and falls with how often the data changes inside the dangerous window around the clock edge. With textbook-scale numbers, twenty-picosecond constants, a one gigahertz clock and data changing a hundred million times a second, a single flip-flop given half a nanosecond to settle fails about once every ten hours. For a chip that runs for years, that is a disaster.
The cure is cheap. Send the outside signal through two flip-flops in a row. The first one may go metastable. But nobody looks at its output until the next clock edge, a whole cycle later, and only the second flip-flop does. That extra cycle adds to the time allowed to resolve, and because the failure rate falls exponentially with that time, the mean time between failures becomes about ten to the eighteen years, hundreds of millions of times the age of the universe, for the price of one cycle of delay. This is a common pattern for a single-bit control signal. Real settling time comes from the implemented path budget. Pulses and multi-bit data need suitable handshakes, encodings or asynchronous FIFOs; independently synchronizing every bus bit does not preserve a word. Thomas Chaney and Charles Molnar measured the effect convincingly in 1973, after years in which many engineers refused to believe in it; forgetting it still produces the rarest and most maddening hardware bugs.
It is tempting to think a better flip-flop could eliminate metastability. It cannot, and a continuous-state model explains why. Plot the time a latch takes to decide against the moment the input changed, relative to the clock. Far from the edge it decides quickly. Near the edge it takes longer, and right at one critical moment, the time is unbounded. Leslie Lamport's 1984 manuscript, published in 2012, calls this Buridan's principle, after the donkey that starved halfway between two bales of hay: a discrete decision based on an input with a continuous range of values cannot always be made in a bounded time. The argument is continuity. For this argument, assume continuous dependence of the device state on its input and a requirement to return the appropriate stable decision for either input class, so if one input leads to zero and another to one, some input in between leads to a state that is neither, for as long as you care to wait. Engineers cannot remove the risk, only make it astronomically small, and that is exactly what the synchronizer does.
6Finite-state machinesDegree2 min
A register and some logic make a finite-state machine: a circuit with a few bits of memory that reacts to a stream of inputs, one per clock cycle. Here is one that watches a stream of bits and raises its output whenever the last four were one, zero, one, one. Each state stands for how much of the pattern has just been seen: nothing, a one, one zero, one zero one, or the whole pattern. The arrows say where each input bit leads. A wrong bit does not always start from scratch: after one zero one, a zero leaves one zero, which is still the start of a match. Its output depends only on the state, which makes it a Moore machine, after Edward Moore's 1956 paper; George Mealy's machines of 1955 let the output depend on the input too, so the response can occur within the cycle.
Feed it the input one zero one one zero one one one zero one zero one one. The highlighted state walks through the diagram one clock cycle per bit, and the output rises exactly three times, each just after a complete one zero one one, including the two that overlap. Thirteen bits of history, and the machine never needed more than five states to keep track of what matters.
7Machines and languagesGraduate4 min
A state machine that only answers yes or no at the end of its input is called a finite automaton, and the set of inputs it says yes to is its language. Here is one for the binary numbers divisible by three, read from the most significant bit. Its state is the number read so far, modulo six: reading a bit b doubles the number and adds b. It accepts when the remainder is zero or three. It works, but it is wasteful. Is six states the fewest a machine for this language can have? A theorem from 1958 answers that question exactly, for every language at once.
John Myhill and Anil Nerode looked at a language from the outside, with no machine at all. Call two prefixes equivalent if no continuation can tell them apart: for every suffix z, x z is in the language exactly when y z is. Their theorem says a language can be recognized by a finite automaton exactly when this equivalence has finitely many classes, and then the smallest automaton has one state per class, no more and no fewer. The proof is short. Any machine must send two inequivalent prefixes to different states, because if they reached the same state every suffix would treat them alike; so a machine has at least as many states as there are classes. And the classes themselves form a machine: reading a bit takes the class of x to the class of x followed by that bit. This is well defined: equivalent prefixes remain equivalent after the same appended bit. For multiples of three, two prefixes are equivalent exactly when they leave the same remainder mod three. Three classes, so three states suffice, and the six-state machine has three it does not need.
There is an algorithm that finds those classes in any machine. Start by splitting the states into two blocks: accepting and rejecting. The empty suffix already distinguishes those two blocks. Then look at each block and ask, for each input bit, which block each state goes to. States that disagree must be split, because some suffix tells them apart. Here states one and four behave alike, and so do two and five, but differently from one and four, so the rejecting block splits in two. Repeat until no block splits. The three blocks that remain, zero and three, one and four, two and five, are exactly the remainders mod three. Merge each block into a single state and you have the minimal machine. Edward Moore's method, used here, is simple; John Hopcroft's refinement of 1971 runs in n log n time for a fixed alphabet. Such algorithms minimize deterministic automata used in lexers and regular-language tools; not every regular-expression engine uses a minimal DFA.
This is the first rung of a ladder that the series climbs in Part 12. Finite automata, with a fixed amount of memory, recognize the regular languages: the patterns of classical regular expressions and finite-state lexers. Features such as backreferences extend some practical regex engines beyond regular languages. Add a stack and you get the machines that parse programming languages. Add an unbounded tape and you are back at Part 1's Turing machine, which can do anything computable. Myhill–Nerode also marks the ladder's first edge. The language of some zeros followed by the same number of ones has infinitely many classes, since zero to the i and zero to the j are told apart by the suffix one to the i. So no finite machine, however clever, can recognize it.
8Counters and shift registersDegree3 min
With registers and a clock, some useful circuits need almost no logic. A counter is a register whose next value is itself plus one: Part 4's adder, fed back. It steps through every number and wraps around, and it is how a processor keeps its place in a program. A shift register needs no logic at all: each flip-flop takes the value of its neighbour at every clock edge, so the whole pattern slides one place per cycle. Every serial link, USB, PCI Express, Ethernet, uses shift registers to turn parallel words into a stream of bits and back. And with one small change, a shift register becomes something remarkable.
Take a four-bit shift register, and instead of feeding it from outside, feed it the exclusive-or of two of its own bits. Each clock cycle, the bits shift along, and the new bit is the exclusive-or of the last two. Start from one zero zero zero and watch the states. It runs through fifteen different patterns, every non-zero four-bit pattern exactly once, in a scrambled-looking order, before coming back to where it started. The all-zero state is the only one missing, since it would stay zero forever. This is a linear-feedback shift register, and the choice of taps corresponds to the polynomial x to the four plus x cubed plus one. With the wrong taps, the cycle would be shorter.
The explanation is algebra over the field with two elements, where one plus one is zero and adding is exclusive-or. Read the register's bits as the coefficients of a polynomial; this is cleanest for the same taps wired in the so-called Galois form, which folds the exclusive-or into the shift. One clock step multiplies that polynomial by x, shifting every coefficient up, and the feedback reduces the result modulo the tap polynomial, exactly as an integer is reduced modulo a number. This quotient is a field when the polynomial is irreducible; reducible polynomials need not give a field. So the states the register visits are the powers of x, and its period is the smallest power of x that comes back to one; either wiring has the same period. The period is the maximum, two to the n minus one, exactly when the polynomial is primitive: when the powers of x run through every non-zero element of the finite field with two to the n elements. Solomon Golomb worked out this theory in the 1950s, and these registers have generated codes, ciphers and test patterns ever since.
9Pebble's register fileDegree3 min
Pebble's instructions name three registers at once: add r three, r one, r two reads two registers and writes a third. So its register file has two read ports and one write port. Sixteen registers of thirty-two flip-flops each, except register zero, which the instruction set defines to be zero and so needs no flip-flops at all. To write, Part 3's decoder turns the four-bit write address into one enable line per register; at the clock edge, the enabled register loads the write data, and every other register, through a multiplexer on each bit, loads its own value back. To read, two trees of multiplexers, each thirty-two bits wide, pick out the two registers named by the read addresses, both in the same cycle.
One subtlety matters as soon as the processor gets faster. The first instruction writes register three; the next one reads it. The register file writes at the clock edge and reads during the cycle, so as long as the second instruction reads in the next cycle, the new value is already sitting in the flip-flops. In the pipelined processors of Part 7, though, one instruction may be reading register three in the very cycle another is writing it. Designs solve this either by writing in the first half of the cycle and reading in the second, or with a bypass: a comparator notices that the read address equals the write address, and a multiplexer hands the new value straight to the output. Those forwarding paths, and when they are not enough, are a large part of Part 7.
In the series' library this register file is a checked circuit model. These are counts in our chosen gate basis, not a transistor-area estimate. Four hundred and eighty flip-flops, and a little under six thousand gates of decoding and multiplexing around them. Two hundred and fifty-six copies were run for sixty-four cycles of random reads and writes, and every value read matched a Python model that simply keeps sixteen variables. Notice where the gates go. Every extra read port is another multiplexer tree, about two thousand gates; every extra write port is another decoder and wider multiplexers on all four hundred and eighty bits. Processors that execute several instructions per cycle need many ports, and their register files become some of the largest and hottest structures on the chip, as Parts 7 and 8 will show.
10Static memoryDegree3 min
A register file of flip-flops is fast but large. For memories of millions of bits, a common compact choice is the six-transistor cell shown here. At its heart is chapter two's latch again: two cross-coupled inverters, four transistors, with two stable states. Two more transistors, switched by a word line, connect the two sides of the latch to a pair of bit lines. Six transistors in all: the static RAM cell, which retains its bit while powered within its operating margins. To read, both bit lines are charged up, and the word line opens the cell; the cell pulls one of them down slightly. That tiny difference is too weak to use directly, so a sense amplifier, which is yet another cross-coupled latch, balanced right on its saddle, falls one way or the other and turns it into a full zero or one. To write, strong drivers force the bit lines, and the cell's small inverters give in.
An idealized regenerative sense amplifier reuses chapter two's instability. It is a latch too, but one that is deliberately parked on its saddle: the two internal nodes are first balanced near an unstable operating point. Real circuits choose suitable bias and common-mode voltages; this normalized phase portrait illustrates the regeneration. Then the bit lines, nudged a few percent apart by the cell, are connected to it. When it is released, the instability that makes metastability dangerous does useful work: the imbalance grows exponentially, and the latch falls quickly to the side it was nudged towards, turning a whisper into a full zero or one. A smaller nudge simply takes longer to resolve, which is chapter five's tail again, and why memory designers specify the smallest signal their amplifiers can read in time.
Memories put their cells in a grid. The address splits in two. The high part goes to a row decoder, which raises one word line, and every cell in that row connects to its bit lines at once. A row of sense amplifiers reads them all, and a multiplexer picks out the bits that were asked for. Many processor caches use SRAM arrays like this, though some use other memory technologies, millions of cells, and Part 9 is about how they are organized. A large server processor carries hundreds of megabytes of it, billions of these cells, and still finds them too few. Fast as it is, static RAM is big: six transistors and their wiring for every bit, so on many chips the caches take more area than the processor cores themselves. Main memory needs something much denser.
11Dynamic memoryDegree2 min
In 1966 Robert Dennard at IBM found a much smaller way to store a bit. One transistor, used as a switch, and one capacitor. The bit is the charge on the capacitor: charged is one, empty is zero. To read it, raise the word line and connect the capacitor to the bit line. But the bit line is far larger than the cell, so the charge spreads out and moves its voltage by only a small fraction of a volt. A sense amplifier detects that. Reading has redistributed the cell's charge and disturbed its stored level, so the sense amplifier restores it immediately. This is dynamic RAM. Intel's successful 1103 appeared in 1970, using an early three-transistor cell. The one-transistor, one-capacitor cell became the dominant dense design later, as semiconductor memory displaced core.
There is a second problem. A capacitor that small is not perfectly isolated, and its charge leaks away, in a fraction of a second for the weakest cells. Left alone, a one would slowly turn into a zero. So the memory refreshes itself: the controller schedules refresh commands, and the chip's internal circuits sense and restore each row, on a fixed schedule, using sixty-four milliseconds as a common normal-temperature example. The required interval depends on device and temperature, and the charge is topped up long before it falls below the threshold. That is why it is called dynamic: the bits survive only because they are constantly rewritten, with time and energy costs that depend on the device, temperature and workload.
12When memory leaksIndustry3 min
As DRAM cells shrank, their neighbours came uncomfortably close. In 2014 Yoongu Kim, Onur Mutlu and their colleagues at Carnegie Mellon and Intel published a disturbing measurement. Pick two rows of memory, and access them alternately, as fast as possible: open one, open the other, again and again. Each time a row is opened, the electrical activity disturbs the rows next to it, and a little charge leaks out of their cells. Do it enough times between two refreshes, and the weakest cells in the row in between, the victim, which the program never touches, lose enough charge to flip. Of a hundred and twenty-nine DDR3 memory modules they tested, a hundred and ten flipped bits, some after only a hundred and thirty-nine thousand activations, well within one sixty-four-millisecond refresh period.
Why did this appear only around 2010? Scaling often shrinks cells and packs rows closer, though vulnerability varies by device and mitigation, and a cell now holds only tens of thousands of electrons, or fewer. Opening a row swings its word line from zero to full voltage, and the electrical coupling into the neighbouring rows, together with charge trapped in the silicon between them, speeds up their leakage a little every time. The sixty-four millisecond refresh interval was chosen for ordinary leakage, with a safety margin, which does not by itself guarantee safety against repeated neighboring-row activity. A reliability margin had quietly become a security boundary, and nobody had been guarding it.
At first it looked like a reliability problem. It is a security problem. In 2015 Mark Seaborn and Thomas Dullien at Google's Project Zero hammered rows until a bit flipped inside a page table, the structure Part 32 uses to keep programs out of each other's memory, and took over the machine. Others did it from JavaScript running in a web page, and from an ordinary Android app. The defences are refreshing more often, counting activations and refreshing a hammered row's neighbours early, and error-correcting codes. These measures need precise scope. TRRespass in 2020 defeated several deployed DDR4 tracking schemes; that does not show that every refresh policy, counter design or error-correcting code fails. The deeper lesson runs through the whole series. Every layer promises something simple; memory promises to hold what you wrote. Rowhammer is what happens when the physics underneath an abstraction leaks through it, and Part 42 meets its relatives.
13Clocks, and memory as logicGraduate2 min
Within a simple synchronous clock domain, the design discipline is a few strict rules. Every flip-flop shares one clock. Every loop passes through a register. Every path meets its setup and hold times, and every crossing from an unrelated clock domain uses an appropriate synchronization protocol. Obey them, and a chip of billions of transistors behaves exactly like a finite-state machine, taking one clean step per tick, simulated cycle by cycle the way this series simulates Pebble. That predictability is worth an enormous amount. The price is that every step waits for the slowest path, even when the work this cycle was easy, and the clock network that reaches every flip-flop can consume a substantial fraction of dynamic power, depending on the chip. Modern chips soften both costs: clock gating switches the clock off to idle blocks, and different parts of a chip run on different clocks, joined by the synchronizers of chapter five.
There is another way: circuits with no clock at all, which signal to each other when they are done. Their basic element, invented by David Muller in the 1950s, is the C-element. When both inputs are one, its output becomes one; when both are zero, zero; when they disagree, it holds its last value. It is a tiny state machine, and like the latch it needs feedback inside. In effect it waits for both of its inputs to agree before it acts, which is exactly what a handshake needs: I am ready, you are ready, go. Asynchronous circuits built this way run each step as fast as that step allows and avoid clock-driven switching while idle, though leakage and other static power remain. They are hard to design and test, so they survive mainly in niches: ultra-low-power chips, the arbiters that decide which of two requests came first, and the boundaries between clock domains.
14Remembering, before chipsDegree2 min
Before chips, computers remembered in ways that sound like science fiction. Delay lines turned bits into pulses of sound travelling down tubes of mercury; a bit was available only at the moment its pulse arrived at the end, so programmers arranged their data around the timing. Maurice Wilkes's EDSAC, at Cambridge in 1949, used them. The Williams tube stored bits as spots of charge on the face of a cathode-ray tube, which had to be redrawn constantly, like DRAM's refresh; the Manchester Baby, the first stored-program computer, ran on one in 1948, with thirty-two words of memory. Then core memory, magnetized rings, which ruled for twenty years, until the Intel 1103 of 1970 put a thousand bits on a chip, and the curve of Moore's law took over. Flash memory, which keeps its charge without power, arrived in the 1980s; it is the storage of Part 34.
Core memory deserves a closer look, because its ideas are still in every memory chip. Each bit was a tiny ring of ferrite, magnetized clockwise or anticlockwise, threaded on a grid of wires. To select one core, send half the current needed to flip a core down its row wire and half down its column wire. Only the core at the crossing feels the full current and flips: two-dimensional selection implemented directly by the magnetic threshold. Reading worked by trying to flip the core to zero and sensing whether it pulsed, which destroyed the value, so every read was followed by a write-back, exactly as in DRAM today. Unlike DRAM, core kept its bits with the power off. Many core arrays were laboriously assembled by hand, and the Apollo guidance computer's programs were woven permanently into a related form, rope memory, wire by wire.
15Frontier: defending memoryResearch6 min
Chapter twelve met Rowhammer: activate one row of memory often enough and bits flip in its neighbours. The research since is an arms race. In 2014 it took a hundred and thirty-nine thousand activations. By 2020, a study of more than fifteen hundred chips, with mitigations disabled, found some newer DDR4 thresholds around ten thousand. The most vulnerable tested device flipped after about four thousand eight hundred activations to each of two aggressors, nine thousand six hundred total. Smaller cells hold less charge and sit closer together, and many tested devices became more vulnerable; this is a measured trend, not a universal rule for every generation. And an attacker has plenty to spend: in the sixty-four milliseconds between refreshes, the idealized per-bank budget is almost one point four million activations, ignoring refresh and mitigation overhead. That is more than a hundred times what it needs.
The simplest defence, proposed with the discovery, is a coin toss. In our simplified variant, refresh all modeled victim neighbors with independent probability p on each activation. Original PARA selects an adjacent row; its selection probability must also be included. An attacker who needs T activations in a row without a refresh succeeds with probability one minus p to the T, about e to the minus p T. For a conservative one-percent annual bound per bank, count every possible ending activation: at most seconds per year divided by the row-cycle time. Multiply that budget by the probability of one unrefreshed run. This union bound also covers overlapping runs; it does not assume those runs are independent. At a hundred and thirty-nine thousand, p is about three hundredths of a percent. At ten thousand it is about four tenths of a percent, and at a thousand, nearly four percent of all activations. Each successful coin toss refreshes the modeled victim neighbors. This union-bound calculation assumes the stated trial and timing model. It illustrates a storage-versus-refresh tradeoff, not a certificate for arbitrary physical disturbance patterns.
The other way is to count. Exact counts for every row would need a counter per row, millions of them. But the problem is one Part 20 will study, finding the frequent items of a stream, and Jayadev Misra and David Gries solved it in 1982 with a handful of counters. Keep k counters. A row that has one adds one; a new row takes a free counter; and when none is free, every counter goes down by one and zero entries are removed. After a modeled victim refresh, remove that row's counter too, so no occupied zero can become negative. Each such decrement cancels k plus one activations, so in a window of W activations there are at most W over k plus one of them, and no row's estimate falls further below its true count. Refresh a row's neighbours when its estimate reaches half the threshold, and the count stays below threshold in this bounded-window, immediate-refresh teaching model if k is at least two W over T. This is a sufficient choice, not a minimum-counter theorem. At the 2014 threshold that is twenty counters per bank. At ten thousand it is two hundred and seventy-seven; at a thousand, nearly three thousand. Graphene, by Park and colleagues in 2020, also builds on frequent-item counting, but uses a spillover-counter implementation and accounts for refresh-window alignment and multiple contributing aggressors. Our toy tracker is not its full physical guarantee.
What happens with too few counters? We simulated an attacker who hammers twenty rows in turn, with ordinary traffic mixed in, for one refresh window, against trackers of different sizes. With four or sixteen counters, the twenty rows keep knocking each other out of the table, nothing is ever refreshed, and each aggressor reaches sixty thousand activations, six times the threshold. This illustrates the many-sided idea investigated by TRRespass in 2020, rather than reproducing its proprietary hardware trackers: the manufacturers' trackers had only a few counters, and hammering many rows at once broke them. Sixty-four counters happened to survive this particular pattern; two hundred and seventy-seven is a sufficient choice from our conservative bound for this one-window model. Measured luck is not a guarantee; a proof is.
Where the research stands. Half-Double in 2021 and RowPress in 2023 show why the physical model matters: disturbance can reach farther rows, and long row-open times can reduce the activation count needed for a flip. PRAC is a framework added to the DDR5 specification in 2024, combining per-row activation counting and controller back-off. Safety still depends on counting, reset, queuing and refresh choices; support is not a universal deployment guarantee. CoMeT in 2024 uses count-min sketches that can overcount but do not undercount under their specified update and reset rules. Hash collisions can increase refresh cost; randomness here does not simply exchange safety for space. As of November 2026, a concrete research task is verifying complete implementations against explicit disturbance and timing models. The June 2026 AutoPRAC preprint reports using model checking to find a reset-policy flaw in a proposed PRAC design. Its result is attributed here, not independently proved. The challenge is a sound guarantee with affordable area, delay, energy and refresh cost.
Recap, problems, and where this comes backAll tracks3 min
What we built in this part. Feedback, and the SR latch that holds a bit. The latch as a dynamical system, with two wells and a saddle, and metastability, whose idealized undecided probability has an exponential tail with no fixed settling-time bound. Flip-flops, the clock, setup and hold, and the synchronizer. Finite-state machines, and the Myhill-Nerode theorem that gives the smallest one. Primitive-feedback LFSRs that visit every nonzero state from a nonzero seed, Pebble's register file, and memory chips that must rewrite their bits to keep them.
Where this comes back. Registers, the clock and the register file become Pebble in Part 6, and Part 7 slices its critical path with more registers. Static and dynamic memory are the raw material of Part 9's memory hierarchy. Finite automata are the first rung of Part 12's languages and of Part 25's limits. Shift registers over the field with two elements return as error-detecting codes in Part 28 and as ciphers in Part 29. Rowhammer returns in virtual memory and in web security, and arbiters, which decide which request came first, return when many processors, and many machines, have to agree.
In practice: unrelated clock-domain crossings need appropriate synchronizers, handshakes or asynchronous FIFOs, with dedicated checks. Servers use error-correcting memory, which repairs single flipped bits, and scrub their memory in the background. Embedded firmware is built from state machines, and so are network protocols, parsers and regular-expression engines, which often contain finite-state components; full parsers and protocol implementations can require more memory.
Seven problems, with full solutions in the part's notes. Pause on any of them. The sixth is a build problem: it asks you to use this series' sequential-circuit library yourself. The last, marked with a star, is a research problem: a bounded-model counting proof, a counter-reset regression, and the harder question of which assumptions a physical defence must satisfy.
Next time: the stored-program computer, the end of act one. We have gates, adders, an ALU, registers and memory. Part 6 puts them together, with a program counter, an instruction decoder and a control unit, into Pebble itself: a thirty-two-bit processor, built from NAND gates, that fetches its own instructions from memory and runs them, including the Euclid program of Part 1.
The books and papers this part follows are on screen and in the notes. Thank you for watching.
Where it goes next. Registers, the clock and the register file become Pebble in Part 6, and Part 7 slices its critical path with more registers. Static and dynamic memory are the raw material of Part 9's memory hierarchy. Finite automata are the first rung of Part 12's languages and Part 25's limits; shift registers over GF(2) return as the error-detecting codes of Part 28 and the ciphers of Part 29; Rowhammer returns with virtual memory and web security.
Key results
The part's results in one place, for revision.
Try it
Lab 5 · A latch, a register file and every shift register of degree 2 to 8
Drive an SR latch of two NAND gates through set, hold, reset and the forbidden input with unit gate delays; write and read Pebble's 16 x 32 register file at random against an array; then find the period of every feedback polynomial of degree 2 to 8 and count those that visit all 2^n - 1 states.
python -m videos.cs.labs 5
needs numpy, scipy, matplotlib · download lab05.py ·
source on GitHubSR latch: Q after set, during hold 1, 1 (remembers 1)
SR latch: Q after reset, during hold 0, 0 (remembers 0)
after releasing S = R together Q = 01010101 (oscillates in the unit-delay model)
register file 480 flip-flops, 5,824 gates (the film: 480 and 5,824)
random reads that matched the model 5,120 of 5,120
maximal-length polynomials, degree 2 ... 8 [1, 2, 2, 6, 6, 18, 16] (phi(2^n - 1) / n: [1, 2, 2, 6, 6, 18, 16])
x^8 + x^4 + x^3 + x^2 + 1 from state 52 period 255 (2^8 - 1 = 255)
Two gates in a loop hold a bit, 480 flip-flops behind a decoder and two multiplexer trees make a register file, and a shift register with the right feedback counts through every state but zero.
The code (117 lines; it asserts its own result)
"""Lab 5: make two NAND gates remember, run Pebble's register file against a model, and count the maximal LFSRs."""
import numpy as np
from videos.coursekit import labs
from explainer.cs.pebble import seq
TITLE = "A latch, a register file and every shift register of degree 2 to 8"
GOAL = ("Drive an SR latch of two NAND gates through set, hold, reset and the forbidden input with unit gate "
"delays; write and read Pebble's 16 x 32 register file at random against an array; then find the period "
"of every feedback polynomial of degree 2 to 8 and count those that visit all 2^n - 1 states.")
TASKS = [
"Release the forbidden input one tick apart (S first, then R) instead of together. Does the latch still oscillate?",
"Build seq.register_file(16, 32, zero_reg=False) and count its flip-flops and gates. What did hard-wiring r0 save?",
"For degree 8, list the periods that are not 255. Which of them divide 255, and what does that say about the polynomial?",
]
def period(poly, n, start=1):
"""The period of the Galois LFSR of the degree-n polynomial (bit i = the coefficient of x^i): multiply the state
by x modulo the polynomial until it returns."""
s, t = start, 0
while True:
s <<= 1
if s >> n & 1:
s ^= poly
t += 1
if s == start:
return t
if t > 1 << n:
return 0 # never returned: the start was not on a cycle through itself
def totient(m):
r, x, p = m, m, 2
while p * p <= x:
if x % p == 0:
while x % p == 0:
x //= p
r -= r // p
p += 1
return r - r // x if x > 1 else r
def run(seed=0):
rng = np.random.default_rng(seed)
lab = labs.Lab()
# 1. the SR latch (inputs active low): set, hold, reset, hold, forbidden, released together
prog = [(1, 1)] * 3 + [(0, 1)] * 4 + [(1, 1)] * 5 + [(1, 0)] * 4 + [(1, 1)] * 5 + [(0, 0)] * 4 + [(1, 1)] * 9
h = seq.sr_latch().run(lambda t: {"S_": prog[t][0], "R_": prog[t][1]}, len(prog), init={"Q": 0, "Qn": 1})
q = h["Q"]
lab.row("SR latch: Q after set, during hold", f"{q[6]}, {q[11]} (remembers 1)")
lab.row("SR latch: Q after reset, during hold", f"{q[15]}, {q[20]} (remembers 0)")
lab.row("after releasing S = R together", f"Q = {''.join(map(str, q[-8:]))} (oscillates in the unit-delay model)")
assert q[9:12] == [1, 1, 1] and h["Qn"][9:12] == [0, 0, 0], "holds the 1 with both inputs released"
assert q[18:21] == [0, 0, 0] and h["Qn"][18:21] == [1, 1, 1], "holds the 0"
assert all(q[t] != q[t + 1] and q[t] == h["Qn"][t] for t in range(len(prog) - 8, len(prog) - 1)), "the race never settles"
ring = seq.ring(5).run(lambda t: {}, 40, init={f"x{i}": i % 2 for i in range(5)})["x0"]
assert ring[:10] == ring[10:20] and ring[:5] != ring[5:10], "a ring of 5 inverters has period 10"
# 2. the register file against an array, 64 machines side by side
rf = seq.register_file(16, 32)
copies, cycles = 64, 40
rf.reset(copies)
model = np.zeros((copies, 16), dtype=np.int64)
idx = np.arange(copies)
reads = 0
for _ in range(cycles):
we, wa, ra, rb = (rng.integers(0, k, copies) for k in (2, 16, 16, 16))
wd = rng.integers(0, 1 << 32, copies)
out = rf.step({"we": we, "wa": wa, "wd": wd, "ra": ra, "rb": rb})
assert np.array_equal(out["a"], model[idx, ra]) and np.array_equal(out["b"], model[idx, rb])
reads += 2 * copies
m = (we == 1) & (wa != 0) # register 0 is hard-wired to zero
model[idx[m], wa[m]] = wd[m]
lab.row("register file", f"{rf.flip_flops} flip-flops, {rf.c.size():,} gates (the film: 480 and 5,824)")
lab.row("random reads that matched the model", f"{reads:,} of {reads:,}")
assert (rf.flip_flops, rf.c.size()) == (480, 5824) and np.all(model[:, 0] == 0)
# 3. every feedback polynomial x^n + ... + 1 of degree 2 to 8
degrees = list(range(2, 9))
maximal, expected, periods8 = [], [], []
for n in degrees:
ps = [period((1 << n) | (mid << 1) | 1, n) for mid in range(1 << (n - 1))]
maximal.append(sum(p == (1 << n) - 1 for p in ps))
expected.append(totient((1 << n) - 1) // n)
periods8 = ps
lab.row("maximal-length polynomials, degree 2 ... 8", f"{maximal} (phi(2^n - 1) / n: {expected})")
assert maximal == expected, "the primitive polynomials number phi(2^n - 1) / n"
start = int(rng.integers(1, 256))
lab.row(f"x^8 + x^4 + x^3 + x^2 + 1 from state {start}", f"period {period(0b100011101, 8, start)} (2^8 - 1 = 255)")
assert period(0b100011101, 8, start) == 255, "a primitive polynomial has full period from every non-zero state"
l4 = seq.lfsr((3, 2), 4) # the same machine as gates and flip-flops, 4 bits
l4.reset(1)
states = [int(l4.step({})["r"][0]) for _ in range(15)]
assert sorted(states) == list(range(1, 16)), "the 4-bit LFSR visits all 15 non-zero states"
lab.note = ("Two gates in a loop hold a bit, 480 flip-flops behind a decoder and two multiplexer trees make a "
"register file, and a shift register with the right feedback counts through every state but zero.")
fig, ax = labs.figure(2, size=(11, 4.2))
t = np.arange(len(prog) + 1)
for k, (name, color) in enumerate((("Qn", labs.PURPLE), ("Q", labs.GOLD), ("R_", labs.BLUE), ("S_", labs.BLUE))):
ax[0].step(t, np.array(h[name] + h[name][-1:]) * 0.7 + k, where="post", color=color)
ax[0].set_yticks([0.35, 1.35, 2.35, 3.35], ["Q̄", "Q", "R̄", "S̄"])
for x, text in ((3, "set"), (7, "hold"), (12, "reset"), (16, "hold"), (21, "both"), (25, "released")):
ax[0].axvline(x, color=labs.GRID, lw=1)
ax[0].text(x + 0.2, 3.95, text, color=labs.MUTED, fontsize=8, va="top")
ax[0].set(title="An SR latch of two NANDs, tick by tick", xlabel="time (gate delays)", ylim=(-0.2, 4.05))
ax[0].grid(False)
ax[1].bar(np.arange(len(periods8)), sorted(periods8), color=[labs.GREEN if p == 255 else labs.BLUE for p in sorted(periods8)], width=1.0)
ax[1].axhline(255, color=labs.MUTED, ls="--", lw=1)
ax[1].set(title=f"Degree 8: periods of all 128 polynomials ({maximal[-1]} reach 255)", xlabel="polynomial (sorted by period)",
ylabel="period from state 1")
ax[1].set_axisbelow(True)
lab.fig = fig
return lab
Now change it
- Release the forbidden input one tick apart (S first, then R) instead of together. Does the latch still oscillate?
- Build seq.register_file(16, 32, zero_reg=False) and count its flip-flops and gates. What did hard-wiring r0 save?
- For degree 8, list the periods that are not 255. Which of them divide 255, and what does that say about the polynomial?
Problems, with solutions
Try each problem before opening its solution.
-
A NOR latch. Build an SR latch from two NOR gates. Which input is forbidden now, and what do the outputs do?
Solution
Q = NOR(R, Q̄), Q̄ = NOR(S, Q), with active-high inputs: S = 1 forces Q̄ = 0 and then Q = 1; R = 1 forces Q = 0; S = R = 0 holds. The forbidden input is S = R = 1, which forces both outputs to 0; an exactly symmetric analog release can remain at the unstable equilibrium; the binary unit-delay model can oscillate instead. Real mismatch and noise usually break the symmetry.
-
The fastest clock. t_cq = 50 ps, t_setup = 30 ps, slowest logic path 420 ps. What is f_max? What if the clock reaches the second register 20 ps late?
Solution
T ≥ 50 + 420 + 30 = 500 ps, so f_max = 2 GHz. With 20 ps of skew in the capturing register's favour, the setup inequality becomes 500 ≤ T + 20, so T ≥ 480 ps and f_max ≈ 2.08 GHz; but the hold check t_cq + t_logic,min ≥ t_hold + 20 ps is now 20 ps harder on the shortest path.
-
Synchronizer design. τ = 25 ps, T₀ = 20 ps, f_clk = 2 GHz, f_data = 50 MHz. How long must a synchronizer wait for an MTBF of 1000 years?
Solution
T₀ f_clk f_data = 20·10⁻¹² · 2·10⁹ · 5·10⁷ = 2·10⁶ s⁻¹, and 1000 years ≈ 3.16·10¹⁰ s. So e^{t_r/τ} ≥ 6.3·10¹⁶, t_r ≥ 25 ps · ln(6.3·10¹⁶) ≈ 25 · 38.7 ps ≈ 0.97 ns: about two 0.5 ns clock cycles, so three flip-flops in this idealized budget (two cycles of resolution time). Real paths must subtract register and routing delays and use characterized constants; this is not an implementation sign-off.
-
A Moore machine. Draw a Moore machine that outputs 1 when the number of 1s read so far is divisible by 3. Is it minimal?
Solution
Three states c₀, c₁, c₂ (the count of 1s mod 3), start c₀, output 1 in c₀ only; a 1 moves cᵢ → cᵢ₊₁, a 0 stays. It is minimal: the suffixes ε, 11 and 1 distinguish the three states pairwise (from c₀, ε is accepted; from c₁, "11" is; from c₂, "1" is), so there are three Myhill–Nerode classes.
-
Palindromes are not regular. Use Myhill–Nerode to show no finite automaton recognizes the palindromes over {0, 1}.
Solution
Take the prefixes xᵢ = 0ⁱ1 for i = 0, 1, 2, …. For i ≠ j the suffix z = 0ⁱ gives xᵢz = 0ⁱ10ⁱ, a palindrome, but xⱼz = 0ʲ10ⁱ, which is not. So the xᵢ are pairwise inequivalent: infinitely many classes, and no finite automaton can recognize the language.
-
Build: every 5-bit LFSR. With
explainer/cs/pebble/seq.py, find the period of every 5-bit LFSR, and check that exactly φ(31)/5 = 6 are maximal.Solution
Tap bit 4 (so the register really has length 5) plus any subset of bits 0–3: 16 registers. Run each with
lfsr(taps, 5)from state 1 until it returns. The periods are 5, 6, 8, 12, 14, 14, 15, 15, 21, 21 and six times 31; the maximal tap sets are {4, 1}, {4, 2}, {4, 0, 1, 2}, {4, 0, 1, 3}, {4, 0, 2, 3} and {4, 1, 2, 3}. 31 is prime, so φ(31)/5 = 30/5 = 6. -
★ Research: verify a bounded-window tracker. Prove the undercount bound in the stated finite model. Test
[0,0] + [1]*20with one counter and trigger 2. What must a physical guarantee also model?Solution
Solution and starting point. Every full-table decrement consumes k tracked events plus the incoming event, so there are at most floor(W/(k+1)) decrements. For each row, since its last immediate modeled victim refresh, the true count exceeds its estimate by at most this total. Triggering at T/2 therefore keeps the count at most T when floor(W/(k+1)) ≤ T/2. This is a sufficient bound inside one aligned window, not a universal counter lower bound. Delete a row's counter after refresh: retaining a zero can produce a negative ghost entry on the next full-table miss. The regression stream then gives maximum unrefreshed counts
{0:2,1:2}; the defective version gives{0:2,1:20}. A physical proof must also account for multiple aggressors, window alignment, reset policies, refresh queues, row-open time and device assumptions. Compare Graphene's spillover table and CoMeT's count-min upper estimates; investigate formally checked guarantees and their implementation cost. AutoPRAC (Qu and Saileshwar, June 2026 preprint) is a dated reported example of reset-policy analysis.
Notes and sources
Glossary
反馈 feedback · SR 锁存器 SR latch · D 锁存器 D latch · 触发器 flip-flop · 主从触发器 master–slave flip-flop · 时钟 clock · 寄存器 register · 建立时间 / 保持时间 setup / hold time · 时钟到输出延迟 clock-to-Q · 时钟偏斜 clock skew · 亚稳态 metastability · 同步器 synchronizer · 平均故障间隔 MTBF · 相图 phase portrait · 鞍点 saddle · 有限状态机 finite-state machine · 摩尔机 / 米利机 Moore / Mealy machine · 独热码 one-hot · 格雷码 Gray code · 有限自动机 finite automaton · 正则语言 regular language · Myhill–Nerode 定理 · 状态最小化 state minimization · 计数器 counter · 移位寄存器 shift register · 线性 反馈移位寄存器 LFSR · 本原多项式 primitive polynomial · 寄存器堆 register file · 静态 / 动态随机存储器 SRAM / DRAM · 读出 放大器 sense amplifier · 字线 / 位线 word line / bit line · 刷新 refresh · 行缓冲 row buffer · 行锤攻击 Rowhammer · 异步 电路 asynchronous circuit · C 元件 C-element · 只读存储器 ROM · 可编程逻辑阵列 PLA · 微码 microcode · 磁芯存储器 core memory
Sources
Books: Harris & Harris, Digital Design and Computer Architecture, ch. 3; Nisan & Schocken, The Elements of Computing Systems, ch. 3; Sipser, Introduction to the Theory of Computation, ch. 1; Hopcroft, Motwani & Ullman, ch. 4; Jacob, Ng & Wang, Memory Systems: Cache, DRAM, Disk; Golomb, Shift Register Sequences; Strogatz, Nonlinear Dynamics and Chaos, ch. 6.
Papers: Mealy (1955); Moore, "Gedanken-experiments on sequential machines" (1956); Myhill (1957); Nerode, "Linear automaton transformations" (1958); Muller & Bartky (1959); Hopcroft, "An n log n algorithm for minimizing states in a finite automaton" (1971); Chaney & Molnar, "Anomalous behavior of synchronizer and arbiter circuits" (1973); Dennard, DRAM patent (1968); Ginosar, "Metastability and synchronizers: a tutorial" (2011); Kim et al., "Flipping bits in memory without accessing them" (2014); Seaborn & Dullien (2015); Frigo et al., "TRRespass" (2020).
Primary checks for this revision: IBM DRAM history; Micron DDR5 features; Lamport's dated manuscript (1984; published 2012); Kim et al. 2020; Graphene; CoMeT; AutoPRAC (submitted 22 June 2026; preprint attribution).
About this partfrom its README
Part 5 of a sixty-one-part course in computer science (see the series plan and
the syllabus). Connect a circuit's output back to its input and it can remember. Memory brings time
into the design, and a cost that never quite vanishes: a flip-flop can balance between 0 and 1 for an unbounded time.
The same machines that remember turn out to be the first rung of a theory of languages. Circuits with feedback are
simulated gate by gate with unit delays (Loop in explainer/cs/pebble/seq.py), clocked circuits cycle by cycle
(Seq); every number is computed in compute.py.
- A circuit that remembers. Combinational circuits forget; two NANDs in a loop hold a bit; a ball between two valleys and on the ridge; objectives.
- 1. Feedback. The SR latch, wire by wire (set, reset, hold, the forbidden input); tick-by-tick waveforms, including the symmetric release that oscillates forever in the unit-delay model; the ring oscillator (period 2k in the binary unit-delay model, with physical oscillation requiring gain and delay).
- 2. Two wells and a saddle. The cross-coupled inverters as τv̇₁ = f(v₂) − v₁, τv̇₂ = f(v₁) − v₂; the phase portrait (vector field, nullclines, trajectories) with two stable states and a saddle on the diagonal; the Jacobian at the saddle, RC-normalized eigenvalues −4 and +2, and t_resolve ≈ (τ/λ) ln(Δ/|δ|).
- 3. Latches, flip-flops and the clock. The D latch (transparent and closed, simulated); the master–slave edge-triggered flip-flop (Q takes D at the rising edge); registers; the synchronous picture (state, logic, next state).
- 4. How fast can the clock go? Setup, hold, clock-to-Q on a waveform; f_max = 1/(t_cq + t_logic + t_setup) on a budget bar; an assumed 290 ps worst-case logic budget (≈ 2.8 GHz with the stated register delays); clock skew, and why a hold violation cannot be fixed by slowing the clock.
- 5. Metastability. A D change at the edge makes the simulated master oscillate; 40,000 random arrivals integrated through the latch equations: a histogram with an exponential tail, P(t > T) ∝ e^{−λT}; MTBF = e^{t_r/τ}/(T₀ f_clk f_data): illustrative constants yield about 10 hours versus 6 × 10¹⁸ years. The finite sample illustrates a tail, not an astronomical reliability certificate; single-bit synchronizers do not solve bus coherence or pulse capture.
- 6. Finite-state machines. A Moore detector for 1011, run on a stream; Mealy against Moore; binary, Gray and one-hot encodings synthesized with Quine–McCluskey (with don't-cares), built and simulated: 3/3/5 flip-flops, 14/24/15 gates.
- 7. Machines and languages. A six-state DFA for multiples of 3 (state = value mod 6); the Myhill–Nerode theorem (1958), proved; partition refinement merging it to 3 states; Hopcroft's n log n (1971); {0ⁿ1ⁿ} is not regular; the ladder to Parts 12, 25 and 1.
- 8. Counters and shift registers. The counter; the shift register; a 4-bit LFSR running through all 15 non-zero states; LFSRs as multiplication by x modulo a monic polynomial with constant term 1 (a field only when irreducible); primitive polynomials and nonzero seeds give full period; every such feedback polynomial of degree 2–8, simulated: the maximal ones number φ(2ⁿ − 1)/n (16 at degree 8); CRCs, stream ciphers, scramblers, GPS, BIST.
- 9. Pebble's register file. Sixteen 32-bit registers (r0 hard-wired to 0), a decoder for the write port, a multiplexer per bit to load or keep, two 16-to-1 multiplexer trees for the read ports: 480 flip-flops and 5,824 gates in the chosen gate basis, verified against a Python model; what each extra port costs.
- 10. Static memory. The 6T SRAM cell (cross-coupled inverters and two access transistors), bit lines, word lines and sense amplifiers; cells in a grid.
- 11. Dynamic memory. Dennard's 1T1C idea (1966), destructive sensing and immediate restoration, Intel 1103's early 3T cell (1970); a common 64 ms refresh interval at normal temperature (device dependent); activate, read, precharge and row buffers. DDR4 defaults to burst length 8; DDR5 to 16. The 20× area comparison is an illustrative cell model.
- 12. When memory leaks. Rowhammer (Kim et al., 2014: 110 of 129 DDR3 modules, as few as 139,000 activations); Project Zero's page-table exploit (2015), JavaScript and Android (2016), TRR and TRRespass (2020); leaky abstractions.
- 13. Clocks, and memory as logic. The synchronous discipline and its cost; the Muller C-element and asynchronous handshakes; ROMs, PLAs and FPGAs as memory doing logic; microcode previewed.
- 14. Remembering, before chips. Mercury delay lines (EDSAC), Williams tubes (the Manchester Baby), core memory (Forrester, Whirlwind 1953; coincident-current selection and destructive reads), the Intel 1103, flash.
- 15. Frontier: defending memory. Historical thresholds: 139,000 toggles (2014); as few as 4,800 activations per aggressor in a two-aggressor experiment (2020), with mitigations disabled. A teaching model uses W = 1,383,783 activations per bank per 64 ms. Independent coins refresh all modeled victim neighbours. With N = ceil(seconds per year / t_RC), the union bound N(1 − p)^T ≤ 10⁻² covers overlapping runs: p ≈ 0.03%, 0.4%, 3.8% at T = 139,000, 10,000, 1,000. This all-neighbour variant differs from original PARA. Positive Misra–Gries counters are removed after immediate modeled refresh. In one aligned window the undercount is at most floor(W/(k + 1)); k ≥ 2W/T is sufficient, not a minimum or a physical DRAM guarantee. Four or 16 counters allow 60,739 unrefreshed activations on the chosen trace; 64 and 277 stay below T on that trace. Graphene (Park et al., 2020) uses additional spillover machinery. CoMeT (2024) never undercounts under its specified update/reset rules; collisions can cause extra refreshes. Half-Double, RowPress and PRAC expose further physical/model constraints. AutoPRAC (June 2026 preprint) reports a reset-policy flaw; this lesson attributes that finding without independently auditing the paper's proof.
- Recap, where this comes back, in practice, problems.
Companion material in this repository
The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
- Feedback: the SR latch from two NANDs. The cross-coupled inverters as a dynamical system: two stable fixed points and a saddle, in the computed phase portrait. Metastability is that saddle.
- The D latch and the edge-triggered flip-flop (master–slave); the clock; registers.
- Timing: setup, hold, clock-to-Q; f_max = 1/(t_cq + t_logic + t_setup) derived on a timing diagram; clock skew.
- Metastability: resolution time P(t > τ) ∝ e^{−t/τ}; MTBF = e^{t_r/τ}/(T₀ f_clk f_data); the two-flip-flop synchronizer (computed).
- Finite-state machines, Moore and Mealy: a sequence detector; binary, one-hot and Gray state encodings.
- FSMs are DFAs: the Myhill–Nerode theorem (proved), and minimization by partition refinement (Hopcroft's n log n). The bridge to Part 12.
- Counters and shift registers. LFSRs: maximal-length sequences from primitive polynomials over GF(2) (period 2ⁿ − 1), with the LFSR as multiplication by x in GF(2ⁿ). Returns in CRCs (Part 28) and stream ciphers (Part 29).
- The register file from decoders, multiplexers and flip-flops; what each extra port costs.
- Memory arrays:
- the 6T SRAM cell (cross-coupled inverters again), word and bit lines, sense amplifiers;
- the 1T1C DRAM cell, destructive sensing and restoration, a common 64 ms refresh interval at normal temperature (device dependent), row buffers;
- why DRAM is dense and slow. Part 9 builds on this.
- Rowhammer (2014): hammering one DRAM row flips bits in its neighbours, and the hardware abstraction leaks (Part 42 returns to it).
- The synchronous discipline, and why nearly everyone clocks; asynchronous circuits and the Muller C-element.
- ROMs, PLAs, FPGAs: memory as logic; a preview of microcode.
- History: mercury delay lines (EDSAC), Williams tubes, core memory (Forrester, Whirlwind 1953), the Intel 1103 DRAM (1970); flash previewed for Part 34.
- Frontier: a bounded-window counting model, an annual union bound covering overlapping runs, counter-reset regression and the physical assumptions required by Rowhammer defences. Graphene, CoMeT, PRAC and the explicitly dated June 2026 AutoPRAC preprint.
- Outro.
Computed: the cross-coupled-inverter ODE phase portrait; a metastability histogram; Myhill–Nerode minimization; LFSR periods for monic degree 2–8 polynomials with constant term 1; the register file in the simulator. Visuals: a ball rolling into one of two wells or balancing on the saddle; setup and hold windows on a waveform; the DRAM capacitor leaking charge until refresh. In practice: clock-domain crossings in chip design, DRAM refresh and ECC in servers, Rowhammer mitigations, state machines in embedded firmware and protocol code. Reading: Harris & Harris ch. 3; Nisan & Schocken ch. 3; Sipser ch. 1; Hopcroft, Motwani & Ullman ch. 4; Jacob, Ng & Wang, Memory Systems; Golomb, Shift Register Sequences; Kim et al. 2014 (Rowhammer); Ginosar, "Metastability and Synchronizers" (2011).
中文讲义
本讲的中文部分(与英文版对应)。
习题与解答
-
或非锁存器。 用两个或非门搭一个 SR 锁存器。现在哪个输入是禁止的?输出会怎样?
解答
Q = NOR(R, Q̄),Q̄ = NOR(S, Q),输入高电平有效:S = 1 迫使 Q̄ = 0,进而 Q = 1;R = 1 迫使 Q = 0;S = R = 0 时保持。禁止的输入是 S = R = 1,它迫使两个输出都为 0;在理想模拟模型中完全对称地释放,可停在不稳定平衡点;二值单位延迟模型则可能振荡。实际失配与噪声通常会打破对称性。
-
最快的时钟。 t_cq = 50 ps,t_setup = 30 ps,最慢的逻辑路径为 420 ps。f_max 是多少?如果时钟到达第二个寄存器晚了 20 ps 呢?
解答
T ≥ 50 + 420 + 30 = 500 ps,所以 f_max = 2 GHz。有 20 ps 对捕获寄存器有利的偏斜时,建立条件变为 500 ≤ T + 20,于是 T ≥ 480 ps,f_max ≈ 2.08 GHz;但保持检查 t_cq + t_logic,min ≥ t_hold + 20 ps 对最短路径变严了 20 ps。
-
设计同步器。 τ = 25 ps,T₀ = 20 ps,f_clk = 2 GHz,f_data = 50 MHz。要让平均故障间隔达到 1000 年,同步器要等多久?
解答
T₀ f_clk f_data = 20·10⁻¹² · 2·10⁹ · 5·10⁷ = 2·10⁶ s⁻¹,1000 年 ≈ 3.16·10¹⁰ s。所以 e^{t_r/τ} ≥ 6.3·10¹⁶, t_r ≥ 25 ps · ln(6.3·10¹⁶) ≈ 25 · 38.7 ps ≈ 0.97 ns:约两个 0.5 ns 的时钟周期,因此要用三个串联的触发器(两个周期的 决断时间)。这是理想预算;实际路径还须扣除寄存器与布线延迟,使用实测常数,并验证实现。
-
摩尔机。 画一个摩尔机:当已读到的 1 的个数能被 3 整除时输出 1。它是最小的吗?
解答
三个状态 c₀、c₁、c₂(1 的个数模 3),初态 c₀,只在 c₀ 输出 1;读 1 使 cᵢ → cᵢ₊₁,读 0 不变。它是最小的:后缀 ε、11 和 1 两两区分这三个状态(从 c₀ 出发 ε 被接受;从 c₁ 出发 "11" 被接受;从 c₂ 出发 "1" 被接受),所以有三个 Myhill–Nerode 类。
-
回文不是正则的。 用 Myhill–Nerode 定理证明,没有有限自动机能识别 {0, 1} 上的回文。
解答
取前缀 xᵢ = 0ⁱ1,i = 0, 1, 2, …。对 i ≠ j,后缀 z = 0ⁱ 使 xᵢz = 0ⁱ10ⁱ 是回文,而 xⱼz = 0ʲ10ⁱ 不是。所以 xᵢ 两两不等价:有无穷多个类,没有有限自动机能识别这个语言。
-
动手:所有 5 位 LFSR。 用
explainer/cs/pebble/seq.py求出每个 5 位 LFSR 的周期,并验证恰有 φ(31)/5 = 6 个达到最大 周期。解答
抽头取第 4 位(这样寄存器长度确实为 5),再加第 0–3 位的任意子集:共 16 个寄存器。用
lfsr(taps, 5)从状态 1 运行到回到起点。周期为 5、6、8、12、14、14、15、15、21、21,以及六个 31;达到最大周期的抽头集合是 {4, 1}、 {4, 2}、{4, 0, 1, 2}、{4, 0, 1, 3}、{4, 0, 2, 3} 和 {4, 1, 2, 3}。31 是素数,所以 φ(31)/5 = 30/5 = 6。 -
★ 研究题:验证有限窗口跟踪器。 证明所述有限模型中的低估界。用一个计数器、触发值 2 测试
[0,0] + [1]*20。物理保证还需建模哪些因素?解答
解答与起点。 每次全表递减消耗 k 个已跟踪事件和当前输入事件,所以最多发生 floor(W/(k+1)) 次。 自一行上次在模型中立即触发受害行刷新以来,它的实际计数与估计值之差不超过该总次数。因此,当 floor(W/(k+1)) ≤ T/2 时,在 T/2 触发刷新可将实际计数限制在 T 内。这是一个对齐窗口内的充分条件, 并非通用的计数器数量下界。刷新后必须删除该行计数器:若保留零项,下次表满且未命中时会产生负数幽灵项。 回归序列中各行未刷新计数的最大值应为
{0:2,1:2};有缺陷的版本得到{0:2,1:20}。 物理证明还需考虑多个攻击行、窗口对齐、重置策略、刷新队列、行开启时长和器件假设。比较 Graphene 的溢出表 与 CoMeT 的 count-min 上估计,并研究形式化验证保证及其实现开销。Qu 与 Saileshwar 的 AutoPRAC (2026 年 6 月预印本)是报告重置策略分析的一个有明确日期的案例。
Build the film
python -m videos.cs.cs5.compute # the part's numbers, into .cache/cs5
python tools/build.py cs5 # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py cs5 Hook # one chapter, silent, with a contact sheet
Scenes: videos/cs/cs5. Setup: see the course page. Source of these notes: the README and the scenes' narration.
Build it
python -m videos.cs.cs5.compute # every number in the part (under a minute)
python tools/build.py cs5 -q l # a 480p preview
python tools/build.py cs5 # 1080p