28 CHAPTERS · TECHNICAL DRAFTAll articles ↗

A practical guide to history implementation and debugging

A value such as 0x12345678 is easy to recognize. The trouble begins when its four bytes cross a boundary: a file, a packet, a DMA descriptor, or a device register. The producer and consumer must agree on what each byte means, and software must know which layer already performs the conversion.

This article builds a precise model of those boundaries, then applies it to complete binary parsers and Linux drivers on little-endian x86 and big-endian s390x. Worked byte fixtures, public source-code traces, and debugging cases connect the model to practical failures. The most useful habit is simple: name the representation at every boundary, decode once, compute in host order, and encode once. Device access, synchronization, and validation remain separate responsibilities.

The examples are original teaching examples, based on public architecture documentation and Linux source code. The article moves from the representation model and history to checked parsing, device boundaries, debugging, and test design. Readers already comfortable with byte order can begin with the complete BORD parser or the Linux PCI walkthrough.

1. Start with the value and its bytes

Endianness describes the ordering of the constituent units of a larger representation. In ordinary systems programming, it usually means the ordering of bytes in a multibyte scalar.

Assume an eight-bit byte and the 32-bit unsigned value 0x12345678. Its four byte-sized pieces, from most significant to least significant, are 12, 34, 56, and 78. At consecutive memory addresses, the two familiar representations are:

Address offset        +0    +1    +2    +3
Big-endian            12    34    56    78
Little-endian         78    56    34    12

Big-endian places the most significant byte at the lowest address. Little-endian places the least significant byte there. Always label the direction of increasing addresses in a diagram. “Left” and “right” alone are ambiguous.

The mathematical value is the same in both cases. After a correctly typed native load, arithmetic such as value + 1 works normally on either machine. Hexadecimal notation also does not change: a debugger can print 0x12345678 on both hosts while the byte dumps differ. The C++ working draft gives the corresponding formal definitions for scalar representations. C++ endian definitions

For bytes b[0] through b[n-1], little-endian decoding gives each byte the weight 256^i. Big-endian decoding gives it the weight 256^(n-1-i). This explains conversion without assuming a processor architecture. For four bytes:

LE value = b[0] + 256*b[1] + 65536*b[2] + 16777216*b[3]
BE value = 16777216*b[0] + 65536*b[1] + 256*b[2] + b[3]

A single byte has no internal byte ordering to reverse. A byte sequence also has no automatically implied numeric meaning. 12 34 56 78 could be an integer, four samples, an instruction fragment, or four unrelated fields.

INTERACTIVE / THE BYTE LAB

See the same value
from both sides.

Edit a 32-bit hexadecimal value. The rows below show the actual byte sequence from the lowest address to the highest.

LIVE / INTERACTIVE
0x

1–8 hex digits. An optional 0x prefix is accepted.

ADDRESS+0+1+2+3
BIG-ENDIAN
LITTLE-ENDIAN
DECIMAL VALUE

2. How the disagreement became part of computing

The terminology is younger than the architectural choices. Danny Cohen’s On Holy Wars and a Plea for Peace, dated 1 April 1980 as IEN 137, applied the egg-breaking dispute in Jonathan Swift’s Gulliver’s Travels to competing computer ordering conventions. Cohen was addressing communication and serialization, including bit order, rather than merely proposing names for a C memory diagram. The essay documents an existing disagreement; it does not establish who invented either byte-order convention. Cohen’s original IEN 137

A few milestones explain why neither convention disappeared:

  • 1964: IBM introduced System/360, a compatible family organized around eight-bit bytes. Compatibility across generations became a major architectural commitment. The later z/Architecture ABI explicitly specifies big-endian scalar storage. IBM System/360 history, zSeries ABI
  • 1970s: DEC’s PDP-11 documentation specifies the low-order byte at the even word address and the high-order byte at the following address. This is a concrete early little-endian word representation, documented independently of today’s terminology. DEC PDP-11/40 Processor Handbook
  • 1978 onward: Intel introduced the 8086, beginning the architecture lineage that became x86. Intel’s current architecture manuals specify little-endian integer storage. Intel 8086 history, Intel architecture manuals
  • 1981: IPv4’s specification documented transmission of a multioctet numeric field with its most significant octet first. This became a familiar example of a canonical external representation, independent of either endpoint’s native storage. RFC 791 Appendix B

There are useful arguments for both layouts. Little-endian puts low-significance bytes at the same starting address across several widths, which can simplify some low-order operations. Big-endian fixed-width unsigned encodings have the useful property that lexicographic byte comparison agrees with numeric order. That comparison property needs its qualifications: variable widths, signed numbers, and floating-point encodings require additional rules.

These are properties of the layouts, not proof of a single historical design motive. Claims such as “little-endian was invented for addition” or “big-endian exists because people read left to right” compress different machines and design decisions into an unsupported origin story. Nor does either order make all modern processors inherently faster. Instruction sets, compilers, memory systems, and established interfaces matter much more than an isolated byte diagram.

3. Why early choices became lasting interfaces

It is tempting to tell the history as a contest in which one layout should eventually have won. A more useful explanation is that byte order became embedded in contracts that were expensive to change.

Once an operating system defines an executable format and calling convention, a compiler’s choices are no longer private implementation details. Debuggers, assembly routines, libraries, crash dumps, and applications have expectations about object representations. Files and network protocols can preserve a representation long after the machine that first wrote them has disappeared. A change to the CPU’s default loads does not migrate that accumulated data.

System/360 is an important example of the broader commitment to architectural compatibility. Amdahl, Blaauw, and Brooks described a common architecture with a coordinated storage and I/O model in their 1964 paper. This explains why the history of byte order belongs within architecture and software compatibility, rather than being treated as an isolated wiring preference. The paper’s existence is not evidence for every later story about why a particular byte order was chosen. Amdahl, Blaauw and Brooks on System/360

The word word also changed meaning between machines. A PDP-11 word is sixteen bits; an IBM z/Architecture word is thirty-two bits; Intel documentation distinguishes a sixteen-bit word, thirty-two-bit doubleword, and sixty-four-bit quadword. Code that assumes “swap one word” specifies a universal width is underspecified. Specify sixteen, thirty-two, or sixty-four bits, or the exact number of octets. DEC PDP-11/40 Processor Handbook, zSeries ABI

Byte addressability made the question particularly visible: a program could name each constituent byte independently, so a scalar’s order in increasing addresses became observable. On a machine or interface that exposes only whole words, other questions may dominate, including word sequencing and the representation used when the word is serialized. This is why Cohen’s original discussion ranges across multiple granularities instead of stopping at a four-byte integer.

There are therefore three historical claims worth separating:

  • An original manual can establish what a specific machine did.
  • A contemporaneous design paper can establish reasons its authors actually gave.
  • A later explanation can identify useful properties of the choice without establishing the original motivation.

Neither a convenient carry-propagation story nor the visual familiarity of hexadecimal notation is sufficient evidence for a universal origin. The practical inheritance is easier to establish: compatible software and durable data keep representation choices alive. Modern systems handle the resulting diversity by translating at interfaces, not by expecting every participant to adopt one native format.

4. Five different kinds of order

Several independent ideas tend to get called endianness. Keeping them separate prevents wrong fixes.

Byte order assigns the significance of bytes within a multibyte field.

Bit numbering assigns names to bit positions. IBM documentation commonly numbers from the most significant end. Many programming interfaces number the least significant bit as bit zero. The numbering convention does not itself reverse the stored bytes. A specification’s bit 0 might therefore correspond to a different mask than a C programmer first expects. For a 32-bit field numbered from the most significant end, specification bit k corresponds to the unsigned mask UINT32_C(1) << (31 - k), provided k is an integer from zero through thirty-one. IBM z/Architecture Principles of Operation

Bit serialization order describes which bit a link transmits first. It belongs to the relevant physical or link protocol. Knowing a CPU’s byte order does not tell you how a serial link encodes or transmits bits.

Word or lane order describes how larger units are arranged. A device can place the low 32-bit half of a 64-bit register at one offset and require the two halves to be accessed in a particular sequence. SIMD lane numbering and register diagrams introduce related presentation conventions. None should be inferred from the host’s byte order alone.

Memory ordering describes when accesses become observable to other agents. It concerns barriers, ownership, cache coherency, and device completion. Byte swapping does not provide a memory barrier; a memory barrier does not swap bytes.

For example, reversing the bytes of 0x12345678 yields 0x78563412. Reversing all 32 bits yields 0x1e6a2c48. These are different operations, and neither operation changes the order in which two stores become visible.

5. Native order is only one contract

The x86 and s390x distinction is especially useful because it exposes code that silently assumes its development machine’s representation.

On ordinary x86 and x86-64 systems, native multibyte integers are little-endian. Linux on s390x follows the big-endian z/Architecture ABI. This does not prevent either machine from processing data in the other representation. Compilers can emit byte-reversing instructions or suitable instruction sequences, and operating-system accessors can hide an I/O-specific conversion. Intel architecture manuals, zSeries ABI

Some architecture families support more than one endian execution mode. A particular operating system and ABI still select a concrete contract. Do not assume a running application’s format can be changed safely with a compiler flag or debugger command. GDB’s set endian changes its interpretation of target data, not the target machine. GDB target byte order

Mixed layouts also exist. For a hypothetical 32-bit field whose 16-bit words are most-significant first but whose bytes inside each word are little-endian, 0x12345678 would appear as 34 12 78 56. A full 32-bit byte swap is not the same transformation as swapping bytes within each 16-bit word. Labels such as “mixed-endian” are useful warnings; an explicit byte map is the actionable specification.

6. Formats choose their own representations

