Algorithm Search⌘K

Techniqueadvanced

LFSR reseeding

Also called Koenemann reseeding.

Koenemann's test compression that stores a seed per test cube and expands it with an LFSR, the seed found by solving linear equations over GF(2) for the care bits.

LFSR reseeding is a way to store a test pattern in fewer bits than it has. A test pattern from automatic test pattern generation is a test cube: most of its bits are don't-cares, and only a few, the care bits, must have given values. Koenemann (1991) stores, for each cube, only a seed for an on-chip linear feedback shift register, chosen so that the LFSR output matches the cube at every care bit. Each LFSR output bit is a fixed XOR of seed bits, so the seed is a solution of a linear system over GF(2) with one equation per care bit, and the cube can be stored this way exactly when that system is consistent. An LFSR a little longer than the largest number of care bits makes almost every cube encodable.

In plain words

A test for one fault fixes a few input bits and leaves the rest free. Storing the whole pattern wastes space on the free bits.

A shift register with XOR feedback can make long streams from a short start value, the seed. Each bit it makes is the XOR of some bits of the seed, and which ones is known in advance. So asking "which seed gives these few fixed bits?" is a small puzzle of XOR equations, one equation per fixed bit. A computer solves it before the test. The tester then stores only the seed, and the chip grows the full pattern from it.

The puzzle has no answer when the fixed bits conflict with the way the register mixes bits. A register a bit longer than the number of fixed bits almost always gives an answer.

When it applies

  • The circuit has scan design, so a test is one load of the scan cells, and the scan cells can be filled from an on-chip generator instead of the tester.
  • The test cubes have few care bits. For a single fault, a cube often fixes a few percent of the cells, and the largest count smax⁡s_{\max} over all cubes decides the size of the LFSR.
  • The design can afford an LFSR of n≈smax⁡+20n \approx s_{\max} + 20 stages, and the tester can load nn bits of seed per pattern. A plain built-in self-test LFSR can be reused, which is how reseeding tops up the coverage of random patterns.

The template

The LFSR has nn stages and a tap set T⊆{1,…,n}T \subseteq \{1, \ldots, n\}. Its output stream starts with the seed bits and then follows the recurrence

at=st (0≤t<n),at=⨁i∈Tat−i (t≥n).a_t = s_t \ (0 \le t < n), \qquad a_t = \bigoplus_{i \in T} a_{t-i} \ (t \ge n).

The tap set TT belongs to the feedback polynomial xn+∑i∈Txn−ix^n + \sum_{i \in T} x^{n-i}. A test cube c0c1…cL−1c_0 c_1 \ldots c_{L-1} over {0,1,X}\{0, 1, X\} is written in the order in which its bits leave the LFSR. With one scan chain of length LL fed straight from the output, the bit ata_t ends in cell L−1−tL - 1 - t, since the first bit out is shifted deepest.

By induction on tt, every ata_t is the XOR of a fixed set of seed bits, written as an nn-bit mask ftf_t: ftf_t is the unit vector ete_t for t<nt < n, and ft=⨁i∈Tft−if_t = \bigoplus_{i \in T} f_{t-i} after that. So at=ft⋅sa_t = f_t \cdot s, the dot product over GF(2).

  1. RESEED(n, T, the cube c_0 ... c_(L-1))
  2. 1f_0, ..., f_(L-1) ← the output masks: f_t = e_t for t < n, else XOR of f_(t-i) over i in T
  3. 2for each t with c_t ≠ X do
  4. 3(m, v) ← (f_t, c_t), reduced by the stored rows whose leading bit is set in m
  5. 4if m = 0 and v = 1 then return FAIL
  6. 5if m ≠ 0 then store (m, v) as the row with leading bit the top bit of m
  7. 6s ← 0
  8. 7for the stored rows in increasing order of leading bit do set that bit of s so that m · s = v
  9. 8return s

The holes are the generator (the size nn, the taps TT, and a phase shifter when one LFSR feeds many chains), the map from output times to scan cells, and the fill of the free seed bits in line L6. Lines L2 to L5 are Gaussian elimination over GF(2), one row at a time, and line L7 is back substitution: every other bit of a stored row is below its leading bit, so it is already fixed when the row is reached.

Why the answer is exact. A seed ss makes the LFSR produce the cube exactly when ft⋅s=ctf_t \cdot s = c_t for every care position tt, since at=ft⋅sa_t = f_t \cdot s. So the encoding seeds are the solutions of a linear system modulo 2. Elimination finds a solution when one exists, and it reaches a row 0=10 = 1 exactly when the rows are dependent in a way that their values contradict. So RESEED fails exactly when no seed encodes the cube. When the system is consistent and its rank is rr, exactly 2n−r2^{n-r} seeds encode the cube.