“Network byte order” conventionally means big-endian for the socket conversion interfaces and many Internet protocol fields. It does not mean that every value carried over a network is big-endian. An application’s payload has its own format. The operating system does not automatically convert arbitrary application buffers passed to send(). Linux byteorder interfaces

Examples show why field-level contracts matter:

  • XDR specifies a common external representation, including big-endian integer encodings and its own padding rules. RFC 4506
  • Protocol Buffers uses little-endian fixed-width numeric encodings, while varints carry seven payload bits per byte with continuation bits. A varint is not a fixed-width integer that can be decoded with one byte swap. Protocol Buffers wire format
  • UTF-8 is a byte-oriented encoding with no LE/BE variants. UTF-16 and UTF-32 use multibyte code units, so their serialized forms need byte-order rules. A UTF-8 byte-order mark, when present, is an encoding signature, not a choice between byte orders. Unicode UTF and BOM FAQ
  • UUIDs have a standardized binary representation, but interoperability with Microsoft’s COM GUID representation requires care. Copying the bytes of an arbitrary host structure is not a general UUID conversion algorithm. RFC 9562 Section 4

ASCII characters do not reverse because the CPU changes endianness. Neither does an opaque byte string. Reverse only the units that the format identifies as multibyte numeric fields. Reversing an entire packet also reverses field positions and byte strings, which usually corrupts it.

Floating-point data needs more than a byte-order label. Agree on the numeric format, width, representation of special values, and byte layout. Reordering the bytes of an IEEE binary32 representation is different from numerically converting a floating-point value to an integer. A format such as XDR specifies the representation; “whatever float looks like here” does not. XDR floating-point encoding

Checksums and hashes deserve the same discipline. Establish exactly which byte sequence the algorithm covers and how the resulting digest or checksum is stored. The algorithm’s internal word operations do not authorize changing the input bytes. A mismatch can come from the input, padding, length encoding, or output serialization, even when the core arithmetic is correct.

7. Three encodings that punish blind swapping

Concrete encodings show why the unit being transformed matters more than the instruction used to transform it.

UTF16 changes bytes within code units

The character U+1F642 is represented in UTF-16 by the surrogate pair D83D DE42. Its serialized bytes are:

UTF-16BE       d8 3d de 42
UTF-16LE       3d d8 42 de

Converting these two forms swaps the bytes within each sixteen-bit code unit. It does not reverse the two code units. Reversing the entire four-byte sequence would put the low surrogate before the high surrogate and produce an invalid pairing. This distinction remains important for long strings: convert code units while preserving the order of the string. A BOM is additional stream metadata, not an instruction to reverse an arbitrary buffer. UTF-16 serialization in RFC 2781

A varint has a different decomposition

For the unsigned value 300, the low seven-bit group is 44 and the next group is 2. A base-128 continuation encoding therefore produces ac 02: the first byte contains 2c with its continuation bit set; the second contains the final group 02. By contrast, a two-byte little-endian fixed-width integer would be 2c 01, and a four-byte one would be 2c 01 00 00.

Byte reversal cannot translate between these representations. A varint decoder must accumulate groups, reject overlong or overflowing representations according to the format, and stop at the terminating byte. Endianness describes the order of the payload groups, but the grouping and termination rules remain essential. Protocol Buffers wire encoding

Floating point adds a representation contract

In IEEE binary32, positive 1.0 has the bit pattern 0x3f800000. If a format stores that pattern big-endian, its bytes are 3f 80 00 00; little-endian storage gives 00 00 80 3f. The integer expression (uint32_t)1.0f instead yields the integer value 1, so it cannot be used to serialize the floating-point bit pattern.

On a platform whose float representation and size have been verified to match the format, memcpy between a float and a uint32_t can preserve the object representation without an incompatible-pointer dereference. Then encode or decode the integer bits. A size check by itself does not establish IEEE compatibility, and a byte-order check does not settle NaN handling, signed zero, or mixed floating-point word layouts. Use a format-aware library when those assumptions cannot be guaranteed. XDR’s explicit floating-point rules are an example of a contract that goes beyond “four bytes.” RFC 4506 floating-point format

8. How loads stores and conversions fit together

A native load interprets memory according to the instruction’s defined representation. A native store performs the reverse mapping. Software can also operate one byte at a time and assemble a value explicitly.

The load and store machinery maps byte positions to the corresponding bits of the operand. It does not reverse all of RAM when an opposite-endian field appears. Cache lines and DMA transfers can carry bytes without understanding the application’s field boundaries. The interpretation enters when an operation treats those bytes as a larger value.

A register holds bits with defined significance; describing it as a sequence of addressed memory bytes is usually the wrong starting point. Register diagrams, subregister operations, vector lanes, and instructions still have their own specified mappings. Similarly, data byte order does not authorize reversing instruction bytes. Machine-code decoding follows the instruction-set encoding.

Two operations that often look identical in assembly have different intent:

  • A byte swap always reverses a specified number of bytes.
  • A host-to-format conversion ensures that a later store produces the required format. It may be a swap or a no-op, depending on the host.

For example, host-to-little-endian conversion is a no-op on ordinary x86 but a byte reversal on s390x. Host-to-big-endian conversion has the opposite behavior. GCC provides explicit byte-swap builtins for common widths. Prefer a library’s semantic conversion helper when the boundary is known, because its name records the intended representation. GCC byte-swapping builtins

An encoded scalar stored in an ordinary integer variable can be confusing. On a big-endian machine, a host-to-little-endian helper applied to 0x12345678 produces a scalar whose ordinary numeric printout may be 0x78563412. Its purpose is to produce bytes 78 56 34 12 when stored. Do not perform ordinary arithmetic on that encoded value and expect the original number’s arithmetic semantics.

The safest design makes encoded storage short-lived or gives it a distinct type. Decode into host values at input, validate and calculate there, then encode at output. If an API already accepts host-order values and performs the conversion, pass it the host value directly.

What the compiler can do with clear C

Explicit byte assembly does not necessarily imply four separate load instructions. For this article, compiling the load_be32 and load_le32 expressions with GCC 14.2.0, -O2, and the default x86-64 target produced the following function bodies, shown in Intel assembly syntax:

Big-endian decoder       Little-endian decoder
mov eax, DWORD PTR [rdi]  mov eax, DWORD PTR [rdi]
bswap eax                ret
ret

The compiler recognized the mathematical operation and selected a native load plus byte reversal for the non-native representation. This is an observation about that compilation, not a promise for every compiler, target flag, alignment context, or instrumentation mode. The source-level bounds and object-access requirements still matter even if the resulting instructions look like a cast-and-dereference shortcut.

Architectures can provide dedicated byte-reversal or reversed-load operations. Their existence does not change the ABI’s native object representation. Prefer a clear codec or established intrinsic, inspect the generated code when performance matters, and benchmark the complete workload. An instruction count alone says little about a memory-bound parser or an I/O-bound driver.

The same caution applies when optimized code no longer contains a visible swap. A conversion might legitimately be a no-op on this host, be folded into a load, or cancel another conversion. Disassembly helps explain how the compiler implemented the program; it cannot establish that the program chose the correct external contract.

9. Portable C without alignment or aliasing traps

This tempting parser has several independent problems:

/* Not a portable parser for an arbitrary byte buffer. */
uint32_t value = *(const uint32_t *)(buffer + offset);

The buffer may be too short. The address may be insufficiently aligned. The access may violate C’s effective-type rules. And a successful native load still uses the host’s representation rather than the format’s. A byte-swap added afterward fixes only the last issue, when a swap is actually required. SEI CERT treats pointer alignment and incompatible-type access as separate hazards. CERT EXP36, CERT EXP39

For ordinary memory containing an octet-based format, explicit byte assembly is straightforward:

#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <limits.h>

_Static_assert(CHAR_BIT == 8, "This format uses 8-bit bytes");

/* p points to at least four readable bytes of ordinary memory. */
static uint32_t load_be32(const unsigned char *p)
{
    return ((uint32_t)p[0] << 24) |
           ((uint32_t)p[1] << 16) |
           ((uint32_t)p[2] << 8)  |
            (uint32_t)p[3];
}

static uint32_t load_le32(const unsigned char *p)
{
    return  (uint32_t)p[0]        |
           ((uint32_t)p[1] << 8)  |
           ((uint32_t)p[2] << 16) |
           ((uint32_t)p[3] << 24);
}

/* p points to at least four writable bytes of ordinary memory. */
static void store_be32(unsigned char *p, uint32_t value)
{
    p[0] = (unsigned char)(value >> 24);
    p[1] = (unsigned char)(value >> 16);
    p[2] = (unsigned char)(value >> 8);
    p[3] = (unsigned char)value;
}

static bool read_be32_at(const unsigned char *buffer,
                         size_t length, size_t offset,
                         uint32_t *out)
{
    if (buffer == NULL || out == NULL)
        return false;
    if (offset > length || length - offset < 4)
        return false;
    *out = load_be32(buffer + offset);
    return true;
}

The casts happen before the shifts, avoiding signed overflow on 32-bit-int targets. If an unusual implementation promotes these operands to a wider signed integer, the intermediate results remain representable. The bounds check uses subtraction after checking offset <= length, avoiding an overflowing offset + 4 test. The caller must still ensure that length describes the actual accessible buffer and out points to a valid result object. These routines are for ordinary memory, not MMIO.

The code intentionally requires an eight-bit C byte and the availability of uint32_t. ISO C does not require every implementation to provide an exact 32-bit unsigned type. C’s object representation, integer, and shift rules explain these requirements. C11 committee draft N1570, Sections 6.2.6, 6.5.7 and 7.20.1.1

Another valid pattern is to memcpy the bytes into a properly aligned integer object, then apply the platform’s format-to-host helper. The copy solves the problematic typed load; it does not by itself decode the bytes. On Linux userspace, <endian.h> provides helpers such as le32toh() and be32toh(), with feature-test and portability considerations documented by the C library. These are not ISO C interfaces. Linux endian interfaces

In kernel code, use the existing unaligned helpers, such as get_unaligned_le32() and put_unaligned_be32(), where appropriate. Their endian-specific forms combine the unaligned access and representation conversion. Do not decode again afterward. Linux unaligned-access guidance

10. Extend the codecs without weakening the checks

Once byte assembly is understood, wider and narrower fields follow naturally. The following helpers retain the earlier assumptions: eight-bit bytes, the named exact-width types, ordinary memory, and enough readable or writable bytes at the pointer.

static uint16_t load_be16(const unsigned char *p)
{
    return (uint16_t)(((uint32_t)p[0] << 8) | (uint32_t)p[1]);
}

static uint64_t load_le64(const unsigned char *p)
{
    return (uint64_t)load_le32(p) |
           ((uint64_t)load_le32(p + 4) << 32);
}

static uint64_t load_be64(const unsigned char *p)
{
    return ((uint64_t)load_be32(p) << 32) |
            (uint64_t)load_be32(p + 4);
}

static uint32_t load_be24(const unsigned char *p)
{
    return ((uint32_t)p[0] << 16) |
           ((uint32_t)p[1] << 8)  |
            (uint32_t)p[2];
}

static void store_le64(unsigned char *p, uint64_t value)
{
    for (unsigned i = 0; i < 8; ++i)
        p[i] = (unsigned char)(value >> (8U * i));
}

For sixty-four-bit decoding, the cast precedes the shift by 32. Shifting a thirty-two-bit operand by its own width would be invalid on a conventional implementation. Parentheses also make the intended grouping explicit.

A twenty-four-bit field needs only three bytes. Reading four and masking the extra byte afterward can cross the end of a buffer, touch an inaccessible page, or consume a byte with device side effects if someone incorrectly adapts the code to MMIO. “The extra bits are discarded” is not an access-safety argument.

For a signed two’s-complement twenty-four-bit field, the sign bit is bit 23. After u = load_be24(p), an interpretation in a wider signed type is:

int64_t signed24 = (u & UINT32_C(0x800000))
                 ? (int64_t)u - INT64_C(16777216)
                 : (int64_t)u;

This is a numeric interpretation after decoding. Reversing bytes and sign-extending are separate operations; perform them in the appropriate order. If the field uses sign-magnitude, biased values, or another signed representation, this two’s-complement rule is wrong even when its bytes are in the expected order.

Reusable codecs should expose their preconditions plainly. The low-level helpers above do not receive a length, so the caller must check it. A parser can instead centralize cursor advancement in checked functions, but the checks must precede pointer formation and access. Do not let a tidy helper name obscure an unchecked read.

11. Parse a complete mixed order record format

Individual integers are easy to decode correctly while the surrounding parser remains unsafe. A complete example connects byte order with field offsets, lengths, versioning, and buffer lifetime.

Consider a fictional format called BORD. It deliberately uses different orders for different numeric fields so that native-load assumptions are visible. This is a teaching format, not a recommendation to mix orders in a new protocol.

Header offset   Size    Meaning                   Representation
0               4       Magic                    42 4f 52 44
4               1       Version                  1
5               1       Flags                    Bits 0 and 1 allowed
6               2       Header size              BE unsigned, must be 16
8               4       Number of records        LE unsigned
12              4       Payload size in bytes    BE unsigned

Each record has exactly 12 bytes
Record offset   Size    Meaning                   Representation
0               4       Identifier               BE unsigned
4               8       Timestamp ticks          LE unsigned

The payload contains exactly the declared records with no trailing bytes. Timestamp ticks are a format-defined unsigned counter; this example assigns no real-world epoch. Version 1 allows no header extensions. Reserved flag bits must be zero.

The byte fixture below contains two records. Every line is written in increasing file-offset order:

0000  42 4f 52 44 01 03 00 10 02 00 00 00 00 00 00 18
0010  01 02 03 04 08 07 06 05 04 03 02 01
001c  a0 b0 c0 d0 88 77 66 55 44 33 22 11

Its header declares 24 payload bytes. Record zero decodes to identifier 0x01020304 and ticks 0x0102030405060708. Record one decodes to identifier 0xa0b0c0d0 and ticks 0x1122334455667788. The bytes do not change when the parser runs on another host.

Here is a bounded parser using the preceding codecs. Its result holds host-order metadata and a borrowed pointer into the original buffer:

#include <string.h>

enum bord_result {
    BORD_OK,
    BORD_BAD_ARGUMENT,
    BORD_SHORT_HEADER,
    BORD_BAD_MAGIC,
    BORD_BAD_VERSION,
    BORD_BAD_FLAGS,
    BORD_BAD_HEADER_SIZE,
    BORD_BAD_LENGTH
};

struct bord_view {
    unsigned char flags;
    uint32_t count;
    const unsigned char *records;
};

struct bord_record {
    uint32_t identifier;
    uint64_t timestamp_ticks;
};

static enum bord_result parse_bord(const unsigned char *p,
                                   size_t n,
                                   struct bord_view *out)
{
    static const unsigned char magic[4] = {0x42, 0x4f, 0x52, 0x44};
    uint32_t count, payload;

    if (p == NULL || out == NULL)
        return BORD_BAD_ARGUMENT;
    if (n < 16)
        return BORD_SHORT_HEADER;
    if (memcmp(p, magic, sizeof magic) != 0)
        return BORD_BAD_MAGIC;
    if (p[4] != 1)
        return BORD_BAD_VERSION;
    if ((p[5] & 0xfcU) != 0)
        return BORD_BAD_FLAGS;
    if (load_be16(p + 6) != 16)
        return BORD_BAD_HEADER_SIZE;

    count = load_le32(p + 8);
    payload = load_be32(p + 12);
    if (payload != n - 16 || payload % 12 != 0 ||
        count != payload / 12)
        return BORD_BAD_LENGTH;

    out->flags = p[5];
    out->count = count;
    out->records = p + 16;
    return BORD_OK;
}

static bool bord_record_at(const struct bord_view *view,
                           uint32_t index,
                           struct bord_record *out)
{
    const unsigned char *p;

    /* view must be an unchanged result of successful parse_bord(). */
    if (view == NULL || out == NULL || index >= view->count)
        return false;
    p = view->records + (size_t)index * 12;
    out->identifier = load_be32(p);
    out->timestamp_ticks = load_le64(p + 4);
    return true;
}

Several decisions are doing useful work here.

Validate before accessing. The parser checks the fixed header length before reading any field beyond the argument itself. The caller must still supply the actual accessible length. No API can validate a fabricated length without an independent description of the allocation.

Avoid overflowing the length expression. After establishing n >= 16, the parser compares the declared payload against n - 16. It validates the number of records by division and remainder instead of calculating an unchecked count * 12. A successful parse establishes that every allowed record index fits within the validated payload.

Separate the view from the serialized layout. The host structures have no packed attribute and no promised on-disk layout. Their padding is irrelevant because they are never copied wholesale to or from the file. Each field is decoded at its specified offset.

Treat magic as bytes. The numeric byte constants specify the exact signature, rather than depending on the compiler’s execution character set for a string literal. Character encoding and integer byte order are independent concerns, including when code is ported between environments associated with ASCII or EBCDIC.

Preserve lifetime and immutability. The view borrows storage. The original buffer must remain alive and unchanged while records are read, and callers must not manufacture or alter the view. If another thread, device, or mapped-file writer can change the backing data, validation followed by later access needs a separate synchronization or snapshot design. Correct byte decoding does not prevent a time-of-check/time-of-use race.

For a production parser, add format-appropriate resource limits, structured diagnostics, and fuzzing. Rejecting a truncated file does not prevent a valid but enormous input from consuming excessive memory or CPU elsewhere in the application.

12. Structures bit fields and signed values

Writing sizeof(struct header) bytes to a file is not a portable serialization format. Structure padding, field widths, alignment, and byte order can differ. Padding can also expose bytes that were never intended to be part of the message.

Packing a structure addresses some layout padding, but it does not automatically assign the required byte order to its fields. It can create unaligned members, and taking an ordinary pointer to a packed member may lose the compiler’s knowledge that special access is necessary. Use explicit codecs for portable formats, or a carefully specified ABI with verified offsets, sizes, and access rules. Linux unaligned-access guidance

C bit-field allocation is implementation-defined. A declaration such as unsigned flag:1; unsigned mode:3; is therefore not a portable statement of wire bit positions. Decode the containing integer first and use masks and shifts on the host-order value. A byte swap cannot repair a bit-field layout that the compiler allocated differently. C11 committee draft N1570, Section 6.7.2.1

For a decoded host-order field:

uint32_t flags = load_le32(bytes);
unsigned mode = (unsigned)((flags >> 8) & UINT32_C(0x7));
bool enabled = (flags & UINT32_C(0x1)) != 0;

The example assumes that the format assigns mode to numeric bits 8 through 10 and enabled to numeric bit 0. If its diagram uses most-significant-first numbering, translate the numbering before choosing masks.

Signed fields require a signed-encoding rule as well as byte order. For an explicitly specified two’s-complement signed 32-bit field, first decode the bits into uint32_t. A portable way to interpret the result in a wider integer is:

int64_t signed_value = (u <= INT32_MAX)
                    ? (int64_t)u
                    : (int64_t)u - INT64_C(4294967296);

Here u is the decoded unsigned value. This avoids depending on an out-of-range unsigned-to-signed cast under older C language rules. Validate the range required by the application before narrowing further.

13. Translate specification bit numbers into masks

Byte diagrams are only half of register decoding. The numbering printed over a field can refer to most-significant-first positions even when the C expression will use least-significant-first numeric shifts.