What is always encodable. If n∈Tn \in T, then any nn consecutive output bits aj,…,aj+n−1a_j, \ldots, a_{j+n-1} can take any values. The window at jj fixes the window at j−1j - 1, since the recurrence for aj+n−1a_{j+n-1} contains aj−1a_{j-1} with coefficient 1 and the other terms are in the window. So by induction the window at jj fixes the seed, the map from seeds to windows is one to one, and as both sets have 2n2^n elements it is onto. So a cube whose care bits fit in nn consecutive positions always has a seed.

What is not. Having at most nn care bits is not enough. For x3+x+1x^3 + x + 1, the tap set is {2,3}\{2, 3\}, so at+3=at+1⊕ata_{t+3} = a_{t+1} \oplus a_t for every tt. A cube with ct=1c_t = 1, ct+1=0c_{t+1} = 0 and ct+3=0c_{t+3} = 0 has only 3 care bits, but it asks for 0=1⊕00 = 1 \oplus 0, and no seed of the 3-stage LFSR gives it.

How large an LFSR. Suppose, as a model, that the ss masks of the care bits behave like independent uniform vectors of GF(2)n\mathrm{GF}(2)^n. Row i+1i + 1 falls in the span of the first ii with probability at most 2i−n2^{i-n}, so all ss are independent, and the cube is encodable, with probability at least 1−∑i<s2i−n>1−2s−n1 - \sum_{i<s} 2^{i-n} > 1 - 2^{s-n}. For n=s+20n = s + 20 the failure chance is below 2−20≈10−62^{-20} \approx 10^{-6}, which is Koenemann's rule of smax⁡+20s_{\max} + 20 stages. This is a model of the masks, not a theorem about a given LFSR: real masks are not random, and the "what is not" case above is a set of 3 dependent masks out of 3. A measurement shows how close the model is. For the 24-stage LFSR with the primitive polynomial x24+x7+x2+x+1x^{24} + x^7 + x^2 + x + 1, cubes of length 400 with ss care bits at random positions and random values, 2000 cubes per row (seed 2026), gave these rates.

care bits ss 16 20 22 24
encodable, measured 0.9985 0.9655 0.8675 0.6000
encodable, random-mask model 0.9980 0.9692 0.8826 0.6103

The model value counts that a dependent row is still consistent with probability 1/21/2, so it is above the bound 1−2s−n1 - 2^{s-n}.

Example. Take n=4n = 4 and x4+x+1x^4 + x + 1, so T={3,4}T = \{3, 4\} and at=at−3⊕at−4a_t = a_{t-3} \oplus a_{t-4}. The masks of the first ten outputs are s0s_0, s1s_1, s2s_2, s3s_3, s0+s1s_0 + s_1, s1+s2s_1 + s_2, s2+s3s_2 + s_3, s0+s1+s3s_0 + s_1 + s_3, s0+s2s_0 + s_2 and s1+s3s_1 + s_3. The cube XX1X0XX1X0 has the care bits c2=1c_2 = 1, c4=0c_4 = 0, c7=1c_7 = 1 and c9=0c_9 = 0. Line L5 stores s2=1s_2 = 1 (leading bit 2), s0+s1=0s_0 + s_1 = 0 (leading bit 1) and s0+s1+s3=1s_0 + s_1 + s_3 = 1 (leading bit 3). The last row s1+s3=0s_1 + s_3 = 0 has leading bit 3, so line L3 adds the stored row and gets s0=1s_0 = 1, a new row with leading bit 0. Line L7 then sets s0=1s_0 = 1, s1=1s_1 = 1, s2=1s_2 = 1 and s3=1⊕s0⊕s1=1s_3 = 1 \oplus s_0 \oplus s_1 = 1. The seed 1111 gives the stream 1111000100, which matches the cube, and a search over all 16 seeds finds no other. Four care bits fix four seed bits here, so one more care bit can only agree or conflict: the cube 0X1X0XX1X0 asks for s0=0s_0 = 0 and fails.