Suppose a thirty-two-bit specification numbers positions 0 through 31 from the most significant end. It defines an enable flag at specification position 0 and a four-bit mode field at positions 20 through 23. These map to numeric bit 31 and numeric bits 11 through 8 respectively:

Specification positions      0            20 21 22 23          31
Numeric bit positions        31           11 10  9  8           0
Enable mask                  80000000
Mode mask                    00000f00

For enable set and mode ten, the decoded host value is 0x80000a00. A big-endian stored field would contain 80 00 0a 00; a little-endian stored field would contain 00 0a 00 80. Once the correct decoder or MMIO accessor has returned the host value, the masks are identical on x86 and s390x:

bool enable = (value & UINT32_C(0x80000000)) != 0;
unsigned mode = (unsigned)((value >> 8) & UINT32_C(0xf));

There are two separate translations: bytes become the host integer, then specification positions become numeric shifts. Swapping the value a second time because “IBM counts bits differently” breaks the first translation without correctly performing the second.

For a field spanning most-significant-first positions first through last, inclusive, the numeric right shift is 31 - last, and the field width is last - first + 1. For unsigned positions, check first <= last && last < 32 before using those expressions. For signed positions, also require first >= 0. A generic mask builder must also handle a width of 32 without evaluating 1U << 32.

In kernel code, facilities such as FIELD_GET and FIELD_PREP can make already-correct masks easier to use. They do not discover the device’s numbering convention or perform an arbitrary endian decode for you. Linux’s packing API goes further for some irregular layouts, distinguishing byte placement, thirty-two-bit word ordering, and bit reversal within bytes. Choose it only after matching the actual layout to its documented quirks. Linux bitfield helpers, Linux packing API

Keep access semantics in the review as well. A read-modify-write expression can preserve the right bit positions and still be invalid for a write-one-to-clear register or a register changed concurrently by hardware. A correct mask is not permission to use an arbitrary update sequence.

14. Use the language or platform codec

Handwritten byte assembly is useful for understanding and testing. Production code should also consider established interfaces:

  • POSIX socket code: htons, htonl, ntohs, and ntohl handle 16-bit and 32-bit network-order values. The l suffix does not mean the width of the platform’s C long; htonl is a 32-bit interface. Linux byteorder interfaces
  • C++: C++20 supplies std::endian; C++23 supplies std::byteswap for suitable integral types. std::byteswap always swaps, so use the known format and native order to decide whether it is needed. The standard also allows native ordering that is neither uniformly little nor uniformly big. C++ endian definitions, C++ byteswap specification
  • Python: struct.unpack(">I", data) and struct.unpack("<I", data) decode a four-byte unsigned integer explicitly. Avoid the default native format for a portable wire format; = still uses native byte order even though it standardizes sizes and omits alignment padding. Python struct documentation
  • Rust: u32::from_be_bytes, u32::from_le_bytes, to_be_bytes, and to_le_bytes state the boundary directly. Rust integer byte-conversion methods
  • Java: a ByteBuffer starts in big-endian order. Set its order explicitly when the format requires otherwise, and pay attention to the byte order captured by typed views. Java ByteBuffer documentation

When a library parser already returns a numeric value, do not swap it because the input was big-endian. The parser’s job may already have been to perform exactly that decoding.

15. PCIe has several different boundaries

For a Linux PCI driver, separate at least these three paths:

  1. Configuration space: use PCI configuration access functions such as pci_read_config_dword(). Their architecture-specific implementations return and accept host-order scalar values. Do not add another endian conversion. Check the return status before consuming a result.
  2. Device registers: use the documented MMIO accessors, access width, mapping, and register-specific byte order.
  3. DMA buffers and descriptors: ordinary memory shared with a device follows the device’s data format and DMA ownership contract.

Calling all three “PCIe data” conceals the interfaces that make them work. PCIe transport does not supply the semantic layout of every vendor-defined descriptor or application payload. Linux’s own drivers illustrate the distinction: mlx5 work-queue structures contain big-endian fields, while Xilinx XDMA descriptors contain little-endian fields. The device ABI decides. mlx5 work-queue structures, XDMA descriptor definitions

For s390x, this layering is visible in public Linux source. Architecture-specific zPCI access routines implement the low-level operations, while the driver-facing interfaces provide their established contracts. A portable driver should not replace those interfaces with assumptions about an ordinary CPU load from a BAR. Linux s390 PCI implementation

16. Follow a value through the Linux PCI layers

An endian audit becomes more useful when it follows one value through actual interfaces. Linux v6.12 on s390x provides a revealing example: the driver’s scalar value, the I/O token, the architecture’s instruction operands, and a descriptor’s stored bytes are different objects. Treating them as interchangeable loses information that debugging needs.

A number, an encoded object, and an I/O token

Suppose a device specifies a little-endian 32-bit length field containing 0x00010203. Its bytes at increasing offsets must be 03 02 01 00. A CPU-native u32 length represents the mathematical number 66051 on both x86 and s390x. If stored as ordinary native memory, that object’s bytes differ between those hosts.

An __le32 encoded = cpu_to_le32(length) has another purpose: storing it produces the required four bytes. On s390x, printing its bit pattern as an ordinary unsigned integer would show 0x03020100. That diagnostic does not prove corruption. To inspect the intended number, decode it with le32_to_cpu(encoded); to inspect the representation, examine its bytes while the CPU owns the memory.

Now consider writel(length, register_address). The argument remains the mathematical number. In the generic v6.12 implementation, writel() performs the little-endian conversion before the raw write. The corresponding readl() converts the raw result before returning it. Consequently, a log immediately before writel() should record a host value, while a dump of a descriptor should record encoded bytes. They are not expected to look identical as native integer printouts. Generic I/O implementation

The register address is a third category. A void __iomem * is an access token, not an encoded numeric field and not a DMA address. Converting its byte order would corrupt the token rather than adapt the register access.

The s390 implementation makes this distinction concrete. In v6.12, pci_iomap_range() selects between two paths. Without the Memory I/O facility, pci_iomap_range_fh() records the device’s function handle and BAR in an internal mapping table, then returns a token containing a table index and offset. The token identifies an operation to perform; it is not a promise that a normal C pointer dereference can load the register. With Memory I/O available, the mapping path instead uses the BAR’s MIO address. Both paths remain behind the same driver-facing interface. s390 PCI mapping and configuration code

For a standard 32-bit register read, the relevant layering is:

driver readl(token + register_offset)
    generic readl conversion and ordering hooks
        s390 raw accessor: zpci_read_u32
            zpci_load
                function-handle/cookie path, or MIO instruction path

The s390 I/O header maps raw operations to the zPCI helpers and includes the generic I/O implementation. The function-handle path resolves the table entry, constructs an instruction request from the function handle, BAR and width, and supplies the offset separately. The MIO path uses its own instruction form. These are implementation details explaining the abstraction, not interfaces a portable driver should duplicate. s390 I/O definitions, zPCI instruction implementation

The practical consequence extends beyond byte swapping: replacing readl() with a volatile dereference can bypass address interpretation and the required instruction as well as conversion and ordering. A successful experiment on one mapping path does not validate that replacement on another.

Configuration access includes an error contract

Configuration space takes a separate route. The s390 zpci_cfg_load() converts and positions the instruction result before returning a scalar through the PCI interface. zpci_cfg_store() prepares the reverse representation. A driver should consume the resulting number directly and check the operation’s status first.

u16 command;
int ret;

ret = pci_read_config_word(pdev, PCI_COMMAND, &command);
if (ret)
        goto config_error;  /* Driver-specific error handling. */

/* command is now a host-order scalar. No le16_to_cpu(). */
bool master_enabled = (command & PCI_COMMAND_MASTER) != 0;

This deliberately reads rather than modifies the command register. Configuration writes can change device operation and must follow the driver lifecycle, not a generic read-modify-write recipe.

Access width matters here too. A 32-bit read-modify-write used to emulate a 16-bit update can write back neighboring status bits. If those bits are write-one-to-clear, preserving their numeric value in the temporary variable actually acknowledges them when written back. Linux’s pci_generic_config_write32() explicitly warns about this hazard on hardware limited to 32-bit configuration writes. Correct endianness does not make the wider access semantically equivalent. This is another reason to use the specified access width and established PCI helpers rather than consolidate accesses as an apparent optimization.

Do not diagnose 0xffff or 0xffffffff by swapping it: all-one patterns survive byte reversal. In the v6.12 configuration path, failures can produce an all-one error response; the generic access code can also reject a misaligned register request before assigning the output. Check status before examining output, and interpret successful values according to the particular register. Conversely, generic readl() exposes a value rather than a separate error return, so it cannot simply be treated like the configuration API. PCI access implementation

A 64-bit register has at least three ordering questions

Consider a fictional 64-bit counter split into two little-endian 32-bit registers: low bits at offset zero and high bits at offset four. Its stable value is 0x0123456789abcdef. The two readl() results should be 0x89abcdef and 0x01234567, independent of host byte order. Reconstruct the number as:

u64 value = ((u64)high << 32) | low;

Byte order within each register, placement of the halves, and required access sequence are separate decisions. Linux’s hi_lo_readq() reads the high half first but still finds that half at offset four for its little-endian layout. Thus “high first” does not mean “lowest address first.” In contrast, ioread64be_hi_lo() reads the high half at offset zero and the low half at offset four, using ioread32be() for each. The suffixes encode different parts of the contract. 64-bit high/low access helpers

A helper that performs two reads does not make a changing counter an atomic snapshot. If the device specifies a latch on the first read, follow that sequence. A high-low-high retry algorithm is suitable only when the documented counter behavior and side effects make it valid; it is not a universal replacement for the hardware protocol. Likewise, a 64-bit CPU does not establish that a device accepts a single 64-bit transaction.

17. MMIO conversions belong to the accessor

For the standard little-endian MMIO register contract, Linux’s readl() returns a host-order u32, and writel() takes a host-order u32. Thus this is the intended shape:

u32 status = readl(regs + STATUS_OFFSET);
writel(command, regs + COMMAND_OFFSET);

This commonly seen “fix” is wrong for that contract:

/* Wrong: duplicates the accessor's endian conversion. */
u32 status = le32_to_cpu(readl(regs + STATUS_OFFSET));
writel(cpu_to_le32(command), regs + COMMAND_OFFSET);

On a little-endian host, the extra conversions are no-ops and can escape testing. On a big-endian host, they change the value incorrectly. For a genuinely big-endian register bank, select an appropriate accessor such as ioread32be() or iowrite32be(), according to the device and architecture API. Do not improvise by layering arbitrary swaps around an unrelated accessor. Linux device I/O API

Other MMIO details are equally important:

  • A register may require exactly one 32-bit access; four byte accesses might trigger four operations or be unsupported.
  • Raw and relaxed accessors have different guarantees. A familiar-looking function name is not a reason to omit ordering analysis.
  • A 64-bit register accessed as two 32-bit halves may require low-first or high-first access, a latch operation, or a retry loop. Byte order does not establish atomicity.
  • Repeated or FIFO accessors are not interchangeable with a loop of scalar register accesses. Check their byte-preservation semantics.
  • Reads may clear status, acknowledge events, or advance a FIFO. A speculative debugger read can affect the system.

Treat __iomem as an interface boundary. A volatile cast is not a portable replacement for the Linux I/O API. volatile does not supply the required architecture-specific instruction, endian conversion, or complete device-ordering contract. The Linux kernel separately documents why volatile is not a synchronization primitive. Linux volatile guidance

18. DMA descriptors need explicit representation and ownership

A descriptor in RAM can contain an address, a length, flags, and a device-ownership bit. Suppose a particular fictional device defines these fields as little-endian:

/* Teaching example only: the real device defines layout and alignment. */
struct example_desc {
    __le64 address;
    __le32 length;
    __le32 flags;
};

/* The CPU owns d, and dma is a valid device DMA address. */
d->address = cpu_to_le64((u64)dma);
d->length  = cpu_to_le32(length);

Here the conversion is necessary because these are normal memory stores, not writel() calls. Conversely, a DMA API maps and synchronizes memory for device access; it does not parse the descriptor’s fields or convert a payload’s byte order. A DMA address also must not be fabricated by casting a CPU virtual pointer. Linux DMA API HOWTO

Publishing a descriptor has a second, independent requirement: the device must not observe ownership before it can observe the descriptor contents. A simplified coherent-memory example is:

/* Assumptions: CPU-owned coherent descriptor; device-defined protocol;
 * aligned flags store of the required width; device cannot reuse d yet. */
d->address = cpu_to_le64((u64)dma);
d->length = cpu_to_le32(length);
dma_wmb();
WRITE_ONCE(d->flags, cpu_to_le32(DEVICE_OWN));
writel(queue_tail, regs + DOORBELL_OFFSET);

This is a pattern to reason about, not a drop-in driver. It assumes a device protocol in which the ownership store is valid and sufficient, with reserved bits handled as required. This example assumes default I/O mapping attributes for the doorbell. dma_wmb() orders descriptor contents before ownership publication; normal writel() orders prior coherent-memory writes before the doorbell. DMA barriers do not themselves order MMIO. Streaming buffers additionally require the appropriate DMA mapping or synchronization protocol; that requirement does not replace publication ordering.

Under a particular device protocol, the device may clear an ownership bit only after writing the result fields. The CPU must first observe completion and then use the appropriate DMA read barrier before consuming those fields, when the device’s protocol and memory mapping provide that guarantee. READ_ONCE() alone does not establish the whole ordering relationship. Linux memory-barrier documentation

Coherent memory, ordered accesses, and completed posted writes are three different properties. A barrier does not necessarily make a posted PCI write reach the device before the next line of code executes. When the driver must establish that posted writes have reached the device, the device and bus API may require a safe readback. This establishes write arrival, not completion of the operation commanded by that write. That read must be safe and valid for the device state; never choose a random register. Linux device I/O API

19. Trace both the descriptor and its payload

A realistic receive queue often combines a coherent descriptor ring with separately mapped streaming payload buffers. The descriptor can be CPU-visible without a cache-maintenance operation while its payload still requires synchronization. Treating “the DMA buffer” as one undifferentiated object obscures this distinction.

For a fictional device, suppose a coherent descriptor contains little-endian address, capacity, actual, and control fields. The hardware guarantees that it writes the received payload and actual before clearing DEVICE_OWN, then stops accessing the buffer until reposted. The driver serializes CPU access to the slot. Descriptor alignment, field offsets, reserved bits, and atomic access width have already been checked against that ABI.

Before first publication, map a suitable receive buffer with dma_map_single(..., DMA_FROM_DEVICE) and check dma_mapping_error(). Store the returned dma_addr_t in software state and encode it into the descriptor’s address field. Retain the original mapped extent and direction for later synchronization and unmapping. Do not use the device’s reported completion length as a replacement for those saved mapping parameters. DMA mapping guide

Publication follows the earlier data-before-ownership pattern. Completion needs the reverse relationship:

/* Coherent descriptor for a submitted request; exclusive CPU slot handling. */
u32 control = le32_to_cpu(READ_ONCE(d->control));

if (control & DEVICE_OWN)
        return;                 /* Device still owns this operation. */

dma_rmb();                      /* Acquire the device-published result. */
u32 received = le32_to_cpu(READ_ONCE(d->actual));

if (received > capacity)
        goto bad_completion;    /* Do not index or copy using this length. */

dma_sync_single_for_cpu(dev, payload_dma, mapped_size, DMA_FROM_DEVICE);
consume_received_bytes(payload, received);

These are illustrative statements inside a driver, not a complete function. capacity is the validated posted capacity, no larger than the actual buffer. consume_received_bytes() finishes its reads before returning and does not retain the buffer. The error path must preserve ownership and perform the driver’s recovery procedure. A memory barrier cannot make a device obey an ownership promise it never made. DMA ownership barriers

To reuse the persistent mapping, finish CPU access, perform the required device-side synchronization, initialize completion fields as the ABI requires, publish ownership after dma_wmb(), and notify the device through the normal MMIO accessor. Do not repost while an upper layer retains the payload. If the mapping is retired instead, unmap with the saved parameters after establishing that DMA has stopped. A timeout alone does not establish that condition.

An interrupt is similarly a reason to inspect the completion protocol, not permission to read every slot. Shared queues can contain completed and active entries at once. Any generation or phase field must be checked according to the device ABI so that an old completion cannot authorize access after ring wraparound.

A forensic record that separates the failure classes

Suppose this queue works on x86 but fails on s390x. Capture a single controlled operation rather than spraying reads across live registers. Record the slot and generation, validated host capacity, saved mapping extent and direction, descriptor bytes while CPU-owned, host-order doorbell argument, and completion status after the ownership test. Log the result of the actual register access; do not introduce a second read of a potentially destructive register for the log.

For the length 0x00010203, descriptor bytes 00 01 02 03 on s390x suggest a missing little-endian encoding. Correct descriptor bytes with a doorbell value altered only on s390x suggest a duplicate conversion at the MMIO boundary. Correct descriptor data with an implausible completed length may instead point to a wrong slot, stale completion, layout mismatch, or missing synchronization. These are hypotheses to test, not diagnoses from one hex value.

Take snapshots at legal ownership points. A byte dump made while hardware updates the descriptor may combine several moments and manufacture an apparent endian problem. Additional logging also changes timing, so a failure that disappears under instrumentation warrants lifecycle and ordering analysis. Preserve the distinction between submitted writes, device-visible writes, completed work, and CPU-readable results throughout the investigation.

20. A complete boundary example

Consider a fictional queue-length value received from a network message and then passed to a PCI device:

Network field                 bytes 00 00 10 00, specified as BE
After network decoding        host value 4096
After range validation        host value 4096
LE descriptor length field    bytes 00 10 00 00
MMIO doorbell argument        host value defined by device protocol

On x86, the network decode generally needs a swap, while the descriptor encoding generally does not. On s390x, the network decode can be a no-op, while the descriptor encoding needs a swap. The sequence of semantic operations is identical on both machines.

If the doorbell encodes a producer index rather than the byte count, use that index. A correct endian conversion of the wrong quantity is still a driver bug. Likewise, a descriptor may use units of blocks rather than bytes or reserve high bits for flags. Width, units, layout, and ownership belong in the boundary contract alongside byte order.

21. Debug from raw bytes toward meaning

When a number looks wrong, preserve evidence before adding a swap. A reliable investigation proceeds in this order.

Identify the boundary. Write down the field’s offset, width, signedness, representation, units, and owner. Record whether the observed object is raw storage or an already decoded scalar.

Inspect bytes first. For an ordinary file, od -An -tx1 -v file.bin displays individual bytes. In GDB, compare a byte view with an interpreted word view:

(gdb) show endian
(gdb) x/16bx buffer
(gdb) x/4wx buffer

GDB’s b unit is a byte and w is four bytes. The word view uses the debugger’s target interpretation; the byte view is the starting point for checking an external format. Changing set endian does not change the bytes or repair the producer. GDB memory examination, GDB target byte order

Use a recognizable nonsymmetric value. 0x01234567 and 0x89abcdef distinguish byte positions well. Zero and all-one test patterns survive reversal and are poor first probes. For a 64-bit field, use eight distinguishable bytes so that swapping 32-bit halves cannot masquerade as a full correction.

Decode both ways without changing the source. Python is convenient for an offline check:

import struct