Classic examples

  • Koenemann's scheme (1991). One LFSR of smax⁡+20s_{\max} + 20 stages feeds the scan chains through a phase shifter, the tester loads one seed per pattern, and the LFSR runs freely during the shift.
  • Multiple-polynomial LFSR. Hellebrand, Rajski, Tarnick, Venkataraman and Courtois (1995) let a few extra bits per seed choose one of several feedback polynomials. A cube that one polynomial cannot encode often has a seed under another, which brings the size down to about smax⁡+4s_{\max} + 4 stages with 16 polynomials.
  • Mixed-mode BIST. A built-in self-test runs pseudorandom patterns first, and the faults they miss are covered by stored seeds for the same LFSR, which is much cheaper than stored patterns.
  • Continuous reseeding in embedded deterministic test. Instead of one seed loaded at the start, new tester bits are injected into the generator on every shift clock, and the same linear algebra solves for all of them at once.

Variations

  • Many chains. With a phase shifter, each scan cell gets an XOR of several LFSR stages at some clock. The mask of every cell is still a linear form in the seed, and only line L1 changes.
  • Free bits. The free seed bits of line L6 can be set to 0, to random values, or to values that also detect other faults, so that one seed covers several cubes.
  • Seed per pattern or per set. A seed can be expanded into one pattern, or into a run of patterns that are then simulated against the remaining faults.
  • Incremental solving. Each care bit is one row, so a test generator can ask after each new care bit whether the cube is still encodable, and stop adding care bits to a cube when it is not.
  • Finding a short generator. The opposite problem, finding the shortest LFSR that outputs a given full stream, is solved by the Berlekamp-Massey algorithm. Reseeding fixes the LFSR and asks only for the seed of a partial stream.

Pitfalls

  • Counting care bits is not enough. The 3-bit example above fails with 3 care bits on a 3-stage LFSR. Use the measured failure rate, not s≤ns \le n, to size the LFSR, and keep a fallback such as a stored pattern.
  • Correlated chains. Neighbor stages of one LFSR feed shifted copies of one sequence. If two scan chains take neighbor stages without a phase shifter, the masks of their cells repeat with a shift, and cubes with care bits in both chains fail much more often than the model says.
  • Taps without nn. If n∉Tn \notin T, the window argument fails and some seed bits never reach later outputs. Then fewer than nn seed bits are useful, and the effective size is smaller than it looks.
  • Seed loading time. The seed has to be loaded before the shift starts, which takes time unless the LFSR has a shadow register. Continuous injection, as in embedded deterministic test, avoids the pause.
  • The pattern is not the cube. The don't-care bits get pseudorandom values. They can switch many cells during shift and capture, which raises test power, and they change which other faults the pattern detects.

Code

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

lfsr_reseeding.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lfsr-reseeding/. The authors are listed in prov/NQ6987.jsonl.
"""LFSR reseeding: find a seed whose LFSR output matches a test cube.

The LFSR has n stages and a tap set T, a subset of {1, ..., n}. Its output
stream a_0, a_1, ... starts with the n seed bits, a_t = s_t for t < n, and then
follows the recurrence

    a_t = XOR of a_(t-i) over i in T        (t >= n).

A test cube is a string over '0', '1' and 'X', written in the order in which
its bits leave the LFSR (bit t of the cube is a_t). A seed encodes the cube
when a_t equals the cube at every position that is not 'X'.

Every a_t is a fixed XOR of seed bits, so each care bit gives one linear
equation over GF(2) in the n seed bits. The cube is encodable exactly when
this system is consistent. reseed solves it by Gaussian elimination in
O(L |T| + c n) operations on n-bit words, for a cube of length L with c care
bits.
"""

from __future__ import annotations

from typing import Iterable, Optional


def _check(n: int, taps: Iterable[int]) -> list[int]:
    taps = sorted(set(taps))
    if n < 1 or not taps or taps[0] < 1 or taps[-1] > n:
        raise ValueError("taps must be a nonempty subset of 1..n")
    return taps


def output_forms(n: int, taps: Iterable[int], length: int) -> list[int]:
    """Bit mask over the seed bits of every output a_0 .. a_(length-1). O(length |T|)."""
    taps = _check(n, taps)
    forms: list[int] = []
    for t in range(length):
        if t < n:
            forms.append(1 << t)
        else:
            f = 0
            for i in taps:
                f ^= forms[t - i]
            forms.append(f)
    return forms


def expand(n: int, taps: Iterable[int], seed: int, length: int) -> str:
    """Run the LFSR from a seed and return the first `length` output bits, as a '0'/'1' string."""
    taps = _check(n, taps)
    if not 0 <= seed < 1 << n:
        raise ValueError("the seed must have n bits")
    a: list[int] = []
    for t in range(length):
        if t < n:
            a.append((seed >> t) & 1)
        else:
            v = 0
            for i in taps:
                v ^= a[t - i]
            a.append(v)
    return "".join(map(str, a))