raw = bytes.fromhex("78 56 34 12")
print(hex(struct.unpack("<I", raw)[0]))  # 0x12345678
print(hex(struct.unpack(">I", raw)[0]))  # 0x78563412

Find the first disagreement. Compare the producer’s intended value, the bytes after encoding, the bytes observed by the consumer, and the value after decoding. Log representation explicitly, for example length_raw versus length_host. Seeing 0x78563412 in a log is inconclusive until you know which one it represents.

Check neighboring explanations. A wrong field offset, truncated width, unaligned access, stale DMA cache line, missing ownership barrier, word-lane swap, or incorrect bit numbering can resemble a byte-order problem. A value that changes when logging is added deserves ordering and lifetime analysis as well as endian analysis.

For MMIO, first consult safe-read rules. Use driver instrumentation or a documented diagnostic interface rather than indiscriminately reading a live register range. For DMA, ensure the CPU owns the buffer and has performed any required synchronization before inspecting it.

22. Four debugging cases from symptoms to bytes

The following cases are constructed examples. They show how to reason from evidence without claiming that a particular symptom uniquely identifies endianness.

A length grows from four kilobytes to one megabyte

A message specifies a big-endian thirty-two-bit length of 4096. The captured bytes are 00 00 10 00. A native little-endian interpretation produces 0x00100000, or 1,048,576. A native big-endian interpretation produces the intended 0x00001000.

The useful evidence is not merely that the value is “too large.” It is that the same four bytes, interpreted with the wrong weighting, exactly explain the observed number. Compare the packet capture with the parser’s raw byte dump. If both contain 00 00 10 00 but the parsed value is 1,048,576, the disagreement is in decoding. If the capture already contains 00 10 00 00, investigate the producer instead.

The fix is a format-aware input decoder, followed by the normal length limit. Do not divide the result by 256 as a workaround. That numerical coincidence fails for other values and hides a malformed-input risk. After the fix, test at least 1, 255, 256, 4096, and a nonsymmetric high value, plus a short buffer.

A command works on x86 and fails on s390x

The code writes writel(cpu_to_le32(command), reg) to a standard little-endian register. With command = 0x01020304, the extra helper is a no-op on x86, so the bug is hidden.

On s390x, the helper produces the encoded scalar corresponding to reversed bytes, numerically 0x04030201 when treated as an ordinary host integer. writel() is then asked to write that different host value. Its own conversion correctly encodes the wrong argument, so the device sees the wrong number.

Instrument the value immediately before the accessor, not by repeatedly reading a potentially destructive register afterward. Check the device specification and the accessor contract. If both establish the standard little-endian register case, pass command directly to writel(). Do not change unrelated descriptor conversions: they may be necessary normal-memory stores.

A descriptor address has plausible halves in the wrong places

Suppose a fictional descriptor’s address is 0x0123456789abcdef, stored as one little-endian sixty-four-bit field. Its expected bytes are:

ef cd ab 89 67 45 23 01

A broken implementation splits the address into host high = 0x01234567 and low = 0x89abcdef, then stores high as LE at offset zero and low as LE at offset four. It produces:

67 45 23 01 ef cd ab 89

Each four-byte piece is internally correct, but the halves are reversed. A full eight-byte reversal produces a third wrong layout. Write out all eight offsets and compare them with the descriptor specification. If the format is truly one LE64 field, cpu_to_le64() into a correctly declared and aligned field is the natural representation conversion. If the specification defines two registers or two words, follow their independently documented offsets and access sequence instead.

Before changing code, confirm that this is the device-visible DMA address, not a CPU virtual address or an incorrectly truncated intermediate. An IOMMU mapping mistake can also make an address look unfamiliar. Endian analysis cannot reconstruct a DMA address that was never obtained correctly.

The dump is correct but the program still fails

A completion descriptor contains the expected little-endian length bytes. Logging makes the test pass more often. This does not justify adding a swap. Check whether the CPU observed the ownership transition before reading the fields, whether a DMA read barrier is required, and whether a streaming payload has been synchronized for CPU access.

Another possibility is that the program logs a fresh read but uses an earlier cached scalar in its actual logic. A third is a buffer-lifetime bug: the correct descriptor is being inspected after it has been reused. Mark log entries with the queue, slot, generation or sequence number where available, and stage of ownership. Those details connect a byte dump to the operation that actually failed.

Capture as little as necessary. Dumping unrelated memory or entire packets can expose private data and overwhelm the useful evidence. A field’s offset, its raw bytes, the decoded value, and the relevant lifecycle state often suffice.

23. Test the bytes as well as the round trip

A round-trip assertion is necessary but insufficient:

decode(encode(value)) == value

Two mutually incorrect functions can satisfy that assertion while violating the external format. Add independent golden-byte checks:

BE encode 0x01234567 -> 01 23 45 67
LE encode 0x01234567 -> 67 45 23 01
BE decode 89 ab cd ef -> 0x89abcdef
LE decode ef cd ab 89 -> 0x89abcdef

Include lengths shorter than a field, offsets at and beyond the buffer end, misaligned offsets in ordinary memory, boundary values, signed extrema where relevant, and malformed encodings. Test arrays field by field; do not reverse the whole buffer. Include realistic protocol fixtures generated independently of the implementation under test.

For drivers and low-level libraries, test on both a little-endian target and a big-endian target when supported. A big-endian emulator can expose missing or duplicate conversions that a little-endian build hides. It does not validate real hardware timing, PCI ordering, DMA coherency, or a physical device’s behavior.

Static and dynamic tools cover different failure classes. Linux Sparse’s restricted endian types, including __le32 and __be32, help catch accidental mixing with host-order values. Kernel builds can request Sparse checking with make C=1 or make C=2, subject to the project’s normal build setup. Linux Sparse documentation

Compiler warnings and sanitizers can identify suspicious casts, alignment violations, invalid shifts, and buffer errors. They usually cannot tell that a perfectly valid integer has the wrong protocol meaning. A clean sanitizer run therefore complements golden-byte tests rather than replacing them. GCC instrumentation options

24. Build a test suite that can falsify your assumptions

A useful test suite does more than prove that the author’s encoder and decoder agree. It tries to break the assumptions that make the code correct.

Start with independent fixtures. The BORD fixture is specified as bytes, with separately stated expected values. Its big-endian header length, little-endian count, big-endian payload length, and little-endian timestamps make whole-buffer reversal and one-size-fits-all parsing fail visibly.

Then vary one condition at a time:

  1. Truncate the file at every byte position before its complete length.
  2. Change each magic byte, the version, and every reserved flag bit.
  3. Supply a payload length that is too small, too large, or not a multiple of the record size.
  4. Supply a record count that disagrees with the payload length, including UINT32_MAX.
  5. Test an empty valid file and reject a record lookup in it.
  6. Place the same valid file at several byte offsets within a larger allocation.
  7. Verify first, last, and out-of-range record indexes.
  8. Confirm that successful values match golden results, rather than just round-tripping.

Offset tests exercise the bytewise parser’s alignment independence. Sanitizers help catch invalid accesses and shifts, but host-native byte-order mistakes can remain perfectly valid machine operations. Optimized builds matter too: undefined behavior sometimes remains hidden in a debug build and becomes observable only after optimization.

A second implementation can provide a useful cross-check. For BORD, a small Python script can use explicit <I, >I, and <Q formats to calculate the same results. Keep its offset logic independent enough that it does not simply copy the C implementation’s mistake. A common fixture and independently described expected values are stronger evidence than two implementations that share one generated decoder.

Exercise both endian targets when practical. Cross-compiling alone checks syntax and target-specific compilation; it does not execute the decoder. An emulator can execute a big-endian userspace binary and reveal assumptions hidden on x86. Even that does not validate a hardware driver’s interrupt timing, DMA visibility, mapping attributes, or register side effects.

When a real opposite-endian target is unavailable, an offline model can still expose a specific mistake. For example, interpret a four-byte buffer with both int.from_bytes(raw, "little") and int.from_bytes(raw, "big"), then simulate each helper’s stated contract. Label this as a model. It does not turn a little-endian process into a big-endian execution environment.

For fuzzing, keep failures reproducible by saving the smallest failing input and recording the build configuration. A parser failure should distinguish a clean rejection from a crash, sanitizer finding, hang, or accepted but incorrectly decoded result. Coverage is helpful, but reaching every line is not the same as exercising every representation boundary.

25. Design format evolution before migration becomes urgent

If you control a new file or protocol format, choose one clear representation for each field and write it down in byte offsets. Include a versioning strategy, exact widths, units, signed encodings, reserved-bit behavior, and length limits. Define whether trailing bytes are permitted and whether unknown fields may be skipped. Avoid native widths such as long, pointer-sized fields, or an unspecified “machine word.”

A magic value should help identify a format, not become a substitute for validating it. A byte-order marker can be useful in a format designed to support more than one representation, but the marker itself must be readable without already knowing the answer. Its scope also needs to be explicit: does it govern every numeric field, a subrecord, or only a particular array?

For a legacy native-endian file, record its producer architecture or format version before converting. Make a copy, parse with the old contract, validate semantic ranges, and emit the new canonical representation. Compare record counts and application-level invariants, not only file sizes. Retain enough provenance to explain ambiguous or rejected records.

Do not detect the format by selecting whichever interpretation produces a “reasonable” number unless that ambiguity is explicitly part of a recovery tool. Attackers and accidental corruption can produce values that are plausible under both orders. A reliable format supplies an unambiguous contract or reports that the available evidence is insufficient.

26. Choose fixes that preserve the contract