def reseed(n: int, taps: Iterable[int], cube: str) -> Optional[int]:
    """A seed (bit t is s_t) whose output matches the cube, or None when no seed does.

    Precondition: the cube is a string over '0', '1', 'X'. Free seed bits are set to 0.
    Cost: O(L |T|) to build the forms and O(c n) word operations to eliminate.
    """
    if set(cube) - set("01X"):
        raise ValueError("the cube must be over 0, 1, X")
    forms = output_forms(n, taps, len(cube))  # @line L1
    pivots: dict[int, tuple[int, int]] = {}  # leading bit -> (mask, value)
    for t, ch in enumerate(cube):  # @line L2
        if ch == "X":
            continue
        mask, val = forms[t], int(ch)
        while mask:  # @line L3
            lead = mask.bit_length() - 1
            if lead not in pivots:
                break
            pm, pv = pivots[lead]
            mask, val = mask ^ pm, val ^ pv
        if mask == 0 and val == 1:  # @line L4
            return None
        if mask:  # @line L5
            pivots[mask.bit_length() - 1] = (mask, val)
    seed = 0  # @line L6
    for lead in sorted(pivots):  # @line L7
        mask, val = pivots[lead]
        rest = mask ^ (1 << lead)
        bit = val ^ (bin(rest & seed).count("1") & 1)
        seed |= bit << lead
    return seed  # @line L8


def rank_of_cube(n: int, taps: Iterable[int], cube: str) -> int:
    """Rank over GF(2) of the care-bit rows of a cube (values ignored)."""
    forms = output_forms(n, taps, len(cube))
    basis: dict[int, int] = {}
    for t, ch in enumerate(cube):
        if ch == "X":
            continue
        m = forms[t]
        while m and (m.bit_length() - 1) in basis:
            m ^= basis[m.bit_length() - 1]
        if m:
            basis[m.bit_length() - 1] = m
    return len(basis)
test_lfsr_reseeding.py 119 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lfsr-reseeding/. The authors are listed in prov/NQ6987.jsonl.

import random

import pytest

from lfsr_reseeding import expand, output_forms, rank_of_cube, reseed

# Primitive feedback polynomials as tap sets: x^n + sum c_i x^i gives tap n - i for every c_i = 1.
PRIMITIVE = {3: [2, 3], 4: [3, 4], 5: [3, 5], 6: [5, 6], 7: [6, 7], 8: [4, 5, 6, 8], 10: [7, 10]}


def matches(stream: str, cube: str) -> bool:
    return all(c == "X" or c == s for c, s in zip(cube, stream))


def all_seeds(n, taps, cube):
    return [s for s in range(1 << n) if matches(expand(n, taps, s, len(cube)), cube)]


def test_page_example():
    # n = 4, x^4 + x + 1 (taps 3 and 4), a cube of length 10 with 4 care bits.
    cube = "XX1X0XX1X0"
    assert reseed(4, [3, 4], cube) == 0b1111
    assert expand(4, [3, 4], 0b1111, 10) == "1111000100"
    assert all_seeds(4, [3, 4], cube) == [0b1111]
    # One more care bit that disagrees with the only solution makes the system inconsistent.
    assert reseed(4, [3, 4], "0X1X0XX1X0") is None


def test_inconsistent_example():
    # x^3 + x + 1: a_(t+3) = a_(t+1) + a_t, so care bits 1, 0, 0 at t, t + 1, t + 3 conflict.
    for t in range(5):
        cube = ["X"] * 10
        cube[t], cube[t + 1], cube[t + 3] = "1", "0", "0"
        assert reseed(3, [2, 3], "".join(cube)) is None
        assert all_seeds(3, [2, 3], "".join(cube)) == []


def test_forms_match_expansion():
    rng = random.Random(5)
    for _ in range(200):
        n = rng.randint(1, 12)
        taps = rng.sample(range(1, n + 1), rng.randint(1, n))
        seed = rng.randrange(1 << n)
        length = rng.randint(0, 40)
        out = expand(n, taps, seed, length)
        forms = output_forms(n, taps, length)
        for t in range(length):
            assert int(out[t]) == bin(forms[t] & seed).count("1") % 2