The right repair depends on where the first incorrect interpretation occurs.

  • An input parser uses native loads: replace them with explicit format-aware decoding, retaining bounds checks and valid access semantics.
  • A format is written with raw structures: define a stable field layout and serialize each field. Version the format if existing readers depend on the old representation.
  • The device register value is swapped twice: remove the redundant conversion and keep the correct MMIO accessor.
  • A descriptor field is stored in host order: use the device ABI’s explicit conversion helper at the memory boundary, then separately verify publication and ownership.
  • A legacy format is inconsistent: isolate its quirks in one codec with fixtures. Do not spread special-case swaps through business logic or driver control flow.
  • The boundary is opaque byte data: preserve it. Copying bytes may be the correct operation; numeric conversion may be the bug.

Avoid changing a file’s magic number or endian flag without converting the fields the flag describes. Avoid writing architecture-name conditionals throughout a parser. Avoid suppressing endian type warnings with force casts just to make a build pass. Each shortcut obscures the contract that should be made explicit.

For a large dataset, convert at a well-defined ingress or egress layer and benchmark before optimizing. Compilers can recognize idiomatic byte assembly or use byte-reversing instructions. Bulk conversion may be vectorized, but a vector shuffle must respect each element’s width: reversing sixteen bytes is not equivalent to reversing four independent 32-bit integers.

Some operations can safely avoid decoding, such as copying an opaque field or comparing two identically encoded byte strings for equality. Arithmetic, range checks, and most ordering comparisons should operate on decoded values unless the encoded representation’s properties are deliberately being used.

Atomic arithmetic is no exception. Applying a native atomic increment directly to an opposite-endian encoded integer does not generally increment the intended number. Decoding, incrementing, and encoding with separate operations is not atomic either. A shared counter needs a representation-aware synchronization design, not just an added byte swap.

27. Compare and optimize encoded data deliberately

Some operations have useful properties in an encoded representation. Others only appear to work because the test data is simple.

Consider two sixteen-bit unsigned values, 1 and 256:

Value       Big-endian bytes       Little-endian bytes
1           00 01                  01 00
256         01 00                  00 01

Lexicographic comparison of equal-width BE byte sequences puts 1 before 256, matching unsigned numeric order. The LE byte sequences compare in the opposite order. This can matter in database keys, sorted indexes, or binary search over a memory-mapped format.

Signed numbers need an additional transformation. For an exact thirty-two-bit signed value, converting to the corresponding unsigned representation and flipping numeric bit 31 maps signed numeric order into unsigned order. Encode that transformed value as BE32 to obtain a lexicographically sortable fixed-width key:

Original signed value       Transformed unsigned key
-2                          7ffffffe
-1                          7fffffff
 0                          80000000
 1                          80000001

This is a deliberate key encoding, not the raw two’s-complement file representation. It needs its own format documentation and inverse transformation. Floating-point ordering is more complicated because of the sign, negative zero, infinities, and NaNs; do not extend the integer trick casually.

Also distinguish numeric order from a protocol’s sequence-number order. Counters can wrap. RFC 1982 defines serial-number arithmetic for DNS precisely because an ordinary unsigned comparison does not describe every relevant relationship. Endian decoding recovers the number’s bits; it does not choose the application’s comparison semantics. RFC 1982 serial-number arithmetic

For performance, measure the actual bottleneck. Removing one byte-reversal instruction may have little effect when parsing is dominated by cache misses, bounds checks, allocation, or I/O. Fusing a load with conversion can be useful, but unaligned reads across cache-line or page boundaries may have different costs. SIMD shuffles need a mask that reverses each intended element, not the whole vector, and tails must remain within accessible memory.

Do not optimize ordinary memory code by substituting MMIO accessors, or optimize device code by borrowing an ordinary-memory trick. Their contracts differ even if a particular architecture emits similar instructions. Keep the portable implementation and its byte fixtures available as a reference when adding a specialized fast path.

Finally, preserve the point at which validation occurs. A fast decoder that materializes a large length earlier must not use that length for an allocation, offset, or loop before applying the format’s range limits. Representation conversion can be cheap; a premature interpretation can be expensive or unsafe.

28. A review checklist

Before accepting a binary interface, answer these questions:

  1. What is the exact size and unit of each field?
  2. Which fields are numbers, and which are opaque bytes?
  3. What byte order, bit numbering, signed encoding, and floating-point format apply?
  4. Which function turns encoded storage into a host value?
  5. Which function turns a host value into encoded storage?
  6. Does an accessor or parser already perform that conversion?
  7. Are length, offset, alignment, and object-access rules satisfied?
  8. Are structure offsets and required access widths verified?
  9. For shared memory or devices, who owns the buffer and what makes writes visible?
  10. Do tests compare against independently specified bytes on more than one host order?

Endianness becomes manageable when each layer has one clear job. The processor defines native loads and stores. The format defines external bytes. The codec translates between them. The I/O API supplies device-access semantics. The synchronization protocol determines when another agent may consume the data.

That division works for a small file parser and for a Linux driver crossing from big-endian s390x into PCIe devices. It also gives debugging a concrete target: locate the first boundary where the agreed representation stops matching the observed bytes, and repair that boundary without disturbing the others.

Source and example notes

The linked references are public primary specifications, official project documentation, or original vendor manuals. Historical publication dates are distinguished from current documentation dates. Linux source examples are linked to v6.12 for reproducibility; consult the source and documentation for the actual kernel being built. Device-specific requirements always take precedence over teaching examples.

The companion tests exercise the portable C codecs, the complete BORD parser, golden-byte cases, and malformed inputs in ordinary userspace memory. The MMIO and DMA snippets are explanatory patterns, not runnable or hardware-validated drivers. No claim of validation on an IBM Z machine or a physical PCIe device is made.

Practical companion: PCIe and s390x boundaries

Added 11 November 2026. The following companion extends the original article with offline byte and integer models.

A byte-order bug can survive every test on a little-endian workstation and appear as soon as the same driver runs on s390x. Another failure can look like byte order even when every conversion is correct: two register reads may belong to different moments in a changing counter.

The useful starting point is the contract at each boundary. Is a read returning a number, preserving a byte stream, or sampling one part of a changing value? This chapter develops three examples that make those distinctions visible: a FIFO copied into memory, a 64-bit value with independently ordered words and bytes, and a split counter crossing a rollover. The accompanying executable models use ordinary memory only. They do not access PCI devices or test a real s390x machine.

The Linux implementation references are pinned to v6.12 so that the claims can be checked against a specific source tree. Device documentation and the kernel actually being debugged still decide which access method is valid.

1. Choose the result before choosing the accessor

Consider a FIFO that provides this eight-byte stream through two 32-bit reads:

01 23 45 67 89 ab cd ef

There are two reasonable things a driver might want to do with it. It might want two numbers, interpreting each four-byte transfer as little-endian. Or it might want the eight original bytes, ready for a later packet or file-format parser. Those outputs have different contracts.

For portable Linux PCI code, readl() has the ordinary little-endian register contract. Its returned u32 is a host value. A loop that stores these returned values into a native u32 array produces the numbers 0x67452301 and 0xefcdab89 on either host. [1]

The array’s bytes depend on the host representation:

Logical little-endian host: 01 23 45 67 89 ab cd ef
Logical big-endian host:    67 45 23 01 ef cd ab 89

The big-endian array is a correct array of those two numbers. It is unsuitable only when the next stage expects the original opaque bytes. Calling it a broken readl() implementation would misdiagnose the problem. The conversion became visible when a host value was stored back into native memory.

Linux’s repeated accessors have the byte-stream contract. The device I/O documentation says that helpers such as readsl() and ioread32_rep() access the same address repeatedly and do not perform the big-endian byteswap used by ordinary scalar accessors. The first FIFO byte corresponds to the first memory-buffer byte regardless of host architecture. [2]

In the shown generic readsl() implementation, the I/O address stays fixed while the destination u32 pointer advances. A count of two means two 32-bit transfers and requires eight bytes of destination space. It does not mean two bytes. Nor does it mean reading offsets zero and four of a register window. memcpy_fromio() describes another kind of operation with an advancing I/O address. [3]

For a real FIFO, establish the allowed access width, buffer alignment, amount of available data and behavior of each read before using any accessor. Repeating a destructive read can consume data. Replacing an access with a different width can violate the device protocol even if the final byte sequence looks plausible.

The first debugging experiment

The lab models both interpretations explicitly:

scalar_array(FIFO32(stream), 2, "big")
repeated_stream(FIFO32(stream), 2, "big")

The first returns the two scalar values and their native memory representation. The second preserves the input bytes. Both record two accesses to the same logical port. Repeat the experiment with "little": the scalar array’s bytes now happen to match the stream. That coincidence explains why a byte-preservation bug can hide on an x86 development machine.

The test also checks the converse error. A preserved byte stream viewed as a native big-endian u32 array does not magically become the intended little-endian numeric fields. Decode those fields according to their format when numbers are needed. Choose one boundary for that conversion and make it visible in the code.

2. Follow the s390x path through the source

On s390 with CONFIG_PCI, v6.12’s architecture header binds __raw_readl to zpci_read_u32 before including the generic I/O header. The generic scalar readl() applies __le32_to_cpu around the raw read. Generic readsl() stores the raw result without that scalar conversion. The two paths therefore expose different contracts intentionally. [3, 4]

The source relationship can be read as:

Scalar value
readl -> __le32_to_cpu(__raw_readl(...))
      -> zPCI raw 32-bit read plus scalar conversion

FIFO byte stream
readsl -> repeated __raw_readl(...) -> native u32 stores
       -> zPCI raw 32-bit reads without scalar conversion

The ioread32_rep() alias to readsl() in the generic header is conditional on !CONFIG_GENERIC_IOMAP. Verify the selected implementation and configuration instead of treating a familiar function name as proof of the full path. [3]