def test_edge_cases():
    assert reseed(3, [2, 3], "") == 0
    assert reseed(3, [2, 3], "XXXXXXX") == 0
    assert reseed(1, [1], "1111") == 1
    assert reseed(1, [1], "10") is None
    with pytest.raises(ValueError):
        reseed(3, [4], "1")
    with pytest.raises(ValueError):
        reseed(3, [2, 3], "1Z")


def test_any_n_consecutive_bits_are_encodable():
    # With tap n present the state map is invertible, so any n consecutive care bits have a seed.
    rng = random.Random(8)
    for n, taps in PRIMITIVE.items():
        for _ in range(60):
            start = rng.randint(0, 30)
            bits = "".join(rng.choice("01") for _ in range(n))
            cube = "X" * start + bits + "X" * rng.randint(0, 5)
            seed = reseed(n, taps, cube)
            assert seed is not None and matches(expand(n, taps, seed, len(cube)), cube)


@pytest.mark.parametrize("n", [3, 4, 5, 6, 8])
def test_against_exhaustive_seed_search(n):
    rng = random.Random(1000 + n)
    for _ in range(150):
        taps = PRIMITIVE[n] if rng.random() < 0.5 else rng.sample(range(1, n + 1), rng.randint(1, n))
        length = rng.randint(1, 3 * n)
        p_care = rng.choice([0.1, 0.3, 0.6])
        cube = "".join(rng.choice("01") if rng.random() < p_care else "X" for _ in range(length))
        seeds = all_seeds(n, taps, cube)
        got = reseed(n, taps, cube)
        if not seeds:
            assert got is None
        else:
            assert got in seeds
            # The solutions form a coset of the null space: 2^(n - rank) seeds.
            assert len(seeds) == 2 ** (n - rank_of_cube(n, taps, cube))


def test_long_chain_against_exhaustive_n10():
    rng = random.Random(77)
    n, taps = 10, PRIMITIVE[10]
    for _ in range(30):
        length = 60
        cube = "".join(rng.choice("01") if rng.random() < 0.15 else "X" for _ in range(length))
        seeds = all_seeds(n, taps, cube)
        got = reseed(n, taps, cube)
        assert (got is None) == (not seeds)
        if got is not None:
            assert got in seeds


def test_cubes_from_real_streams_always_encode():
    # A cube cut from a real LFSR stream is consistent by construction.
    rng = random.Random(9)
    for _ in range(300):
        n = rng.choice(list(PRIMITIVE))
        taps = PRIMITIVE[n]
        s0 = rng.randrange(1 << n)
        length = rng.randint(1, 80)
        stream = expand(n, taps, s0, length)
        cube = "".join(c if rng.random() < 0.4 else "X" for c in stream)
        seed = reseed(n, taps, cube)
        assert seed is not None and matches(expand(n, taps, seed, length), cube)

Exercises

  1. For the LFSR x4+x+1x^4 + x + 1, compute the masks f10f_{10} to f14f_{14} and check that f15=f0f_{15} = f_0.
  2. Prove that the solutions of a consistent system with rank rr in nn unknowns over GF(2) are exactly 2n−r2^{n-r} seeds, and use it to count the seeds of the cube X1XX0XX1XX for x4+x+1x^4 + x + 1 (there are 2).
  3. Show that for any tap set that contains nn, every cube whose care bits lie in nn consecutive positions is encodable, and give a tap set without nn for which this fails.
  4. In the random-mask model, show that the chance that ss uniform vectors of GF(2)n\mathrm{GF}(2)^n are independent is ∏i<s(1−2i−n)\prod_{i<s} (1 - 2^{i-n}), and evaluate it for n=24n = 24 and s=20s = 20.

References

  1. B. Koenemann, LFSR-coded test patterns for scan designs, Proceedings of the European Test Conference, Munich, 237 to 242, 1991, the coding of a test cube as an LFSR seed found from linear equations in the care bits, and the rule that an LFSR of s_max + 20 stages fails with probability about 10^-6
  2. S. Hellebrand, J. Rajski, S. Tarnick, S. Venkataraman and B. Courtois, Built-in test for circuits with scan based on reseeding of multiple-polynomial linear feedback shift registers, IEEE Transactions on Computers 44(2), 223 to 233, February 1995, the multiple-polynomial LFSR, where a code selects one of several feedback polynomials for each seed, so that about s_max + 4 stages suffice
  3. Laung-Terng Wang, Cheng-Wen Wu and Xiaoqing Wen, VLSI Test Principles and Architectures, Morgan Kaufmann, 2006, the chapter Test Compression (linear decompressors, reseeding and the solution of the linear equations)

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • five exercises