zpci_read_u32() requests a four-byte load. The deeper zpci_load() implementation chooses the function-handle path or the MIO path using have_mio. Neither route makes an __iomem token an ordinary memory pointer that portable driver code may dereference. Use the supported mapping and accessor APIs. [4, 5]

There is another useful forensic detail in the wrapper: a failed zpci_load() causes zpci_read_u32() to return all ones. An observed 0xffffffff alone cannot establish whether the FIFO supplied those bytes or the access failed. Correlate it with the platform’s error information and device state. A byteswap leaves all ones unchanged, so changing conversion code cannot resolve that ambiguity. [4]

For a source-level investigation, record the exact kernel build, relevant configuration, mapping API, selected accessor definition and device register contract. A source trace is evidence about an implementation. It is not evidence that a particular device transaction succeeded.

3. Name word placement and byte order separately

Take the value 0x0123456789abcdef. Its high 32-bit word is 0x01234567; its low word is 0x89abcdef. Two independent choices determine the following eight-byte layouts:

Word at the lower addressByte order within each wordBytes in increasing address order
Low wordLittle-endianef cd ab 89 67 45 23 01
Low wordBig-endian89 ab cd ef 01 23 45 67
High wordLittle-endian67 45 23 01 ef cd ab 89
High wordBig-endian01 23 45 67 89 ab cd ef

These fixed vectors make a layout problem easier to describe than “the 64-bit value is mixed-endian.” State which word occupies each offset and how the four bytes inside that word encode its number. Chronological read order is a separate question: the word at the higher address can still be read first.

A single 64-bit byte reversal does not fix every mismatch in this table. If the hardware places the high word first but encodes each word little-endian, the bytes are 67 45 23 01 ef cd ab 89. Decode each 32-bit word as little-endian, then place the high word in bits 63 through 32. Reversing the whole eight-byte sequence would also exchange the words.

The lab’s encode64() and decode64() take separate word-order and byte-order arguments. They operate on exactly eight ordinary-memory bytes, reject invalid widths and out-of-range values, and test each mapping against a fixed external golden vector. A successful round trip alone would not establish correctness: a matching mistake in encoder and decoder could cancel out.

How Linux packing quirks express the same distinction

Linux’s packing API gives names to independent layout transformations. For a complete eight-byte buffer, no quirks produces the last row of the table, ordinary big-endian layout. QUIRK_LITTLE_ENDIAN reverses byte placement inside each 32-bit word. QUIRK_LSW32_IS_FIRST changes which word appears first. Combining those two produces the first row, ordinary little-endian layout for the full 64-bit value. [6]

This is why QUIRK_LITTLE_ENDIAN alone must not be read as “serialize the whole u64 little-endian.” Its documented scope is the four-byte word. QUIRK_MSB_ON_THE_RIGHT is a third transformation that reverses bit positions within each byte without moving the bytes. For example, byte 0x23 becomes 0xc4; that says nothing about serial-link bit timing. [6]

The accompanying source register contains the derived golden vectors for all eight quirk combinations. The executable codec lab tests the four word/byte layouts, not a port or conformance test of Linux’s general packing implementation. Keep those claims separate. In particular, the eight-byte examples do not establish behavior for arbitrary buffer lengths or device-specific bit fields.

4. Separate placement from read sequence

Now suppose two 32-bit registers expose a 64-bit counter. Even with both halves decoded correctly, two accesses can sample different counter states.

The v6.12 io-64-nonatomic-hi-lo.h helper hi_lo_readq() reads the little-endian high half at offset four and then the low half at offset zero. The companion lo_hi_readq() reads those same halves in the opposite temporal order. The header’s ioread64be_hi_lo() instead reads the big-endian high half at offset zero and the low half at offset four. [7]

There are four questions to answer:

  1. Which address holds each half?
  2. How is each half encoded?
  3. In which order must the accesses happen?
  4. What makes the combined observation coherent?

The cited header helpers perform two reads and combine them. They do not create a latch or add a retry. Architecture overrides and other implementations can differ, so this is a statement about those definitions, not a guarantee that every similarly named symbol on every build emits two transactions. [7]

5. Make a rollover failure reproducible

Let a free-running counter advance from 0x00000001ffffffff to 0x0000000200000000 between two reads. All numbers in this example are already decoded host values. No byte swap is involved.

Read low first, then high:

Low observation:  ffffffff  at counter 00000001ffffffff
High observation: 00000002  at counter 0000000200000000
Combined value:   00000002ffffffff

The combined result is ahead of both observations. Reverse the temporal order:

High observation: 00000001  at counter 00000001ffffffff
Low observation:  00000000  at counter 0000000200000000
Combined value:   0000000100000000

This result is behind both observations. Changing the order merely changes the failure in these traces. The defect is an incoherent sample across time.

The lab supplies the real counter value at each scripted read event as an oracle. That lets a test show exactly why the result is impossible within the observation interval. A driver does not possess this oracle, and the model does not simulate actual bus timing.

A bounded high low high experiment

For one explicitly defined hypothetical device, there is a useful retry scheme. Read the high half, then the low half, then the high half again. If the two high observations match, combine that high value with the low observation. Otherwise retry, up to a stated limit.

The proof requires independently readable, coherent halves of one incrementing binary counter and observations in the required order. It also requires no latching, destructive reads, reset, decrement or firmware rewriting. The exposed halves cannot lag independently. Finally, a high value must not wrap all the way around and return to its old value between the two high reads. Without an appropriate time/rate bound, matching high observations can be an ABA coincidence rather than evidence of stability.

The executable fixture uses a deliberately stronger bound: strictly fewer than 2**32 ticks may pass during one three-read attempt, with no full-width wrap. It checks that bound using the oracle. Real software must establish the device and timing assumptions elsewhere; it cannot infer them from this code.

In the rollover fixture, attempt one observes high values one and two and rejects the sample. Attempt two observes high value two on both sides of a low value of three, returning 0x0000000200000003. That equals the counter at the middle read, not necessarily its value when the function returns.

Retries have a separate termination requirement. The lab raises RetryLimit after the requested attempt budget instead of spinning forever. It rejects unsupported latch protocols, decreasing traces, missing events and invalid observation order. These guards test the stated model, not the safety of running a similar loop on unspecified hardware. If a device requires a snapshot command or a specific latch sequence, follow that protocol instead.

6. Capture evidence without changing the incident

Before adding debugging reads, establish whether the register is safe to reread. A FIFO, interrupt status register or clear-on-read counter can change the problem merely because it was inspected. Prefer logging the existing driver’s observations when that can answer the question without adding transactions.

For a FIFO problem, capture the destination buffer as bytes after its normal read. Record the transfer width, count, accessor and intended output contract beside the dump. A label such as “two LE32 values stored natively” explains a different result from “eight opaque stream bytes.” Do not diagnose from a debugger’s word-formatted display alone.

For a mixed layout, record the expected byte sequence with offsets before looking at a host integer. Use an asymmetric value such as 0x0123456789abcdef in an offline test or a documented safe test mechanism. Zero, all ones and repeated-byte patterns hide reversals. Do not write a test pattern into an arbitrary live register.

For a split counter, record each half’s decoded value and read sequence, along with any documented latch action. Keep a torn-read hypothesis open even when the byte layout is correct. Ordinary field logs usually do not reveal the true counter value at each instant, so they cannot reproduce the lab’s oracle-based proof by themselves.

Classify the evidence before changing code:

  • Correct scalar numbers but unexpected destination bytes suggest a representation or output-contract mismatch.
  • Correct bytes inside each word but exchanged halves suggest a word-placement mismatch.
  • Plausible individual halves but discontinuities near rollover suggest a snapshot or sequencing problem.
  • All-ones values on the cited s390 path leave both data and access failure in play.

These are hypotheses to test against the device specification and the actual source path, not signatures that prove a cause. Preserve the original observation and change one interpretation at a time.

7. Run the ordinary memory tests

The companion lab used for these examples runs from its lab directory:

python3 -B demo.py
python3 -B -m unittest -v test_models

The 22 tests passed on Python 3.12.14 on x86_64. They include fixed golden bytes, intentional wrong-layout controls, both modeled host byte orders, invalid arguments, bounded retry failure, and seeded cases. The deterministic demonstration output was checked against expected-output.txt.

The suite contains 100 seeded FIFO samples, 250 seeded codec values across all four layouts, 250 general counter traces and 100 forced-rollover samples, in addition to explicit edge cases. The fixed seeds make failures repeatable. They do not turn the samples into exhaustive verification.

Passing these tests establishes properties of the isolated byte and integer models. It does not establish native big-endian execution, compiler output, access barriers, bus transactions, FIFO wiring, mapping attributes, DMA correctness or any particular device’s counter protocol. Native s390x and hardware validation remain separate work.

Companion sources

[1] Linux v6.12, device I/O documentation, scalar accessors, and generic readl() definition. Documentation lines 169 to 176; implementation lines 217 to 229.

[2] Linux v6.12, device I/O documentation, repeated accessors and byte-stream behavior. Lines 277 to 285.

[3] Linux v6.12, generic readsl() and conditional ioread32_rep() alias. Lines 431 to 445; lines 930 to 938; configuration guard at line 791. For advancing copy addresses, see s390 zpci_memcpy_fromio() lines 144 to 161.

[4] Linux v6.12, s390 raw-access aliases and the zpci_read() wrapper. Architecture I/O header lines 49 to 95; PCI I/O header lines 44 to 72.

[5] Linux v6.12, function-handle and MIO load implementations. s390 PCI instruction source lines 156 to 255.

[6] Linux v6.12, packing API layout diagrams and implementation. Documentation lines 43 to 153; transform definitions; address calculation.

[7] Linux v6.12, split-access documentation and the cited non-atomic header definitions. Documentation lines 217 to 230; hi_lo_readq; lo_hi_readq; ioread64be_hi_lo.