diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 2f2164096..c2ec8e6d8 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -16,7 +16,7 @@ Steps to reproduce the behavior: 2. Select '....' 3. Scroll down to '....' 4. Run program '....' -4. See error +5. See error **Expected behavior** A clear and concise description of what you expected to happen. @@ -26,8 +26,8 @@ If applicable, add screenshots to help explain your problem. **Applies to (please complete the following information):** - Hardware type: [e.g. 1541U, U2+, U2+L, U64, U64E2] - - Firmware Version [e.g. 3.12a] - - Git Gash [see F4] + - Firmware Version: [e.g. 3.12a] + - Git Hash: [see F4] **Additional context** Add any other context about the problem here. diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index afdefbc3d..e34d91092 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -17,6 +17,12 @@ jobs: submodules: recursive fetch-depth: 0 + - name: Test HTTP parser preparation + run: python3 tools/tests/test_prepare_http_parser.py + + - name: Prepare reviewed HTTP response parser + run: python3 tools/prepare_http_parser.py + - name: Test JSON Replacement run: | docker run --rm \ @@ -36,7 +42,7 @@ jobs: # needs no device and no network beyond loopback, and it runs before the # firmware builds because it costs seconds and a broken report generator # is better reported now than after an hour of building. - - name: Check Observability Harness + - name: Test Observability Harness run: | docker run --rm \ -v $GITHUB_WORKSPACE:/mnt/project:rw my_docker_image /bin/bash -c "cd /mnt/project && make observability_test" @@ -49,7 +55,7 @@ jobs: # OpenAPI validation step below gives: the build image has neither pip nor # ensurepip, so it cannot install a host package. The ruff version is # pinned in tests/requirements-lint.txt. - - name: Check Tests Lint + - name: Test Lint of the Tests Tree run: | docker run --rm -v $GITHUB_WORKSPACE:/mnt/project:rw --workdir /mnt/project \ --user $(id -u):$(id -g) -e HOME=/tmp python:3.12-slim /bin/sh -c \ @@ -57,14 +63,41 @@ jobs: --target /tmp/lint-packages -r tests/requirements-lint.txt && \ PYTHONPATH=/tmp/lint-packages python3 tests/lib/lint_test.py" - - name: Check D81 track bounds + # Needs no device and no packages, so it runs here, before the firmware + # builds: u64ctrl's network recovery must trust the committed Mozilla root + # list in software/u64ctrl/ca, not ESP-IDF's own, and a refreshed list must + # change the ESP32 cache key. A stock Python image, as for the lint step. + - name: Test u64ctrl Recovery CA List + run: | + docker run --rm -v $GITHUB_WORKSPACE:/mnt/project:rw --workdir /mnt/project \ + --user $(id -u):$(id -g) -e HOME=/tmp python:3.12-slim \ + python3 tests/lib/u64ctrl_ca_test.py + + - name: Test D81 track bounds run: | docker run --rm \ -v $GITHUB_WORKSPACE:/mnt/project:rw my_docker_image /bin/bash -c "cd /mnt/project && make d81_tracks_test" + - name: Test image mount ownership and lifetimes + run: | + docker run --rm \ + -v $GITHUB_WORKSPACE:/mnt/project:rw my_docker_image /bin/bash -c \ + "cd /mnt/project && make -C target/pc/linux/iecdrive clean && \ + mkdir -p target/pc/linux/iecdrive/{output,result} && \ + make -C target/pc/linux/iecdrive CC='gcc -fsanitize=address' CPP='g++ -fsanitize=address' && \ + cd target/pc/linux/iecdrive && \ + (env -u LD_PRELOAD ASAN_OPTIONS=detect_leaks=0 ./result/testdrive > image-mount-tests.log 2>&1 || \ + { tail -100 image-mount-tests.log; exit 1; })" + + - name: Test file manager mount lifetimes under AddressSanitizer + run: | + docker run --rm \ + -v $GITHUB_WORKSPACE:/mnt/project:rw my_docker_image /bin/bash -c \ + "cd /mnt/project && make -C software/filemanager/tests asan" + # Also the gate that catches an endpoint whose documentation was not # updated with it. Runs before the firmware builds because it costs seconds. - - name: Check OpenAPI Specification + - name: Test OpenAPI Generator and Documents Are Up To Date run: | docker run --rm \ -v $GITHUB_WORKSPACE:/mnt/project:rw my_docker_image /bin/bash -c "cd /mnt/project && make openapi_test && make openapi_check" @@ -84,7 +117,7 @@ jobs: # The documents to check come from `generate.py paths`, the same list # `make openapi_validate` uses, so this cannot drift to a different set of # files. tools/openapi/test_ci.py holds the two invocations to each other. - - name: Validate OpenAPI Specification + - name: Test OpenAPI Documents Against The Schema run: | docker run --rm -v $GITHUB_WORKSPACE:/mnt/project:rw --workdir /mnt/project \ --user $(id -u):$(id -g) -e HOME=/tmp python:3.12-slim /bin/sh -c \ @@ -111,17 +144,53 @@ jobs: -v /opt/build-tools:/mnt/build-tools:ro \ -v $GITHUB_WORKSPACE:/mnt/project:rw my_docker_image /bin/bash -c "cd /mnt/project && make -B -C target/pc/linux/test_http_target test-integer-widths" + - name: Test G64 track bounds + run: | + docker run --rm \ + -v /opt/build-tools:/mnt/build-tools:ro \ + -v $GITHUB_WORKSPACE:/mnt/project:rw my_docker_image /bin/bash -c "cd /mnt/project && make -C software/drive/tests" + - name: Test UCI Palette Commands run: | docker run --rm \ -v /opt/build-tools:/mnt/build-tools:ro \ -v $GITHUB_WORKSPACE:/mnt/project:rw my_docker_image /bin/bash -c "cd /mnt/project && make -C software/io/command_interface/tests" - - name: Test HTTP Body Removal + - name: Test HTTP Responses and Resource Cleanup run: | docker run --rm \ -v /opt/build-tools:/mnt/build-tools:ro \ - -v $GITHUB_WORKSPACE:/mnt/project:rw my_docker_image /bin/bash -c "cd /mnt/project && make -B -C target/pc/linux/test_http_target test-body-removal" + -v $GITHUB_WORKSPACE:/mnt/project:rw my_docker_image /bin/bash -c "cd /mnt/project && make -B -C target/pc/linux/test_http_target test-body-removal test-connect-cleanup test-response-completion test-response-boundaries test-response-cleanup test-slow-server test-uci-worker && make -B -C target/pc/linux/test_assembly test" + + - name: Test Ethernet Transmit Framing + run: | + docker run --rm \ + -v /opt/build-tools:/mnt/build-tools:ro \ + -v $GITHUB_WORKSPACE:/mnt/project:rw my_docker_image /bin/bash -c "cd /mnt/project && make -C software/io/network/tests" + + - name: Test Printer Spool + run: | + docker run --rm \ + -v /opt/build-tools:/mnt/build-tools:ro \ + -v $GITHUB_WORKSPACE:/mnt/project:rw my_docker_image /bin/bash -c "cd /mnt/project && make -C software/io/printer/tests" + + - name: Test Time Zones + run: | + docker run --rm \ + -v /opt/build-tools:/mnt/build-tools:ro \ + -v $GITHUB_WORKSPACE:/mnt/project:rw my_docker_image /bin/bash -c "cd /mnt/project && make -C software/io/rtc/tests" + + - name: Test CBM Name Text + run: | + docker run --rm \ + -v /opt/build-tools:/mnt/build-tools:ro \ + -v $GITHUB_WORKSPACE:/mnt/project:rw my_docker_image /bin/bash -c "cd /mnt/project && make -C software/components/tests" + + - name: Test Temp Cleanup, USB Input, Config Files, Power State, and Wake-on-LAN + run: | + docker run --rm \ + -v /opt/build-tools:/mnt/build-tools:ro \ + -v $GITHUB_WORKSPACE:/mnt/project:rw my_docker_image /bin/bash -c "cd /mnt/project && make host_tests" - name: Cache U2 FPGA id: cache-u2 @@ -236,7 +305,16 @@ jobs: -v /opt/build-tools:/mnt/build-tools:ro \ -v $GITHUB_WORKSPACE:/mnt/project:rw my_docker_image /bin/bash -c "cd /mnt/project && make u64ii_no_esp && mv update.ue2 update_${{ env.GIT_VERSION }}.ue2 && mv update.cfw update_${{ env.GIT_VERSION }}.cfw" - - name: Check Firmware Application Space + # The same test again, now that the build output is there: the bundle the + # build embedded must hold exactly the roots of cacert.pem (it says so when + # a cache hit left no build output to look at). + - name: Test u64ctrl Recovery CA List In The Build + run: | + docker run --rm -v $GITHUB_WORKSPACE:/mnt/project:rw --workdir /mnt/project \ + --user $(id -u):$(id -g) -e HOME=/tmp python:3.12-slim \ + python3 tests/lib/u64ctrl_ca_test.py + + - name: Test Firmware Application Space if: always() run: | docker run --rm -e GITHUB_ACTIONS -e GITHUB_STEP_SUMMARY \ diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index 1dac23e94..abdc14c43 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -102,6 +102,10 @@ jobs: RECORD: >- ${{ (github.event_name == 'schedule' || inputs.record) && '--record' || '' }} + # The bench network is the one place probing a /24 is safe, and a + # cartridge nobody names there must still have its drives turned + # off and its settings captured. + U64_CABLING_SWEEP: '1' run: | set +e ./run-tests -o "$RUNNER_TEMP/e2e" \ diff --git a/.github/workflows/https-host.yml b/.github/workflows/https-host.yml new file mode 100644 index 000000000..961f37558 --- /dev/null +++ b/.github/workflows/https-host.yml @@ -0,0 +1,50 @@ +name: HTTPS host validation + +on: [push, pull_request] + +permissions: + contents: read + +jobs: + https-host: + if: github.event_name == 'push' || github.event.pull_request.head.repo.full_name != github.repository + runs-on: ubuntu-22.04 + timeout-minutes: 25 + steps: + - name: Checkout firmware and public submodules + uses: actions/checkout@v7 + with: + submodules: recursive + persist-credentials: false + - name: Checkout the tested TLS core + uses: actions/checkout@v7 + with: + repository: araxis/ultimate-tls-validation + ref: 529b0450955611bd82db921db3bae10222203eba + path: .ci-deps/tls + persist-credentials: false + - name: Checkout the pinned TLS library + uses: actions/checkout@v7 + with: + repository: espressif/mbedtls + ref: 2b96dd8eebe880f304c69976b3c2fa0c5100cbb6 + path: .ci-deps/tls/.deps/mbedtls + submodules: recursive + persist-credentials: false + - name: Install host build tools + run: sudo apt-get update && sudo apt-get install -y cmake g++ make git openssl python3-cryptography ninja-build libgtest-dev + - name: Run the device-free regression + run: | + python3 tools/tests/test_prepare_http_parser.py + python3 tools/test_https_host.py --tls-root "$GITHUB_WORKSPACE/.ci-deps/tls" --output "$RUNNER_TEMP/https-host" + - name: Retain logs and peer records + if: always() + uses: actions/upload-artifact@v7 + with: + name: https-host-evidence + if-no-files-found: warn + path: | + ${{ runner.temp }}/https-host/*.log + ${{ runner.temp }}/https-host/result.json + ${{ runner.temp }}/https-host/*/*.json + ${{ runner.temp }}/https-host/*/*.log diff --git a/.gitignore b/.gitignore index 3c6e13e57..340edc30c 100644 --- a/.gitignore +++ b/.gitignore @@ -289,6 +289,8 @@ tools/swap tools/c64/*.prg software/6502/sidcrt/target software/io/command_interface/tests/paletteCommandTest +software/io/command_interface/tests/uciDeferralTest +software/io/rtc/tests/timezonesTest software/io/c64/tests/build *.d tools/dump_bus_trace diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 000000000..06342aee0 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,217 @@ +# Contributing to the 1541 Ultimate firmware + +Thanks for wanting to help! This repository holds the firmware for the +Ultimate-II, Ultimate-II+ and Ultimate-II+L cartridges, the Ultimate 64, the +Ultimate 64 Elite II and the C64 Ultimate. Experiments and new ideas are +always welcome. + +This page explains how to get your work merged smoothly. The short version: + +1. **Small fixes:** open a pull request against `master`. +2. **Anything bigger:** open an issue first and agree the plan. +3. **Show that it works:** say what you tested, and on which hardware. + +## Small fixes: just open a pull request + +Bug fixes, small improvements, new tests and documentation fixes don't need +any discussion first. If there's an issue for it, link it. + +Not sure whether your change counts as small? Open an issue and ask. It's +quick. + +## Bigger changes: open an issue first + +Open an issue, or comment on an existing one, **before** you write most of the +code if your change does any of these: + +- adds a feature, a setting, a menu entry, a REST endpoint, a UCI command or + anything else other people will build on +- changes how an existing feature behaves, beyond fixing a bug +- changes the overall architecture, restructures existing code, or changes a + class that many parts of the firmware share +- touches FPGA code under `fpga/`, since the maintainer builds and checks the + FPGA images +- is likely to grow beyond about 300 lines, not counting tests + +In the issue, describe the problem you want to solve, which products it +affects, and roughly how you plan to solve it. A few paragraphs is plenty. +Once the maintainer, or the area contact listed below, has replied that they're +happy with the approach, go ahead. This applies to issues you open yourself +too: opening the issue starts the conversation, the reply is the go-ahead. + +You're free to keep exploring in your fork while the discussion goes on. If a +prototype helps explain the idea, open it as a draft pull request and link it +from the issue. Prototypes often change quite a bit on the way to being +merged. + +## Keeping work easy to merge + +- **One problem per issue, one issue per pull request.** If you find + something else along the way, open a new issue for it and link the two, + rather than adding it to the one you're working on. +- **Keep the scope you agreed.** Once a pull request is under review, only + change it to answer the review. New ideas go into a new issue. +- **Each pull request stands on its own.** It should apply to current + `master`, build, and be useful without any other open pull request. If the + work needs several steps, open the next one after the previous one is + merged, rather than a chain that has to be merged in a set order. +- **Open it when it can be merged.** If your change needs something that + isn't on `master` yet, such as an FPGA change or a decision in another + issue, say so in the issue and keep your work in your fork, or in a draft + pull request, until that has landed. +- **Have only a few open at once.** Finishing one pull request before starting + the next gets all of them merged sooner. + +## Who to ask about which area + +Changes to the overall architecture, and all FPGA (VHDL) code, go through the +maintainer, @GideonZ. + +The people below have done significant work in particular areas. If your +change touches one of their areas, mention them in your issue or pull request, +and agree the plan with them before you start on anything bigger than a small +fix. Areas are in alphabetical order. + +| Area | Main paths | Contact | +| --- | --- | --- | +| Command interface (UCI), GitHub Actions workflows | `software/io/command_interface`, `.github/workflows` | @barryw | +| G64 and G71 track parsing, 1581 disk controller (WD177x) | `software/drive/disk_image.cc`, `software/drive/mfmdisk.cc`, `software/drive/wd177x.cc` | @enver-haase | +| Hyperspeed Kernal | `roms/c64rom/kernal` | @bvl1999 | +| Machine code monitor, REST API, test suites, USB keyboard and mouse | `software/monitor`, `software/api`, `tests/`, `software/io/usb` | @chrisgleissner | +| Modem emulation | `software/io/acia` | @xlar54 | +| Printer emulation | `software/io/printer` | @rgc2000 | +| SID player | `software/6502/sidcrt` | @WilfredC64 | +| Software IEC drive and DOS commands | `software/io/iec` | @markusC64, @chrisgleissner | +| Web UI | `html/` | @TangoBravo64, @radius75 | + +For every other area, the maintainer is your contact. Just open the issue. + +Want to be listed, or taken off the list? Open a pull request. + +## Fitting in with the code + +- **Match the code around you.** Follow the style of the file you're editing: + usually 4-space indentation, function braces on their own line and other + braces at the end of the line. Don't reformat, rename or move code your + change doesn't need. +- **Use Linux (LF) line endings.** Some older files still have Windows (CRLF) + line endings. They will be converted all at once later, so when you edit + one, keep its existing endings. If `git diff --stat` shows a whole file + changed, something converted it. +- **Keep shared code generic.** Classes used across the firmware, such as the + file systems, the file manager, the browser and the menus, should not know + about one particular feature. If a feature needs special behaviour, give it + its own type, for example a subclass. If shared code has a bug, fix it there + rather than working around it. +- **Think about every product.** Shared code is built for all of them. The + `U64` macro is 1 on the Ultimate 64, 2 on the Ultimate 64 Elite II and the + C64 Ultimate, and undefined on the cartridges, so `#if U64 == 1` leaves out + two products. Where a feature makes sense on every product, try to make it + work on every product. +- **Mind the size.** The Ultimate-II has little room left, and CI checks every + image. String formatting comes from `software/system/small_printf.cc`, which + has no `l`, `ll` or `z` length modifiers. New C library calls can pull in + large parts of the library and break the RISC-V builds. +- **Comments say why.** Describe the code as it is, not how it got there. Git + keeps the history. + +## Testing + +Building instructions are in [README.txt](README.txt). CI builds the firmware +for every product on each pull request, and the build must pass. On your first +pull request, a maintainer may need to approve the CI run before it starts. +You can download the update files from the run's artifacts and try them on +your own device. + +Beyond that: + +- **Work red/green.** Write the test first and run it against firmware + without your change, where it should fail. Then run it with your change, + where it should pass. For a new feature, the test shows the feature + working. Red/green is a check you run, not something the code base keeps: + don't add switches, patches or "old behaviour" models to the tree so the + red run can be repeated. Run the new tests once against the unpatched + firmware, show that they fail, and say so in the pull request. +- **Reuse what's there.** Hardware tests live under `tests/` and run through + `./run-tests`. Build on the shared helpers in `tests/lib` rather than + writing your own, and make sure your suite runs well alongside the others + and leaves the device as it found it. Logic that runs on a PC without much + mocking can also get a host unit test next to its code, such as + `software/api/tests/`. See [tests/README.md](tests/README.md). +- **Run the standard profile.** `./run-tests --profile standard -o runs/ u64` + runs the same set of suites a merge is checked against. Run it red and + green, and `python3 tools/e2e_report.py runs/` writes a report you can + attach. +- **Test on both device types.** We expect a test on at least an Ultimate 64 + or C64 Ultimate and on an Ultimate-II cartridge, since they differ in many + ways. If you could not test one of them, say so. +- **Check the device runs your build.** `GET /v1/info` shows the commit in + `git_commit_hash`. If a check fails unexpectedly, make sure the check itself + is right before you change the firmware. + +## Writing the pull request + +- **Use GitHub's draft status** while the work isn't ready for review. +- **Commit only source.** Builds leave firmware images and object files in the + working tree, so add files by name rather than with `git add -A`. +- **Preserve pull request history.** Avoid force-pushing or rewriting commits + once a pull request is under review, as this makes changes harder to follow. + Push new commits instead, and merge `master` into your branch when needed. + We squash commits when merging pull requests into `master`, so there is no + need to tidy the history yourself. +- **Keep the description short.** It needs four things: + - the problem, with a link to the issue (`Fixes #123`) + - what you changed, and why you chose this approach + - how you tested it: the devices with their firmware and FPGA versions, + the host you ran from, the `./run-tests` results red and green, and any + manual steps + - anything you know is missing or untested + +## Using AI tools + +AI tools are welcome. You are still the author, so make sure you understand +the change and can explain it in review. A few habits help: + +- Use the most capable model you have access to. At the time of writing + (October 2026) that is Claude Opus 5.5 with high reasoning effort. +- Before opening the pull request, ask a second AI session or a person to + review the change critically, and fix what they find. +- Check what the tool tells you against the code. +- Mention the model you used in the description. + +## Working together + +Everyone here works on this firmware for the love of it, mostly in their spare +time. A few things keep discussions friendly and useful: + +- **Be kind and assume good intent.** A short reply usually means a busy + person, not an unhappy one. +- **Discuss the idea, not the person.** When you disagree, say why with + something concrete, such as a test result, a measurement or a line of code, + and suggest an alternative. +- **Keep it in the issue or pull request,** so others can follow and join in. +- **When you review, help the change land.** Mention what works as well as + what doesn't, and offer a fix or a test where you can. +- **Build on decisions once they're made.** If you see new evidence, raise it + in the issue. The maintainer makes the final call on direction. + +## After you open the pull request + +Pull requests are reviewed by hand. The maintainer squash-merges your commits +into `master` and may adjust the change while merging it. If an issue or pull +request has gone quiet for a couple of weeks, a friendly reminder is welcome. + +## Reporting bugs and asking for features + +When you report a bug, include the product, the firmware version, the steps to +reproduce it, and what you expected to happen. Feature ideas are welcome as +issues too. Describe the need, not only the solution you have in mind. + +The user manual lives in its own repository, +[GideonZ/1541u-documentation](https://github.com/GideonZ/1541u-documentation). +Corrections to the manual belong there. + +## License + +This repository is licensed under the GNU General Public License v3, see +[LICENSE.txt](LICENSE.txt). Contributions are accepted under the same terms. diff --git a/Makefile b/Makefile index 62d640bbf..8a0781f5d 100755 --- a/Makefile +++ b/Makefile @@ -71,9 +71,25 @@ openapi_validate: # the firmware targets deliberately: those build with a cross compiler, and # these need a host g++. host_tests: + @$(MAKE) -C software/filemanager/tests + @$(MAKE) -C software/io/usb/tests @$(MAKE) -C target/pc/linux/configiotest test @$(MAKE) -C target/pc/linux/powerstate test @$(MAKE) -C target/pc/linux/wolmagic test + @$(MAKE) -C target/pc/linux/wifireply test + @$(MAKE) -C software/io/wifi/tests + @$(MAKE) -C software/wifi/tests + @$(MAKE) -C software/wifi/uart_tests + @$(MAKE) -C target/pc/linux/recoverymanifest test + @$(MAKE) -C target/pc/linux/recoveryimage test + @$(MAKE) -C target/pc/linux/recoveryurl test + @$(MAKE) -C target/pc/linux/c64mem test + @$(MAKE) -C target/pc/linux/sdcard test + @$(MAKE) -C target/pc/linux/rasterwait test + @$(MAKE) -C target/pc/linux/socketdma test + @$(MAKE) -C target/pc/linux/syslog test + @$(MAKE) -C target/pc/linux/ucitargets test + @$(MAKE) -C software/userinterface/tests esp32: esp32_raw_u64 esp32_raw_c3 esp32_u64ctrl @@ -377,6 +393,10 @@ u64ii: app_space_test openapi_check esp32_u64ctrl @cp software/u64ctrl/build/u64ctrl.bin u64ii @cp target/u64ii/riscv/update/result/update.app ./update.ue2 @cp target/u64ii/riscv/update/result/update.cfw ./update.cfw + @$(MAKE) -C target/u64ii/riscv/update UPDATE_FPGA=50t + @$(MAKE) -C target/u64ii/riscv/update UPDATE_FPGA=100t + @cp target/u64ii/riscv/update/result/50t/update.cfw ./recovery_50t.cfw + @cp target/u64ii/riscv/update/result/100t/update.cfw ./recovery_100t.cfw u64ii_no_esp:: app_space_test openapi_check @mkdir -p u64ii @@ -394,6 +414,10 @@ u64ii_no_esp:: app_space_test openapi_check @cp software/u64ctrl/build/u64ctrl.bin u64ii @cp target/u64ii/riscv/update/result/update.app ./update.ue2 @cp target/u64ii/riscv/update/result/update.cfw ./update.cfw + @$(MAKE) -C target/u64ii/riscv/update UPDATE_FPGA=50t + @$(MAKE) -C target/u64ii/riscv/update UPDATE_FPGA=100t + @cp target/u64ii/riscv/update/result/50t/update.cfw ./recovery_50t.cfw + @cp target/u64ii/riscv/update/result/100t/update.cfw ./recovery_100t.cfw u2pl: app_space_test openapi_check esp32_raw_c3 @$(MAKE) -C tools diff --git a/doc/api/rest_api_openapi_u2.yaml b/doc/api/rest_api_openapi_u2.yaml index 691a8d31d..1c0dc5e43 100644 --- a/doc/api/rest_api_openapi_u2.yaml +++ b/doc/api/rest_api_openapi_u2.yaml @@ -95,7 +95,7 @@ paths: - Configuration summary: List the configuration categories description: |2- - Reads the same settings the menu shows, at one of three levels of detail. With no path it lists the category names. With a category it gives the current value of every item in it. With a category and an item it describes each matching item in full: the current value, the default, and either the accepted values of an enumeration or the range and format of a number. + Reads the same settings the menu shows, at one of three levels of detail. With no path it lists the category names. With a category it gives the current value of every item in it. With a category and an item it describes each matching item in full: the current value, the default, and either the accepted values of an enumeration, in the order the menu lists them, or the range and format of a number. Both path elements are patterns, so `drive*` selects every category whose name starts with `drive` and `*bus*` selects every item with `bus` in its name. Category and item names contain spaces and must be URL encoded. @@ -184,7 +184,7 @@ paths: - Configuration summary: Read the values in a category description: |2- - Reads the same settings the menu shows, at one of three levels of detail. With no path it lists the category names. With a category it gives the current value of every item in it. With a category and an item it describes each matching item in full: the current value, the default, and either the accepted values of an enumeration or the range and format of a number. + Reads the same settings the menu shows, at one of three levels of detail. With no path it lists the category names. With a category it gives the current value of every item in it. With a category and an item it describes each matching item in full: the current value, the default, and either the accepted values of an enumeration, in the order the menu lists them, or the range and format of a number. Both path elements are patterns, so `drive*` selects every category whose name starts with `drive` and `*bus*` selects every item with `bus` in its name. Category and item names contain spaces and must be URL encoded. @@ -232,7 +232,7 @@ paths: - Configuration summary: Read a setting in full description: |2- - Reads the same settings the menu shows, at one of three levels of detail. With no path it lists the category names. With a category it gives the current value of every item in it. With a category and an item it describes each matching item in full: the current value, the default, and either the accepted values of an enumeration or the range and format of a number. + Reads the same settings the menu shows, at one of three levels of detail. With no path it lists the category names. With a category it gives the current value of every item in it. With a category and an item it describes each matching item in full: the current value, the default, and either the accepted values of an enumeration, in the order the menu lists them, or the range and format of a number. Both path elements are patterns, so `drive*` selects every category whose name starts with `drive` and `*bus*` selects every item with `bus` in its name. Category and item names contain spaces and must be URL encoded. @@ -1816,7 +1816,7 @@ paths: `ethernet_mac` and `wifi_mac` are the addresses of the wired and the wireless interface. Each is left out when the device has no such interface, or when that interface has not started and its address is therefore not known yet, and only the first interface of each kind is reported. A caller that wants to wake the device sends its magic packet to `wifi_mac`, which carries a MAC and not an IP address; the wired interface does not wake the device. - The same information is also available without HTTP, from the Ultimate Ident Service on UDP port 64, which answers a broadcast and so can be used to find a device whose address is not known. + Most of this information is also available without HTTP, from the Ultimate Ident Service on UDP port 64, which answers a broadcast and so can be used to find a device whose address is not known. operationId: getInfo responses: '200': @@ -2066,7 +2066,7 @@ paths: - Machine summary: Pause the CPU description: |2- - Halts the 6510 by holding DMA. The video output freezes on the frame that was being drawn and the machine stays halted until `machine:resume`. Memory can still be read and written while paused, which is what makes this useful before a large `machine:readmem`. + Halts the 6510 by holding DMA. The video output freezes on the frame that was being drawn and the machine stays halted until `machine:resume`. Memory can still be read and written while paused, which is what makes this useful before a large `machine:readmem`. While the on-device menu holds the machine, it is halted already and this does nothing; the machine runs again when the menu closes, so pause after that to keep it halted. **Caution (machine-state):** The machine stays halted until machine:resume. A client that stops without resuming leaves it frozen. operationId: pauseMachine @@ -2293,7 +2293,7 @@ paths: tags: - Machine summary: Resume the CPU - description: 'Releases the DMA hold that `machine:pause` applied. Calling it on a machine that is not paused does nothing and is not an error.' + description: 'Releases the DMA hold that `machine:pause` applied. Calling it on a machine that is not paused does nothing and is not an error. While the on-device menu holds the machine it stays halted, and runs again when the menu closes.' operationId: resumeMachine responses: '200': diff --git a/doc/api/rest_api_openapi_u64.yaml b/doc/api/rest_api_openapi_u64.yaml index d1484f8da..49fa93921 100644 --- a/doc/api/rest_api_openapi_u64.yaml +++ b/doc/api/rest_api_openapi_u64.yaml @@ -98,7 +98,7 @@ paths: - Configuration summary: List the configuration categories description: |2- - Reads the same settings the menu shows, at one of three levels of detail. With no path it lists the category names. With a category it gives the current value of every item in it. With a category and an item it describes each matching item in full: the current value, the default, and either the accepted values of an enumeration or the range and format of a number. + Reads the same settings the menu shows, at one of three levels of detail. With no path it lists the category names. With a category it gives the current value of every item in it. With a category and an item it describes each matching item in full: the current value, the default, and either the accepted values of an enumeration, in the order the menu lists them, or the range and format of a number. Both path elements are patterns, so `drive*` selects every category whose name starts with `drive` and `*bus*` selects every item with `bus` in its name. Category and item names contain spaces and must be URL encoded. @@ -187,7 +187,7 @@ paths: - Configuration summary: Read the values in a category description: |2- - Reads the same settings the menu shows, at one of three levels of detail. With no path it lists the category names. With a category it gives the current value of every item in it. With a category and an item it describes each matching item in full: the current value, the default, and either the accepted values of an enumeration or the range and format of a number. + Reads the same settings the menu shows, at one of three levels of detail. With no path it lists the category names. With a category it gives the current value of every item in it. With a category and an item it describes each matching item in full: the current value, the default, and either the accepted values of an enumeration, in the order the menu lists them, or the range and format of a number. Both path elements are patterns, so `drive*` selects every category whose name starts with `drive` and `*bus*` selects every item with `bus` in its name. Category and item names contain spaces and must be URL encoded. @@ -235,7 +235,7 @@ paths: - Configuration summary: Read a setting in full description: |2- - Reads the same settings the menu shows, at one of three levels of detail. With no path it lists the category names. With a category it gives the current value of every item in it. With a category and an item it describes each matching item in full: the current value, the default, and either the accepted values of an enumeration or the range and format of a number. + Reads the same settings the menu shows, at one of three levels of detail. With no path it lists the category names. With a category it gives the current value of every item in it. With a category and an item it describes each matching item in full: the current value, the default, and either the accepted values of an enumeration, in the order the menu lists them, or the range and format of a number. Both path elements are patterns, so `drive*` selects every category whose name starts with `drive` and `*bus*` selects every item with `bus` in its name. Category and item names contain spaces and must be URL encoded. @@ -1819,7 +1819,7 @@ paths: `ethernet_mac` and `wifi_mac` are the addresses of the wired and the wireless interface. Each is left out when the device has no such interface, or when that interface has not started and its address is therefore not known yet, and only the first interface of each kind is reported. A caller that wants to wake the device sends its magic packet to `wifi_mac`, which carries a MAC and not an IP address; the wired interface does not wake the device. - The same information is also available without HTTP, from the Ultimate Ident Service on UDP port 64, which answers a broadcast and so can be used to find a device whose address is not known. + Most of this information is also available without HTTP, from the Ultimate Ident Service on UDP port 64, which answers a broadcast and so can be used to find a device whose address is not known. operationId: getInfo responses: '200': @@ -2237,7 +2237,7 @@ paths: - Machine summary: Pause the CPU description: |2- - Halts the 6510 by holding DMA. The video output freezes on the frame that was being drawn and the machine stays halted until `machine:resume`. Memory can still be read and written while paused, which is what makes this useful before a large `machine:readmem`. + Halts the 6510 by holding DMA. The video output freezes on the frame that was being drawn and the machine stays halted until `machine:resume`. Memory can still be read and written while paused, which is what makes this useful before a large `machine:readmem`. While the on-device menu holds the machine, it is halted already and this does nothing; the machine runs again when the menu closes, so pause after that to keep it halted. **Caution (machine-state):** The machine stays halted until machine:resume. A client that stops without resuming leaves it frozen. operationId: pauseMachine @@ -2488,7 +2488,7 @@ paths: tags: - Machine summary: Resume the CPU - description: 'Releases the DMA hold that `machine:pause` applied. Calling it on a machine that is not paused does nothing and is not an error.' + description: 'Releases the DMA hold that `machine:pause` applied. Calling it on a machine that is not paused does nothing and is not an error. While the on-device menu holds the machine it stays halted, and runs again when the menu closes.' operationId: resumeMachine responses: '200': @@ -3352,9 +3352,13 @@ paths: description: |2- Sends the named stream to a listening host over UDP. `video` carries the VIC output, `audio` the sound, and `debug` a trace of the cartridge bus. - `ip` may be an address or a host name, and may carry a port as `address:port`. Without a port the stream goes to 11000 for video, 11001 for audio and 11002 for debug. A multicast group is accepted in place of a single host, in which case every listener that joined the group receives the stream. + `ip` may be an address or a host name, and may carry a port as `address:port`. Without a port the stream goes to 11000 for video, 11001 for audio and 11002 for debug. A multicast group from 232.0.0.0 to 239.255.255.255 is accepted in place of a single host, in which case every listener that joined the group receives the stream. + + To send to a single host the device looks up that host's hardware address on the wired port, or the gateway's when the host is on another subnet. When name resolution or the hardware-address lookup fails, the call fails with 404. Video and debug share hardware and cannot both run, so starting video stops debug first. + + The streams leave through the wired Ethernet port only, whichever interface carried this request. Without an Ethernet link that has an IP address the call fails, even when WiFi is connected. operationId: startStream parameters: - name: stream @@ -3375,6 +3379,13 @@ paths: schema: type: string example: '192.168.1.10:11000' + - name: palette + in: query + required: false + description: 'For video, request runtime VIC palette packets (0 or 1). The setting is device-wide: it applies to every receiver of the stream, and the most recent start sets it.' + schema: + type: integer + example: 0 responses: '200': description: The stream is running. @@ -3382,6 +3393,17 @@ paths: application/json: schema: $ref: '#/components/schemas/ErrorResponse' + '400': + description: Bad request + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + examples: + Palette must be 0 or 1 and is only valid for the video stream: + value: + errors: + - Palette must be 0 or 1 and is only valid for the video stream '403': $ref: '#/components/responses/Forbidden' '404': @@ -3395,6 +3417,10 @@ paths: value: errors: - 'Unrecognized stream name ''screen''' + Network Host Resolve Error: + value: + errors: + - Network Host Resolve Error '500': description: Internal server error content: @@ -3402,10 +3428,10 @@ paths: schema: $ref: '#/components/schemas/ErrorResponse' examples: - No Operational Network Interface: + Wired Ethernet link is down or has no IP address: value: errors: - - No Operational Network Interface + - Wired Ethernet link is down or has no IP address '/v1/streams/{stream}:stop': put: tags: diff --git a/doc/g64_mfm_tracks.md b/doc/g64_mfm_tracks.md new file mode 100644 index 000000000..c831c4511 --- /dev/null +++ b/doc/g64_mfm_tracks.md @@ -0,0 +1,130 @@ +# MFM tracks in G64 and G71 images + +This describes how the Ultimate firmware stores MFM tracks inside a G64 or G71 image, as it does today, so that other programs can read and write such images. It is not an official extension of the G64 format: VICE and most other G64 readers do not know it and reject or misread these tracks. + +Two implementations use it: + +- the Ultimate firmware (1541 Ultimate II+, II+L, Ultimate 64), since the 1571's WD177x was added in June 2021: `software/drive/disk_image.cc`, `c1541.cc`, `mfmdisk.cc`, `wd177x.cc`; +- Denise, as "G64 (U-II+/U64 compatibility mode)": `emulation/libc64/disk/structure/gxx.cpp` (`parseMfm`, `writeMfm`). + +An MFM track holds decoded sectors, not an MFM bitstream: sector IDs and sector data, without gaps, sync marks or CRCs. A reader that needs the bitstream has to generate it, as Denise does. + +The firmware behaviour below was checked on an Ultimate II+L running 3.15a, with the 1571's own burst commands (format, inquire, read) on crafted images. + +## Container + +The image is a normal G64: + +| Offset | Size | Content | +|---|---|---| +| 0 | 8 | `GCR-1541` (one side, 84 table entries) or `GCR-1571` (two sides, 168 entries) | +| 8 | 1 | version, 0 | +| 9 | 1 | number of table entries: 84 for `GCR-1541`, 168 for `GCR-1571` | +| 10 | 2 | maximum track length, little-endian | +| 12 | 4 × entries | track offsets, little-endian, 0 = track absent | +| 12 + 4 × entries | 4 × entries | speed zones | + +Both programs write version 0, 84 or 168 entries, and 7928 (`$1EF8`) as the maximum track length. Denise rejects a version other than 0 or an entry count above 84 or 168, skips tracks longer than the header's maximum, and refuses to write one. The firmware takes the entry count from the signature and accepts no track longer than 7928 bytes, whatever the header says. It reads at most 635,932 bytes of the file; tracks behind that are treated as absent. + +**Table entries.** Each entry is a head position in half-track steps, the position the drive's stepper has reached: entry `p` (0-83) is side 0, entry `84 + p` is side 1. Both programs index the table this way. It is not the track number in the sector IDs, which can be anything. The 1571 DOS formats MFM cylinder `c` at the position of GCR track `c + 1`, so a disk formatted by it has cylinder `c` in entry `2c` on side 0 and `84 + 2c` on side 1; other software can format at other positions. A G64 holds side 0 only; MFM tracks on side 1 need a G71. + +**Track placement.** Both programs find a track through its offset only, and both drop a track unless the file contains all of its bytes. They differ in how they lay tracks out: + +- The firmware writes a track back in place. When it saves a whole image, it packs the tracks back to back, each directly behind the previous one's last byte. +- Denise gives every track a slot of 2 + maximum track length bytes. Writing a track, it fills the rest of that slot with zeros, and it appends a new track at the end of the file. + +So Denise writing into a packed image overwrites the start of the track behind a short one. Writers that want both programs to handle their images lay tracks out `2 + maximum track length` bytes apart. + +GCR and MFM tracks can be mixed in one image. A track becomes MFM when the drive formats it with the WD177x, and GCR again when the drive writes it in GCR. + +## Track + +At the track offset, as for any G64 track, comes a 16-bit little-endian length word, then the track bytes. + +**Length word.** Bit 15 set marks the track as MFM. Bits 0-14 are the track length, read as one 15-bit number by both programs (firmware releases up to 3.15a masked it with `$3FFF`; GideonZ/1541ultimate#840 changed that to `$7FFF`). + +- Both programs write back the length they loaded, with bit 15 set: a track loaded with length 7000 and formatted as MFM is written as `$9B58`. +- For a track the image did not contain, the firmware uses the GCR length of that track's speed zone, 6250 to 7692 bytes (cylinder 1, for example, comes out as `$9E0C`). +- Denise uses the length as the size of one revolution: it generates the MFM bitstream into that many bytes. 6250 bytes is one revolution at 250 kbit/s and 300 rpm; a shorter length leaves less room for sectors (see below), a longer one gives a slower disk. +- The firmware needs the sector data to fit into the length minus 162 bytes. + +**Speed zone.** Not used for an MFM track. Writers leave whatever the entry had; readers ignore it. + +**Track bytes:** + +| Offset | Size | Content | +|---|---|---| +| 0 | 1 | number of sectors `n` (readers use at most 32) | +| 1 | 1 | version, 0 | +| 2 | 32 × 5 | sector list: the first `n` entries are used | +| 162 | | sector data | + +Each entry of the sector list is the sector's ID field, as the WD177x reads it, plus one byte: + +| Byte | Content | +|---|---| +| 0 | track (C) | +| 1 | side (H) | +| 2 | sector (R) | +| 3 | size code (N): 0 = 128, 1 = 256, 2 = 512, 3 = 1024 bytes | +| 4 | error byte, see below | + +Both programs write version 0 and ignore it when reading. Entries behind the first `n` are ignored by both; the firmware writes them as zeros, Denise leaves them as they were. + +The list is in physical order: the order in which the sectors pass the head, starting at the index hole. The 1571 DOS lays sectors out with a step of interleave + 1, so its burst format with interleave 1 and nine sectors gives `1,6,2,7,3,8,4,9,5`, and interleave 0 gives `1` to `9`. + +The sector data starts at offset 162, always, whatever `n` is. The sectors follow one another in list order, each `128 << N` bytes long, without gaps, except for a sector without a data field (error byte bit 2, below). The bytes behind the last sector, up to the end of the track, have no meaning; the firmware leaves them as they were. + +## Error byte + +| Bit | Meaning in Denise | +|---|---| +| 0 | the ID field has a CRC error | +| 1 | the data field has a CRC error | +| 2 | the sector has no data field; no data bytes are stored for it | +| 4 | the data field has a deleted data mark (`$F8`, or `$F9` when Denise reads it from a bitstream) | + +The firmware writes 0 and does not look at the byte when it reads. + +This matters for bit 2. Denise stores no data for such a sector, so the data of all following sectors moves up. The firmware counts `128 << N` bytes for every entry, so it reads the sectors after one with bit 2 set from the wrong place; it also reads the sector with bit 2 itself as if it had data. A writer that wants the firmware to read its images should not produce sectors without a data field. + +## What each implementation does beyond the format + +These are properties of the two programs, not of the format, but they decide whether an image works. + +**Firmware, formatting (WD177x Write Track):** + +- It records only sectors with a normal data mark (`$FB`), and at most 5120 data bytes per track. Sectors beyond that are dropped silently: a 1571 format of 11 × 512 bytes ends with drive error 24, but the track is stored with the first 10. +- It can store an MFM track only where the image has a track, or where it keeps a blank one: even entries 0-78 (cylinders 0-39), on side 1 only if the image is already double-sided. A format anywhere else is lost. +- A track the file contained is written back in place. A track the file did not contain stays in memory until the whole image is saved (*Save as GCR*), which packs all tracks and, with *GCR Save Align Tracks* on, tries to rotate every track, MFM ones included, to start at a GCR sector 0. +- A GCR write marks the track as GCR again, as a 1571 `N:` format after an MFM format shows. + +**Firmware, reading:** + +- The sector list is read when the image is mounted. +- A sector is found by its track and sector number (C and R); the side byte H is not compared, and the first matching entry wins. +- A size code above 3 ends the list at that entry: that sector and all after it are not found. + +**Denise, reading:** + +- It generates the bitstream with standard gaps into the first 6250 bytes of the track, or fewer if the length is shorter. At the first sector that does not fit, it stops: that sector and all after it are missing. A sector with bit 2 takes the space of its data anyway. +- It uses size codes modulo 4. + +**Denise, writing:** + +- It decodes the sectors back from its bitstream, scanning the first 6250 bytes from the index, and sets the error bits from what it finds. It stores the size code as found, so a size code above 3 can end up in an image. + +## Example + +A track formatted on an Ultimate II+L by the 1571's own burst `FORMAT MFM`, for PC 360K (both sides, nine 512-byte sectors starting at 1, fill `$E5`, interleave 1), cylinder 0 side 0, in entry 0 of an image whose track lengths were 7928: + +``` +length word F8 9E bit 15 + 7928 +offset 0 09 00 9 sectors, version 0 +offset 2 00 00 01 02 00 C=0 H=0 R=1 N=2 (512), no error +offset 7 00 00 06 02 00 R=6 +... (sectors 2, 7, 3, 8, 4, 9, 5) +offset 47 00 ... entries 10-32, zero +offset 162 E5 × 4608 data of R=1, R=6, R=2, ... in list order +offset 4770 ... rest of the track, as it was before +``` diff --git a/doc/http-transport.md b/doc/http-transport.md new file mode 100644 index 000000000..204101554 --- /dev/null +++ b/doc/http-transport.md @@ -0,0 +1,81 @@ +# HTTP and HTTPS transport + +The target-6 HTTP command interface is unchanged. Select HTTPS with an `https://` +URL; header creation, request bodies, handles, response blocks and JSON rendering +use the same commands as HTTP. The default build still uses ordinary HTTP and +rejects HTTPS when no qualified provider is available. + +## Request path + +`HttpTarget` owns a connection returned by its borrowed `HttpSecureProvider`. +`HttpRequest` borrows that connection and renders/parses HTTP through +`HttpConnection`. The ordinary socket implementation remains the default for +HTTP and schemeless URLs. The parser does not depend on TLS or the UART protocol. + +For the opt-in firmware, `OwnerHttpProvider` submits copied requests to the native +owner queue. The manager exchanges identity-bound control and data messages with +the ESP32 owner task. `TlsBackend` supplies `TlsHttpConnection`, whose platform +callbacks use ESP-IDF sockets, entropy, time and certificate verification. Another +backend can implement the same authenticated stream contract without changing +the C64 command interface. + +The native `PROVIDER_JOURNAL=1` option and the ESP32 +`ULTIMATE_PROVIDER_CONTROL`, `ULTIMATE_PROVIDER_TLS` and +`ULTIMATE_PROVIDER_SOURCES` options are disabled by default. Building both sides +is insufficient: an explicitly installed restart identity, successful owner +negotiation, qualified time and entropy are required before HTTPS is admitted. +See [provisioning](../target/pc/linux/test_http_tls/PROVISIONING.md). + +## Failure and ownership rules + +- Each connection is single-use. Failure closes partially initialized resources; + repeated close is harmless. Recovery creates a fresh exchange without replay. +- Reads and writes may be short. Zero read means authenticated EOF for TLS; a bare + TCP close is not authenticated EOF. Negative results are terminal. +- The request is destroyed before its owned connection. A borrowed connection, + factory, platform context and trust material must outlive their users. +- One absolute budget covers open and subsequent I/O. Progress and lease renewal + do not extend it. Cancellation, clock/entropy revocation and identity changes + fence results before publication. +- A failed write may already have sent bytes. It is never automatically retried. +- Authentication requires certificate chain, hostname and date verification. + Missing providers or failed secure operations never fall back to plaintext. +- Secure failures use the existing `503 SERVICE UNAVAILABLE` status and empty + response. Invalid URL syntax uses the existing `500 BAD FORMAT` status. + +Scheme matching is case-insensitive. HTTPS defaults to port 443 and accepts +explicit decimal ports 1–65535. Unsupported schemes, malformed secure prefixes, +empty hosts, userinfo and unsupported authority syntax are rejected before opening. + +## Response framing + +The parser rejects conflicting lengths, unsupported transfer codings, malformed +chunks, premature EOF and oversized responses. It supports one chunked coding, +bounded trailers and interim responses. The limits are a 2048-byte header, +1024-byte chunk-line input buffer, 2048 bytes of trailers, eight interim responses +and a 16384-byte body plus a separate terminator byte. Identical individual +Content-Length fields are accepted; length lists and protocol upgrades are not. +Failures release partial bodies rather than expose them as successful responses. + +The public HTTP submodule revision is accompanied by +`patches/http-response-framing.patch`. Run `python3 tools/prepare_http_parser.py` +after initializing submodules and before building. It checks every affected file +against the public base or exact patched contents, refuses unrelated local edits, +and verifies the result. CI performs the same preparation. The submodule then +appears modified by this reviewed patch; do not commit those changes in the parent +as a different, unpublished submodule reference. + +## Validation and remaining qualification + +The [host runner](../target/pc/linux/test_http_tls/README.md) covers the unchanged +HTTP commands, framing, authenticated RSA/ECDSA peers, ownership, cancellation, +deadlines, restart fencing and cleanup. The [embedded fixture](../target/esp32/test_provider_runtime/README.md) +runs the ESP32 platform and production owner task in QEMU. Native and ESP32 +firmware are also cross-built with default and opt-in configurations. + +These tests do not qualify the revised firmware on a physical Commodore. Physical +UART timing, native stack/resource measurements, actual entropy, journal power-loss +behavior, exact controller-image installation verification and recovery remain +installation gates. Previous HTTP-only or prototype hardware results are not +hardware evidence for this implementation. Keep the coordinated candidate off +devices until those gates and an explicit hardware plan have been reviewed. diff --git a/doc/https-client.md b/doc/https-client.md new file mode 100644 index 000000000..20e51b96f --- /dev/null +++ b/doc/https-client.md @@ -0,0 +1,11 @@ +# HTTPS implementation + +The earlier prototype has been replaced by the connection/owner architecture +described in [HTTP and HTTPS transport](http-transport.md). The public HTTP command +interface remains unchanged; the TLS backend is replaceable. + +See [session ownership](https-session-contract.md), +[host regression](../target/pc/linux/test_http_tls/README.md), +[embedded runtime](../target/esp32/test_provider_runtime/README.md) and +[readiness](https-release-readiness.md). The revised implementation is opt-in and +has not yet been qualified on a physical Commodore. diff --git a/doc/https-device-validation.md b/doc/https-device-validation.md new file mode 100644 index 000000000..e24d3b9f7 --- /dev/null +++ b/doc/https-device-validation.md @@ -0,0 +1,15 @@ +# Device validation status + +The revised owner/provider implementation has not been installed or tested on the +physical Commodore. Host, cross-build and ESP32 emulator results must be reported +separately from device results. + +The [prototype report at its fixed revision](https://github.com/araxis/1541ultimate/blob/fc1498932ac0c01b16786660262ce2181fa3c80e/doc/https-device-validation.md) +preserves the earlier measurements and limitations. They do not apply to this +replacement implementation. HTTP-only checks from the merged prerequisite PRs +likewise do not establish revised HTTPS behavior. + +The installation and hardware gates are listed in +[release readiness](https-release-readiness.md). New device evidence must identify +both installed images, FPGA/device scope, endpoint certificates, complete attempts, +raw logs, peer observations and cleanup before claiming a pass. diff --git a/doc/https-hardware-runner.md b/doc/https-hardware-runner.md new file mode 100644 index 000000000..b692038b1 --- /dev/null +++ b/doc/https-hardware-runner.md @@ -0,0 +1,151 @@ +# Controlled HTTPS hardware runner + +This runner is opt-in. Local and emulator tests do not establish hardware readiness. +Installation and board-specific recovery qualification remain pending. + +## Prepared bring-up runner + +`tools/https_hardware_runner.py` validates a plan offline by default. Only +`--execute --installation RECORD` permits device access. The record must bind the +candidate and plan hashes, provide a current LAN address, expire within 24 hours, +and reference hashed local evidence for every installation/preflight gate. These +are operator/evidence gates, not remote attestation. Never mark an unverified gate +confirmed merely to start a test. + +The runner uses the repository's native 6502 UCI agent, with opt-in +`WAIT_WRAPS=$80` and `EXTERNAL_ABORT=1`. Default assembly remains byte-identical. +The HTTPS mode accepts a host cancellation mailbox while the command is pending; +the 6502 still writes the actual UCI abort register. The host has a 35-second +request guard and a 15-minute campaign guard. The longer 6502 counter is a +secondary escape, not a measurement of wall time. Use ordinary C64 CPU speed. +No tests are automatically retried. `operator.stop` ends progression at the next +host poll. Failure preserves evidence and does not attempt a reset/reinstallation. + +The fixed 43-exchange matrix covers: + +- HTTP GET/HEAD baseline, five HTTPS GETs and five HEADs, two chunked responses. +- Wrong hostname and untrusted chain, with a valid recovery request after each. +- Stalled handshake, response headers and response body, each followed by recovery. +- Cancellation during a stalled handshake and body, each followed by recovery. +- Ten repeated successful requests and five authentication failures. + +Each command's complete native result block, payload and host timing is retained. +The runner releases handles, observes a 180-second idle interval, checks release +again and requests a C64 CPU reset only when that cleanup action was explicitly +approved in the installation record. It never resets the management controller or +ESP32. A reset request alone is not confirmation that BASIC is visible. + +`tools/https_test_endpoint.py` is a bounded, allowlisted fixture. It supports +ordinary HTTP, TLS and a stalled TLS handshake. TLS routes provide fixed 2048-byte +responses, chunked responses, incomplete bodies and stalled headers/bodies. It +defaults to loopback; LAN binding requires an explicit peer allowlist. Keep keys +outside the repository. Use the production-trusted certificate for the valid +endpoint, the same certificate with a mismatched hostname for the name rejection, +and a separate private certificate for the untrusted-chain endpoint. Do not alter +production roots or the clock to make the tests pass. + +Endpoint logs must be on the same host, OS and monotonic clock as the runner. +The preflight rejects old/stopped/used logs, port mismatches and differing clock +domains before any device call. A Windows fixture and a WSL runner do not share +a clock domain; start the fixtures in the runner's environment instead. Cancel is +sent only after that endpoint records the relevant stall. After execution, stop +the fixtures and run `tools/audit_https_hardware.py` against their complete logs. +The audit requires exact requests, response bytes, one connection per exchange, +failed TLS before HTTP for authentication cases, observed client close during +stalls, complete closure and no extra/plaintext fallback connections. A run cannot +pass with a missing or truncated log. Hashes detect later changes relative to the +saved record; they do not authenticate the original evidence producer. + +The 1.5-second cancellation/peer-close guard includes host observation overhead. +It does not prove the firmware's 500-ms internal cleanup target. The first matrix +does not qualify resource trends, physical restart identity, journal durability, +entropy, trusted certificate-date rejection or power-loss recovery. Those remain +explicit held phases, and a matrix pass is not a full hardware qualification. + +## Device-free verification + +### Standard runner entry + +`run-tests -s https-hardware` is an explicit-only controlled campaign. No profile, +including deep/exhaustive, `--all`, or `--manual` selects it automatically. It must +run alone. Its dispatch occurs before target discovery, health probes, settings +capture/restoration, screen recording and reset/recovery orchestration. The +installation record supplies the sole target; do not supply a positional host or +`-H`. Ordinary execution options are rejected when they change defaults. The +campaign always has one attempt, regardless of the normal runner retry default. + +Validate a plan without device access (the default action is `prepare`): + +```sh +python3 run-tests -s https-hardware --https-plan plan.json -o runs/https-preparation +``` + +The directory must be new. Preparation records `SKIP` for the hardware suite and +exits zero for successful offline validation; it is not a hardware pass. Invalid +arguments exit 64. Invalid plans or failed child operations exit 3 and retain logs. + +Only after installation, recovery and every operator gate have been qualified, +explicitly authorize one execution using: + +```sh +python3 run-tests -s https-hardware --https-action execute \ + --https-plan plan.json --https-installation installation.json -o runs/https-execution +``` + +The existing plan, evidence hashes, expiry, candidate identity and fresh peer-clock +checks still run before device access. Authentication uses the standard `-p` or +`U64_PASS`; it is passed through the child environment, not logged in its command. +There is no automatic retry, configuration write, recovery command or management +reset. The explicitly gated final C64 CPU reset remains part of the campaign. +Create `runs/https-execution/campaign/operator.stop` to stop the campaign at its +next guard. Preserve that directory; never reuse it or silently resume a stopped run. + +Completed exchanges are recorded as `awaiting-independent-peer-audit`, with a +`SKIP` hardware verdict and exit 3, so an unaudited run cannot pass a release gate. +After stopping the fixtures normally, audit all their complete logs offline: + +```sh +python3 run-tests -s https-hardware --https-action audit \ + --https-evidence runs/https-execution/campaign \ + --https-peer peers/http.jsonl --https-peer peers/trusted.jsonl \ + --https-peer peers/untrusted.jsonl --https-peer peers/stall.jsonl \ + -o runs/https-audit +``` + +Repeat `--https-peer` for every distinct peer log (the trusted and wrong-name +origins may share a listener). Audit rereads the raw evidence; it does not accept +an earlier audit verdict as proof. A successful audit exits zero and reports only +`saved-evidence-audit-passed`. It does not distinguish fabricated traces from +physical evidence and does not qualify the held hardware phases above. + +Each invocation retains standard `https/run.jsonl` plan/suite/run records, +`result.json` and `https/controlled-https-hardware.log`. Preparation/execution artifacts live under `campaign/`; +successful audits add `audit.json`. Existing artifacts are never overwritten. +Run `python3 tools/tests/test_run_tests_https.py` directly for device-free entry, +gate and reporting regressions. This policy suite is also registered as +`https-runner-policy` from the quick profile upwards; ordinary `run-tests` profiles +still perform their normal bench setup, so use the direct script when offline. + +### Component and loopback checks + +Run `python3 tools/tests/test_https_hardware.py` for execution gates, full synthetic +trace audit, evidence mutations, orchestration stop behavior and loopback fixture +checks. These synthetic results must never be published as physical results. +The ordinary regression remains `tools/test_https_host.py` with the pinned TLS +tree. Retain failures alongside later successful attempts. + +For runner-to-fixture integration, run +`python3 tools/tests/test_https_runner_loopback.py --output OUTPUT_DIRECTORY` +under Linux with OpenSSL installed. It executes the unchanged 43-case controller +against real loopback HTTP/TLS endpoints through a substituted host transport. +The substitute creates UCI-shaped results; it does not execute the 6502 agent, +management firmware or ESP32 backend. Every saved run is marked as host-only. +An in-process socket guard rejects non-loopback connections and binds. Temporary +test certificates are trusted only by that host client; private keys are removed +afterward. Production trust configuration and installation gates are unchanged. + +This integration test uses a 750-ms host-client timeout for fault injection and +checks prompt cancellation separately, so it does not qualify firmware deadlines. +It retains the real 180-second idle interval, complete peer logs, raw simulated +transactions, an independent matrix audit and an operator-stop rejection case. +Only the simulated final CPU-reset request is recorded; no device is contacted. diff --git a/doc/https-release-readiness.md b/doc/https-release-readiness.md new file mode 100644 index 000000000..bd0209304 --- /dev/null +++ b/doc/https-release-readiness.md @@ -0,0 +1,30 @@ +# HTTPS review and installation gates + +The draft implementation can be reviewed independently of device installation. +It must not be described as hardware-qualified or ready to flash. + +Before installation: + +1. Identify the installed controller and confirm the FPGA variant. The RAM-only + diagnostic is locally tested, but has not been executed on the device. +2. Close exact controller-image installation/readback verification and equal/newer + version handling. The updater's transfer acknowledgements are not a hash readback. +3. Review the configuration backup, identity-journal reservation and practical + recovery procedure. A saved backup is not proof that restore/recovery works. +4. Prepare the trusted endpoint and fixed hardware runner/peer acceptance criteria. +5. Review the coordinated native/controller image hashes and authorize installation. + +Then qualify ordinary HTTP and HTTPS on the exact installed revision: valid GET +and HEAD, authentication failures, original deadlines, cancellation, restart +fencing, repeated cleanup and resource measurements. Physical UART timing, actual +entropy, journal persistence/endurance and native stack use remain unqualified. + +The selected ordinary SNTP source is unauthenticated. Certificate date checks are +mandatory, but clock bounds do not authenticate the time source. Journal rollback +and cloning cannot be detected by CRC. These limitations remain explicit. + +Prior prototype and HTTP-only device results, and standalone TLS duration runs, +are historical evidence. They are not qualification of this connected firmware. +Maintainer agreement on UART command allocation and shared-backend integration is +also pending. Keep default activation disabled and the PR in draft until the +remaining scope and acceptance criteria have been reviewed. diff --git a/doc/https-session-contract.md b/doc/https-session-contract.md new file mode 100644 index 000000000..2a05dfe92 --- /dev/null +++ b/doc/https-session-contract.md @@ -0,0 +1,71 @@ +# HTTPS session ownership and restart contract + +This contract is implemented by the native manager, copied UART queues and ESP32 +owner task. A separate host model checks event ordering; the model is not linked +into firmware. Target-6 HTTP commands, handles, rendering and status strings are +unchanged. All production activation remains opt-in. + +## Ownership + +`HttpTarget` owns its connection; `HttpRequest` borrows it. The request is destroyed +first. A connection is single-use, including close before open. Recovery creates +a fresh exchange and never replays a failed write. + +Only the owner executes TLS operations or frees TLS resources. Other tasks signal +cancellation and copy messages into bounded queues. They do not close sockets or +free session state while the owner is blocked. The owner observes cancellation, +discards uncommitted results and cleans up once before acknowledging close. + +## Identity and admission + +A solicited identity exchange and the control handshake must succeed before work +is admitted. Product version numbers are not capability evidence. Replies must +match the outstanding request, native incarnation, provider boot, grant, session +and operation identifiers. Foreign, stale, replayed or out-of-order completions +cannot publish data. Identity counters fail closed on exhaustion. + +The native identity combines a provisioned journal domain and a committed durable +epoch. ESP32 boot identity uses its qualified boot entropy path. A host model's +symbolic identity is not a substitute for either source. The journal's rollback, +clone and power-loss limitations are described in [provisioning](../target/pc/linux/test_http_tls/PROVISIONING.md). + +The control protocol uses Offer, Initialize, Renew and Close. Initialization waits +for confirmed cleanup of the previous owner. Leases expire without renewal; a +renewal must be the next expected sequence for the current unexpired grant. +Lost communication never produces a fabricated cleanup acknowledgement. + +## Cancellation, restart and deadlines + +| Event | Required behavior | +| --- | --- | +| Open succeeds | Admit I/O only after authentication and identity checks | +| Open fails | Retain the diagnostic, close, require a fresh exchange | +| Data completion arrives | Validate identity, cancellation and deadline before publishing | +| Cancellation is observed | Fence uncommitted data and let the owner clean up | +| Either endpoint restarts | Retire old grants; renegotiate without resuming old work | +| Wi-Fi link is lost and returns | Fail pending work and negotiate from a fresh provider snapshot. A matching Busy initialization reply keeps HTTPS unavailable. Retry initialization on the same offer after 50 ms, within 1500 ms of sending the offer. Only a matching success admits requests. | +| Control reply expires before the ESP32 restart is observed | Retire the grant at the reply deadline. Wait for the old provider lifetime to be cancelled and a different boot identity to be observed before negotiating again. A late reply or a reconnect with the same boot cannot revive the grant. Queue overflow, lease expiry, send failure and rejection remain terminal on a live link. | +| Reply/queue overflow or send failure | Retire the affected generation | +| Lease expires | Cancel work and release resources through the owner | +| Repeated close | No second release or publication | + +The native exchange budget is 30 seconds and cleanup bound is 500 ms. Those are +configured software bounds, not measured physical guarantees. Control servicing +during long TLS calls consumes at most one event per cancellation check and never +recursively performs resource cleanup. Valid renewals preserve the owner lease +but cannot extend the original HTTP deadline. + +Data ingress copies bounded frames before returning. One data operation is pending +per session; waiting for the owner consumes the same deadline. ISR code only +copies/fences input. Boot, control and data framing are explicitly versioned and +reject malformed lengths and padding. The current development framing still needs +maintainer agreement with other UART clients before it becomes a stable protocol. + +## Evidence boundary + +Host tests exercise real TLS peers through the connected target/manager/provider +components and separately test deterministic scheduler, flash and ISR ports. +ESP32 QEMU tests execute the production owner task with a protocol actor in place +of the native processor and physical UART. Neither proves real-device scheduling, +entropy, storage durability or safe installation. Global heap snapshots include +network cleanup state and must not be equated with scoped TLS allocation balance. diff --git a/doc/https-startup-review.md b/doc/https-startup-review.md new file mode 100644 index 000000000..1c934f21d --- /dev/null +++ b/doc/https-startup-review.md @@ -0,0 +1,93 @@ +# ESP32 startup and version review + +The boot identity is now sampled after `esp_wifi_start()` succeeds and before +the connector and command dispatcher start. The HTTP command interface is +unchanged. Wi-Fi association is not required for this initialization. + +Previously, `app_main()` called `bootloader_random_enable()` and +`bootloader_random_disable()` before ADC and Wi-Fi initialization, including in +the default build. In ESP-IDF 5.3.1 the ESP32-S3 disable implementation asserts +the SARADC digital reset and changes the SAR power setting. Those operations +bypass the ADC/PHY driver's shared power accounting. The application no longer +uses this temporary SAR entropy source; successful RF startup supplies entropy +for `esp_fill_random()` instead. + +The identity is generated once per controller boot. A failed Wi-Fi start does +not generate it, a zero identity remains unavailable, and later Wi-Fi disable +and enable cycles retain it. The existing TLS entropy policy still becomes +unavailable when Wi-Fi stops. These rules preserve restart fencing without +adding a second ADC initialization sequence. + +## Version selection + +With upstream at 1.30, the provisional default and provider versions are +**1.38** and **1.39**, respectively. Confirm the allocation and merge order +before installation. Earlier builds used 1.22/1.23 and 1.30/1.31. This matters because +the ordinary C64U/U64-II updater installs a controller image only when its numeric version +is newer; equal versions are skipped. TLS capability still requires explicit +negotiation and cannot be inferred from a version number. + +These numbers are relative to the reviewed source base. Reconcile them with +other pending controller changes, including +[the IDF 6 migration](https://github.com/GideonZ/1541ultimate/pull/1028), before +merging or building an installation package. Previously built 1.22 provider +packages do not contain this correction and must not be relabeled or reused. + +## Local validation + +Four startup regressions compile the production boot implementation, the Wi-Fi +start/stop wrappers and both version configurations under ASan/UBSan. They check +RF-start failure, successful initialization, zero-identity rejection, repeated +starts, TLS entropy revocation, ADC-state preservation and startup ordering. +All four fail against the previous source and pass with the correction. +Three deliberately reintroduced defects are also rejected: SAR manipulation, +identity generation after a failed RF start, and identity regeneration. + +Default and provider-enabled modules build on ESP-IDF 5.3.1 and 5.3.6. Saved +binary labels, provider configuration and artifact hashes are checked. The +compiled boot-identity object references `esp_fill_random` and neither +`bootloader_random_enable` nor `bootloader_random_disable`. + +The complete serial host run passed 82 stages, 18,865 counted assertions, +37 parser tests and 184 TLS cases across both certificate profiles. The four +new startup tests are reported separately from the assertion total. The +independent raw-log/peer audit passed and rejected all seven altered or missing +evidence examples. + +An earlier run overlapped module builds and failed a connected ECDSA +`command-read-cancel` peer check: its fixed 150 ms cancellation timer fired +before authentication completed, so the primary peer received no HTTP request. +The failure and peer log are retained. The unchanged suite passed when run +serially; that does not establish that the fixture is immune to scheduling +delays. No production deadline or evidence acceptance condition was relaxed. + +This establishes the software ordering and removes the identified peripheral +side effects. It does not measure physical ADC voltages, RF entropy quality or +Wi-Fi startup on a C64U. Those checks remain part of the controlled hardware +plan after recovery qualification and installation authorization. + +## IDF 6 compatibility + +The new boot implementation compiles against the ESP-IDF 6.0.3 `esp_random.h` +API. The complete firmware is **not yet IDF 6 compatible**. Compiler probes +against its pinned Mbed TLS revision +`ce3f3485a121c100f58f36d700cb35b060f6e866` confirm these blockers: + +- The pinned TLS core includes the removed `mbedtls/ctr_drbg.h` and calls + `mbedtls_ssl_conf_rng`, which is no longer declared. +- Recovery signature verification includes the removed `mbedtls/sha256.h` and + calls the removed `mbedtls_pk_get_type`. Header probes accept the replacement + PSA hash and `mbedtls_pk_get_key_type` APIs; the recovery port and runtime + validation still remain. +- The UART integration also needs the IDF 6 header/type migration described + in the pending SDK update; the existing source still uses `soc/uart_periph.h`. + +Use the supported PSA initialization, hash and RNG interfaces when porting. +Preserve the trust, clock and RF-entropy gates, authentication failures, +cancellation, deadlines and cleanup tests. A successful header probe is not a +full IDF 6 build or runtime qualification. No production SDK or TLS dependency +pin was changed in this review. + +References: [ESP32-S3 entropy requirements](https://docs.espressif.com/projects/esp-idf/en/v5.3.1/esp32s3/api-reference/system/random.html), +[IDF 5.3.1 SAR implementation](https://github.com/espressif/esp-idf/blob/v5.3.1/components/bootloader_support/src/bootloader_random_esp32s3.c), +[IDF 6 security migration](https://github.com/espressif/esp-idf/blob/v6.0.3/docs/en/migration-guides/release-6.x/6.0/security.rst). diff --git a/doc/https-uart.md b/doc/https-uart.md new file mode 100644 index 000000000..eed23d5cb --- /dev/null +++ b/doc/https-uart.md @@ -0,0 +1,15 @@ +# HTTPS UART integration + +The prototype TLS_STREAM/METRICS command pair has been replaced by the +[owner/session protocol](https-session-contract.md). Version strings alone do not +enable HTTPS. Identity, capability, lease and operation validation happen before +requests or completions are accepted. + +The current development layout is defined by `provider_identity.h`, +`provider_control.h` and `provider_data.h`, with native delivery in +`provider_manager_uart.cc` and ESP32 routing in `rpc_dispatch.c`. Receive ingress +copies bounded messages and preserves the ordinary Wi-Fi reply table. + +The framing is still experimental. Shared command allocation and interoperability +with other TLS clients require maintainer agreement before stabilizing it. +Physical UART timing and buffer-pressure qualification remain pending. diff --git a/doc/https-usage.md b/doc/https-usage.md new file mode 100644 index 000000000..dc16a587b --- /dev/null +++ b/doc/https-usage.md @@ -0,0 +1,35 @@ +# Using HTTP and HTTPS + +Both protocols use command-interface target 6. Select the protocol in the URL: +`http://example.test/path` or `https://example.test/path`. HTTPS is outbound client +support; it does not secure the device's management web server. The revised +firmware remains experimental and is not yet qualified on physical hardware. + +Commands below are hexadecimal bytes; `H`, `RH` and `RB` are returned byte handles. +Strings are ASCII and NUL-terminated. Check each status before using its data. + +| Operation | Bytes | Successful result | +| --- | --- | --- | +| Create GET | `06 11 01 "URL" 00` | Header handle `H` | +| Add header | `06 13 H "User-Agent: C64-HTTP/1.0" 00` | `000 OK` | +| Exchange JSON | `06 31 H FF` | Response header/body handles `RH RB` | +| Query JSON | `06 2A RB "key" 00` | Existing typed JSON representation | +| Exchange raw body | `06 32 H FF` | Body bytes and HTTP status/header prefix | +| Free header | `06 12 H` | `000 OK` | +| Free body | `06 22 RB` | `000 OK` | + +`FF` selects no request body. Free returned response handles as well as request +handles. Raw bodies use the existing continuation mechanism and Data Last flag; +acknowledge the final block even when it is empty. The command interface is not a +new BASIC function or client library. + +HTTPS defaults to port 443 and requires a matching certificate hostname, trusted +chain, qualified clock, entropy and negotiated provider. Applications do not send +certificates or clock values with each request. Failures return the existing +`503 SERVICE UNAVAILABLE` status without automatic HTTP fallback. The opt-in +native provider uses a 30-second total exchange budget; this is not a timing +guarantee for ordinary HTTP. + +See [transport and framing](http-transport.md), +[provisioning](../target/pc/linux/test_http_tls/PROVISIONING.md) and +[readiness](https-release-readiness.md) before enabling firmware options. diff --git a/doc/https-validation.md b/doc/https-validation.md new file mode 100644 index 000000000..1e1cff7ed --- /dev/null +++ b/doc/https-validation.md @@ -0,0 +1,166 @@ +# HTTPS validation snapshot — October 30, 2026 + +This is a draft review candidate, not an installation or hardware qualification. +The initial host and cross-build snapshot is +`fb8c76ab3141135f33aa74533ec068f608788d1f`. Documentation and explicit CI package +declarations added after this snapshot do not change the tested firmware inputs. +The subsequent factory-test and parser-preparation corrections are recorded below. + +The later [startup and version review](https-startup-review.md) removes the +application's SAR entropy manipulation and separates default/provider versions +as 1.22/1.23. The table below is the earlier historical snapshot; its module +versions and packages are not the corrected installation candidate. + +## Results + +| Validation | Result | +| --- | --- | +| Device-free host regression | 81 stages; 18,865 assertions; zero failures | +| HTTP parser unit tests | 37 tests passed | +| TLS peer matrix | 184 cases across seven paths and RSA/ECDSA; each includes recovery | +| Host evidence rejection checks | All seven incomplete, missing or altered examples rejected | +| Native firmware | Default and journal-enabled variants built | +| ESP32 firmware | Default 1.21 and provider-enabled 1.22 variants built | +| Embedded owner fixture | RSA/ECDSA QEMU: 644 checks, 48 attempts, two boots | +| Embedded evidence rejection checks | All 24 altered or incomplete examples rejected | +| RAM identity diagnostic | 61 sanitized host checks and 12 instruction/MMIO scenarios | +| Experimental installer | 23 orchestration scenarios; seven unsafe variants rejected | +| Installer packages | Combined, XC7A50T and XC7A100T builds; carried payloads/checksums audited | + +The host assertion total includes the session model's 1,354 checks and the assembly +suite's 172 checks. Parser test counts and mutation checks are separate; they are +not added to that assertion total. Wi-Fi reply-table and ingress tests also pass. +The published head `bf5c7b0` passed the hosted HTTPS host check, but its Build job +failed in the factory-test link described below. + +Reproduce the host run using the public dependency pins and command in +[the host test README](../target/pc/linux/test_http_tls/README.md). Complete raw +logs, peer records, command results and independent audits are retained in the +review evidence package. Its download link must be verified when it is published; +no unpublished download URL is represented here as available. + +## Factory-test build correction + +The [hosted Build job](https://github.com/GideonZ/1541ultimate/actions/runs/41028507948/job/123972319735) +failed because the U64-II factory tester links `wifi_cmd.cc` without the WiFi +application that defines `wifi_provider_receive`. A fresh local cross-build of +`bf5c7b0` reproduced that undefined reference. + +The factory target now selects `WIFI_COMMANDS_ONLY`, excluding the provider +ingress hook while retaining frame-length checks and ordinary RPC reply handling. +Normal firmware keeps the hook; recovery keeps its existing exclusion. No HTTP +interface or provider protocol changes are involved. + +Local checks on the correction passed: + +- Factory application, ELF, simulation output and raw binary cross-build. +- Default and journal-enabled U64-II application cross-builds. +- Sanitized command tests for normal, factory and recovery configurations, + covering frame rejection, reply delivery, timeouts and late replies. Factory + and recovery tests supply no provider stub. The factory regression fails to + link with the original guard and passes with the correction. +- Symbol checks: factory retains the receive ISR without the provider hook; + normal firmware retains the provider hook. +- Complete host regression: 81 stages, 18,865 counted assertions, 37 parser tests + and 184 TLS cases with recovery. Independent evidence audit passed and all + seven missing or altered evidence controls were rejected. + +Cross-builds used xPack RISC-V GCC 11.3.0. These results are local; the full hosted +multi-board Build job has not been rerun with this correction. No firmware was +installed or executed on a device. Previous hardware and installation gates remain. + +## Reused-checkout parser preparation + +The next [hosted Build run](https://github.com/GideonZ/1541ultimate/actions/runs/41031130807/job/123980867788) +at `5953aaf` stopped before compilation: parser inputs did not match the complete +before or after manifest. Its log shows a reused checkout with a top-level reset +and forced submodule checkout. It does not include individual parser file hashes. + +A local regression reproduces the same error with that checkout sequence: +tracked files return to the public pin, but the patch-created, untracked +`response_test.cpp` survives. Preparation now retains that addition only when it +matches the reviewed result hash and all tracked inputs match the public pin. +It applies the remaining entries and verifies all result hashes. Unknown contents +are still rejected, and no broad cleanup or reset was added to preparation. + +All 14 preparation tests pass, including three consecutive real submodule +checkout/reset cycles, repeat application, source exports, LF/CRLF inputs and +preservation of unrelated files. Negative tests check that modified or missing +inputs, partial patches and changed patch contents fail without writing files. +The local workflow changes add this regression to both jobs. + +The corrected preparation also passes the full 81-stage host suite (18,865 counted +assertions, 37 parser tests and 184 TLS cases with recovery), the independent host +evidence audit and all seven evidence rejection controls. Default U64-II application +and factory cross-builds pass. The regression fails with the original helper. +These are local results; hosted CI has not run with this preparation correction. + +## Provenance and limits + +The candidate includes upstream `03c70e6e` and preserves published PR history at +`26a8938319e35494c5a7371d992797bc0f8743fb`. The TLS core is pinned to +`529b0450955611bd82db921db3bae10222203eba`, Mbed TLS to +`2b96dd8eebe880f304c69976b3c2fa0c5100cbb6`, and ESP-IDF to +`79e3454c68248bd7d881721c9b2e94561378a8ce`. The public HTTP submodule base is +`ad73d3217bb0e1b3f37e0dbba595309b942aea17`; the checked-in framing patch and hash +manifest are applied by `tools/prepare_http_parser.py`. A private submodule +commit is not required. + +QEMU ran source `645a15cc4d0b6f349920b3def04ead3e296c7ec5`. Archive comparison +confirms that its embedded runtime inputs are byte-identical to the final host +snapshot. Subsequent differences are the host runner/fixture and diagnostic or +installer files, not the embedded runtime. Both runs used the repository CA +list pinned at the time, SHA-256 `796f1389bfea13c0ed78f663b765baaff54a508e5483786bd6ece73c5e3e3cbe`. + +The embedded runs measured minimum stack margins of 9,188 bytes (RSA) and 8,344 +bytes (ECDSA), maximum scheduling gaps of 11/25 ms and maximum acknowledgement +latency of 21 ms. Free heap declined by 2,756/2,736 bytes between the first and +last samples. Balanced scoped allocations do not establish global leak freedom; +that decline and the earlier long-duration findings remain part of the record. +These are emulator measurements, not native-device memory or timing guarantees. + +No revised firmware was installed or executed on a physical device during this +validation. U64/U2-family device coverage, actual UART behavior, entropy, journal +durability, exact post-write controller verification and recovery remain open. +The diagnostic and installer artifacts are held, not released for installation. +See [the installation gates](https-release-readiness.md). + +## Failures retained and corrected + +- Fresh exports exposed an HTTP patch application problem when a parent Git + repository was present. The helper now applies from the repository root with + an explicit destination; clean exports and real submodule layouts pass. +- Parser tests initially used C++14 against a GoogleTest installation requiring + C++17. The host runner now selects C++17 explicitly. +- Upstream Wi-Fi tests exposed a heavyweight ingress-header dependency. A small + ingress interface preserves the upstream reply tests and validates frame size. +- The HTTP general test initially ran outside its fixture directory. The runner + now sets its working directory explicitly. +- One connected ECDSA total-deadline case exposed an undelivered renewal in the + synchronous host fixture. The fixture now delivers that exchange before the + next operation or terminal close. Production owner code and time bounds were + not relaxed; the complete matrix subsequently passed. +- A separate installer export omitted the HTTP submodule and failed to compile. + Its corrected export includes the public submodule and verified patch. +- Review found that strict installer gates affected the ordinary updater and + that the paired controller label could differ. The ordinary updater is restored + byte-for-byte from upstream. Strict gates live in the explicitly selected + coordinated updater, with required native/controller hashes and label checks. + +Failed runs remain separate from the successful snapshot. Earlier prototype +hardware evidence and standalone TLS soaks are historical results, not passes +for this connected revision. + +## Migration from the published prototype + +The command target, HTTP operations and caller-visible interface remain unchanged. +The prototype-specific TLS stream and metrics commands are replaced by identity, +capability and owner-session negotiation behind a replaceable secure provider. +The development UART allocation still requires maintainer agreement. + +The old prototype's device scripts depend on its removed protocol and metrics. +They are not presented as passing tests for this implementation. The current host +matrix and embedded fixture cover the replacement locally; adapting the physical +runner to the project's E2E framework and qualifying the device remain explicit +work. Original scripts and hardware reports remain in published commit history. +The independently merged HTTP fixes and upstream tests are retained. diff --git a/doc/softiec_compatibility_spec.md b/doc/softiec_compatibility_spec.md new file mode 100644 index 000000000..39aed77ed --- /dev/null +++ b/doc/softiec_compatibility_spec.md @@ -0,0 +1,2740 @@ +# Software IEC: CMD DOS, sd2iec and C64 OS compatibility + +**Status: the contract.** This describes what the Software IEC drive does and why. +Every requirement is either in force, and the tests in `target/pc/linux/parse`, +`target/pc/linux/iecdrive` and `tests/e2e/io/iec` hold the drive to it, or it is marked +**Deliberately unsupported** and says what the drive answers instead and why that is the +right answer. Section 18.1 lists the deliberate exclusions in one table, with the +requirements that answer differently from one of their sources; section 19 lists what is +out of scope, which is the capabilities this drive does not have at all. + +"In force" means implemented in this repository and held to by those tests. A firmware +release answers as this document describes only from the release that carries the change, +so a requirement can be in force here and absent from the newest released build. The +release each requirement first ships in is not tracked here; `git log` on the files a +requirement names answers that, and the pull request that introduces a requirement says +so in its own description. + +Two further documents describe the same drive from other angles: +[software/test/iecdrive/doc.md](../software/test/iecdrive/doc.md) on the name mapping and +[tests/e2e/io/iec/README.md](../tests/e2e/io/iec/README.md) on the hardware tests. +[doc/filenames_design.txt](filenames_design.txt) is the original design note for the +mapping. + +The goal is that an Ultimate 64 or Ultimate II+ can be the system drive of C64 OS, +and that in doing so it also becomes a closer replacement for an sd2iec, a CMD HD, a +CMD FD, a CMD RAMLink and an IDE64 for every other program that already targets +those. Issues [#877](https://github.com/GideonZ/1541ultimate/issues/877) and +[#890](https://github.com/GideonZ/1541ultimate/issues/890) are the immediate +drivers, with [#917](https://github.com/GideonZ/1541ultimate/issues/917) added later; this document covers the whole command surface those issues sit in, so the +work can be done once rather than one report at a time. + +The Software IEC drive has shipped for years to a large install base, so every +requirement states the source of truth it comes from, and the requirements that ask for +nothing unusual are written down as well, because they are the contract that later work +must not break. + +Where a requirement cites a measurement, it was obtained by running the command through +`IecCommandChannel::push_command()` and reading `IecDrive::get_error_string()` back, in a +probe linked against the same object files `target/pc/linux/iecdrive` links. + +Nothing in this document is left open. Where the sources disagreed, section 16 states +which primary source settled it, and for two of the cases that source is the 1541 ROM +in `roms/1541.bin` rather than any manual. + +--- + +## Contents + +- [1. Sources of truth and how conflicts are settled](#1-sources-of-truth-and-how-conflicts-are-settled) + - [1.1 Source register](#11-source-register) + - [1.2 Precedence](#12-precedence) + - [1.3 Acceptance](#13-acceptance) + - [1.4 Notation](#14-notation) + - [1.5 Conformance and traceability](#15-conformance-and-traceability) + - [1.6 Terminology](#16-terminology) +- [2. The model](#2-the-model) + - [2.1 Device, partitions, directories](#21-device-partitions-directories) + - [2.2 What the partition model must not do](#22-what-the-partition-model-must-not-do) +- [3. Command string grammar](#3-command-string-grammar) + - [3.1 Path syntax](#31-path-syntax) + - [3.2 The left arrow](#32-the-left-arrow) + - [3.3 The command terminator](#33-the-command-terminator) + - [3.4 Numeric parameters](#34-numeric-parameters) + - [3.5 Command length](#35-command-length) +- [4. Error codes](#4-error-codes) + - [4.1 The table](#41-the-table) + - [4.2 The error codes that are not CBM DOS errors](#42-the-error-codes-that-are-not-cbm-dos-errors) +- [5. Partition commands](#5-partition-commands) + - [5.1 Change partition](#51-change-partition) + - [5.2 Get partition info](#52-get-partition-info) + - [5.3 Partition directory](#53-partition-directory) + - [5.4 Other partition commands](#54-other-partition-commands) +- [6. Directory commands](#6-directory-commands) +- [7. File commands](#7-file-commands) + - [7.1 Open](#71-open) + - [7.2 Scratch, rename, copy](#72-scratch-rename-copy) +- [8. Relative files](#8-relative-files) +- [9. Direct access](#9-direct-access) +- [10. Device commands](#10-device-commands) +- [11. Device identification](#11-device-identification) +- [12. Real time clock](#12-real-time-clock) +- [13. Directory listings](#13-directory-listings) + - [13.1 Layout](#131-layout) + - [13.2 Filters](#132-filters) + - [13.3 Raw directory](#133-raw-directory) + - [13.4 File types inside a disk image](#134-file-types-inside-a-disk-image) +- [14. File naming on the host file system](#14-file-naming-on-the-host-file-system) + - [14.1 The scheme that already exists](#141-the-scheme-that-already-exists) + - [14.2 x00 wrappers](#142-x00-wrappers) + - [14.3 The shifted space](#143-the-shifted-space) +- [15. Limits, and what must not break](#15-limits-and-what-must-not-break) + - [15.1 Limits](#151-limits) + - [15.2 Behaviour that must not change](#152-behaviour-that-must-not-change) + - [15.3 Consequences elsewhere](#153-consequences-elsewhere) +- [16. Conflicts between the sources, and how each is decided](#16-conflicts-between-the-sources-and-how-each-is-decided) +- [17. Tests](#17-tests) +- [18. The operation log](#18-the-operation-log) + - [18.1 Deliberately unsupported, and the differences from the sources](#181-deliberately-unsupported-and-the-differences-from-the-sources) +- [19. Out of scope](#19-out-of-scope) +- [Appendix A. What C64 OS sends](#appendix-a-what-c64-os-sends) +- [Appendix B. Requirement index](#appendix-b-requirement-index) +- [Appendix C. The programs issue #917 reports](#appendix-c-the-programs-issue-917-reports) +- [Appendix D. Conformance against the two C64 OS reference articles](#appendix-d-conformance-against-the-two-c64-os-reference-articles) + - [D.1 GAP, "Gaps in Software IEC"](#d1-gap-gaps-in-software-iec) + - [D.2 GSD, "SD2IEC User's Manual"](#d2-gsd-sd2iec-users-manual) +- [Appendix E. Traceability](#appendix-e-traceability) + +--- + +## 1. Sources of truth and how conflicts are settled + +### 1.1 Source register + +| Code | Source | +| --- | --- | +| **1541** | [*1541-II Disk Drive User's Guide*](https://www.zimmers.net/anonftp/pub/cbm/manuals/drives/1541-II_Users_Guide.pdf), DOS error message list. Where a point needs a Commodore drive other than the 1541, the *1571* and *1581 User's Guides* are cited by name. | +| **917** | Issue [#917](https://github.com/GideonZ/1541ultimate/issues/917), "More SoftIEC compatibility issues", opened by the reporter on 18 September 2026. It carries Greg Nacu's measurements of a CMD HD and an sd2iec against this drive, and photographs of the two BASIC programs he used. The programs are transcribed in appendix C. | +| **FD** | [*CMD FD-Series Disk Drives User's Manual*](https://archive.org/details/CMD_FD_Series_Disk_Drive_Users_Manual_1993-10_Creative_Micro_Designs). | +| **FDROM** | The CMD FD-2000 DOS V1.40 ROM, 32768 bytes mapping to `$8000..$FFFF`, SHA-256 `e6b9c7562cc51ebe5577840db29d10fb0a1b8540f7cd5fbee6cc2e15f49a9f72`. It is not in this repository. Quoted addresses are from a disassembly of that image. | +| **GAP** | Greg Nacu, ["Gaps in Software IEC"](https://c64os.com/post/softwareiecgap), 10 January 2023. The canonical statement of why C64 OS does not support this drive. Written against firmware 3.10a; several of its items are already fixed. | +| **GFN** | Greg Nacu, ["Understanding SD2IEC Filenaming"](https://c64os.com/post/sd2iecfilenames). | +| **GSD** | Greg Nacu, ["SD2IEC User's Manual" v1.3](https://c64os.com/post/sd2iecdocumentation). | +| **GUG** | [*C64 OS User's Guide*, File System chapter](https://c64os.com/c64os/usersguide/filesystem). | +| **HD** | *CMD HD Hard Drive User's Manual*, 4th edition, January 1991. The scan linked on issue #877, [primrosebank.net scan](http://www.primrosebank.net/computers/pet/documents/CMD-HDD-Manual_OCR.pdf). Page numbers are the manual's own, e.g. 9-15, B-2. A second copy is on [archive.org](https://archive.org/details/cmd-hd-series-user-manual-4th-ed-2nd-printing-feb-1993-creative-micro-designs-inc). | +| **HDR** | [*CMD HD Manual Remaster V0.2*](https://archive.org/details/cmd-hd-manual-remaster). Same text, cleaner typesetting. Used to resolve OCR damage in HD. | +| **IDE** | [*The IDE64 Project user's guide*](https://s3.amazonaws.com/com.c64os.resources/weblog/sd2iecdocumentation/manuals/IDE64_Users_Guide.pdf), IDEDOS 0.90, 24 February 2019. Section numbers as printed. Linked by the reporter on #877. | +| **RL** | [*CMD RAMLink User's Manual*](https://archive.org/details/CMD_RamLink_Users_Manual). | +| **ROM** | [`roms/1541.bin`](../roms/1541.bin) in this repository, 16384 bytes, mapping to `$C000..$FFFF`. Quoted disassembly was produced from that file. | +| **SD** | SDU and SDM together: a citation reads `SD` only where SDU and SDM carry the same behaviour at the commits their rows name, which was checked for every function, constant and README passage this document cites. Where they differ, the citation names SDU or SDM, and the requirement says what the other one does. | +| **SDBUGS** | [`markusC64/sd2iecCommonBugs`](https://github.com/markusC64/sd2iecCommonBugs), a list of defects the sd2iec family shares, kept by the reporter of #877 and #917. A report is on it when it is in the upstream firmware or in three independent forks. It is not a source of truth for what this drive does: it says what other implementations get wrong, and `Suite11-CommonBugs` checks this drive against it. | +| **SDM** | sd2iec as extended by the reporter of #877 and #917, [`markusC64/sd2iec`](https://github.com/markusC64/sd2iec) at commit `9087321` on its `devel` branch, 4 September 2026. A fork of SDU that tracks it and adds, among other things, the attribute, locking and header commands, the `$` image write lock and the extension mode 5 name mapping. Paths are `src/...`, and `SDM README` is its README, which the reporter named as this drive's sd2iec documentation. | +| **SDU** | sd2iec as it ships, [`thierer/sd2iec`](https://github.com/thierer/sd2iec) at release [`v1.0.0atentdead0-186-g069555f1`](https://github.com/thierer/sd2iec/releases/tag/v1.0.0atentdead0-186-g069555f1), commit `069555f1`, 13 June 2026. A clone of the original at `sd2iec.de`, and the line a user is most likely to be running. Paths are `src/...`, and `SDU README` is its README. | +| **TRACE** | [`log_boot.log.txt`](https://github.com/user-attachments/files/32097131/log_boot.log.txt), attached by the reporter to #877 on 11 September 2026. 601 lines of `SOFTIEC-TRACE` output from one successful C64 OS boot on a U64 II. | +| **U** | This firmware, [GideonZ/1541ultimate](https://github.com/GideonZ/1541ultimate). Paths are relative to the repository root. | + +### 1.2 Precedence + +The reporter set the rule on #877, 11 September 2026: "If the sources differ, then +you have to decide on a case-by-case basis, but most of the time it will come down +to the decision I made in my SD2IEC branch, because that's where I made the +decision." + +This specification applies it as follows. + +1. Where CMD DOS defines a behaviour and every later device copied it, that + behaviour is normative. HD is the reference text, with FD and RL used for the + points where the three CMD devices differ from each other. +2. Where a behaviour exists only because a device has a host file system underneath + it, **SD** is normative, because that is the device the Ultimate most resembles + and the one the reporter maintains. +2a. Where SDU and SDM differ, SDU is normative, because that is the line a user is + likely to be running, and the requirement says what SDM does. Three such conflicts were + found. The hidden attribute inside a disk image, which SDU clears from the type byte + and SDM keeps behind a setting: this drive follows SDU (SI-134). And `,M`, which SDU + opens read and write on a FAT file system and SDM opens for reading: this drive + follows SDM, for the reason SI-070 gives, which is the exception that proves the rule + is about behaviour rather than about which line it came from. And the rename of a file + that lives in an x00 wrapper, where SDU writes the header alone and SDM renames the + host file to match it: this drive follows SDM, for the reason SI-144c gives. Where a + command exists in SDM only, there is nothing to conflict with, and the requirement + says that it rests on SDM alone: SI-064's optional id, SI-077, SI-077a and the name + mapping of SI-140 to SI-148. SI-076's `L` is a CMD command (HD 9-30); only its + sd2iec citation, for the toggle, is SDM's. +3. Where IDE and SD disagree, SD wins, and the difference is recorded in section 16. +4. Where a source disagrees with the reporter's own measurement on real hardware, + neither wins on authority. The disagreement is resolved from a primary source that + can settle it, normally the 1541 ROM in `roms/1541.bin`, and section 16 states the + evidence. Nothing in this document is left open. +5. Ultimate extensions are allowed where they cannot be mistaken for a documented + command and do not change the answer to one. + +### 1.3 Acceptance + +The specification is met when all of the following hold. + +* **A1.** C64 OS installs on, boots from and runs from a Software IEC partition, with + no error on the command channel that a CMD HD would not also produce. +* **A2.** Every requirement in force is traceable to a test that names it, as section 1.5 + requires and appendix E shows. The exceptions are the requirements that state only what + is out of scope and name no answer (SI-106, SI-115), and the retired SI-151. +* **A3.** Nothing in section 15.2 behaves differently. + +### 1.4 Notation + +**Normative text.** A requirement is a numbered paragraph beginning `SI-nnn`. Its +statements are normative and are written in the present indicative: "the drive answers +`31`" states what the drive does and what an implementation has to keep doing. `must` and +`must not` appear where a statement is a prohibition or where it is easy to read an +obligation as a description. Nothing here uses `should` or `may`: a requirement that is +optional would say nothing an implementation could be held to, and the deliberate +exclusions are listed instead (section 18.1). + +**Rationale, sources and differences.** A requirement's first paragraph is the statement. +Anything after it explains why, records where the behaviour comes from, or says how it +differs from a source (`Difference from ...`). A source is cited either on a line of its +own, after `Source:` or `Sources:`, or inside the sentence it belongs to where the +citation is part of the statement. Those +paragraphs are not separate requirements, and an implementation cannot satisfy a +requirement by following its rationale rather than its statement. + +**Identifiers.** `SI-nnn` identifiers are stable. A letter suffix, as in `SI-103b`, is a +further rule of the requirement it follows and is numbered that way so that a number +already cited elsewhere keeps its meaning. A retired identifier is not reused; SI-151 is +the only one. + +**Status.** Every requirement has one of four statuses, and a requirement that is not in +force carries its status in its heading, as in `SI-054 (deliberately unsupported)`. *In +force* is the default and is not written out. *Deliberately unsupported* means the drive +refuses the command on purpose; the requirement states what it answers instead, and +section 18.1 indexes all of them. *Out of scope* means the drive does not have the +capability the requirement describes; section 19 indexes those. *Retired* applies to +SI-151 alone, whose number is not reused. + +**Typography.** `code` marks a command, an identifier, a file name or a path. A byte is +`$hh`, an answer on the error channel is `NN,TEXT` as the C64 reads it, and a character +the C64 sends as a number is `CHR$(n)`. A citation is the register code of section 1.1 +followed by the place in that source, as in `HD 9-15`, `SD file_open()` or `SDM +d64_set_attrib()`. + +### 1.5 Conformance and traceability + +An implementation conforms when, for every requirement that is in force, the tests that +name it pass, and each of those tests fails when the behaviour the requirement states is +reverted. The second half is what makes the first half worth anything, and it is the rule +every change to this drive is held to. + +The tests name the requirement they check: a `Suite11` case is called after it, a parser +case carries it in a comment, and a hardware check puts it in the label a run prints. +Appendix E lists the mapping, which `tools/softiec_traceability.py` generates from the +test sources, so a requirement that no test names shows up there rather than being +believed. Section 17 says which layer a requirement belongs in and why. + +**Changing a requirement.** A change to what the drive does is a change to the statement +here, to the tests that name it, and to the firmware, in one piece of work. A statement +that no longer matches the firmware is a defect in this document, not a description of an +exception. Where a change makes the drive answer differently from one of its sources, the +requirement says which source and why, and section 18.1 indexes it. Nothing is settled by +a note that behaviour drifted. + +--- + +### 1.6 Terminology + +These terms are used throughout with one meaning each. Where a requirement defines the +term, it is named. + +| Term | Meaning | +| --- | --- | +| drive | The Software IEC drive: one device on the serial bus, with one device number (SI-001), serving files from the Ultimate's file systems rather than from a disk of its own. | +| host file system | The file system the Ultimate itself uses, FAT on a card, a stick or the internal flash, reached through the Ultimate's virtual file system. | +| medium | Whatever a directory ultimately sits on: a host file system, or a CBM disk image mounted as a directory (SI-003). A requirement says "medium" where the answer is the same for both. | +| image | A `.d64`, `.d71`, `.d81` or `.dnp` file holding a Commodore disk, which the Ultimate mounts as a directory so that a partition or a directory can sit inside it (SI-003). | +| partition | One of the drive's numbered areas, 1 to 255, each with a name, a root and its own current directory (SI-002). Partition 0 names the current partition and cannot be entered. | +| current directory | The directory a partition is in, which every command that takes no path acts on, and which survives a warm reset (SI-103). | +| entry | One item a directory holds, whether a file or a directory, as a listing shows it. | +| CBM name | The name a C64 program uses, up to 16 bytes of PETSCII, which may hold bytes a host file system cannot (section 14). | +| host name | The name the same entry has on the host file system, produced from the CBM name by the mapping of SI-140 to SI-148. | +| channel | One of the 16 addresses a C64 opens on the drive. Channel 15 is the command channel; 0 to 14 are data channels, which carry a file, a listing or a direct access buffer. | +| command channel | Channel 15: it takes commands and answers the error channel status, `NN,TEXT,TT,SS` (section 4). | +| error channel | What a read of the command channel returns: the answer to the last command (section 4). | +| splat | The `*` a listing puts in front of the type of an entry whose write never closed it (SI-132). | +| lock | The flag `L` turns over, shown as `<` after the type, which stops a scratch (SI-076). | +| record | One fixed-length unit of a relative file, addressed by number with `P` (section 8). | +| buffer | The 256 bytes a direct access channel holds, opened with `#` (SI-090). | +| terminator | The `CHR$(13)` a `PRINT#` appends to a command, which is not part of the command (SI-016). | +| pattern | A name holding `*` or `?`, matched as SI-136 states. | + +--- + +## 2. The model + +### 2.1 Device, partitions, directories + +**SI-001.** The drive presents one IEC device number, configurable from 8 to 30, with +11 as the default, which is the range and default of the configuration item +(`CFG_IEC_BUS_ID` in `U software/io/iec/iec_drive.cc`). Test: +`Suite11-SI001-DeviceNumberRange`. GUG confirms that C64 OS expects storage devices in 8 to 30 and +supports five at a time. + +**SI-002.** The drive presents partitions numbered 1 to 255. Each partition has a +name, a root directory on the host virtual file system, and its own current +directory. Partition 0 is not a partition a user can enter; as a parameter it means +"the current partition". Sources: HD 9-8 and 9-10 (1 to 254 on the HD, 0 means the +current partition), FD (1 to 31), RL (1 to 31), IDE 15.3.1 ("Partition 0 is not a +valid parameter"), GUG ("CMD devices support 255 partitions, numbered from 1 to 255. +Partition 0 is a special system partition that cannot be accessed directly"). + +**SI-003.** A partition's root may be a directory on the host file system or a +mounted CBM disk image, because the Ultimate virtual file system mounts `.d64`, +`.d71`, `.d81` and `.dnp` images as directories. + +**SI-004.** The blocks free reported for any directory is the free space of the +partition, not of the directory. Source: HD 4-5, "all of the blocks within a Native +Mode partition are shared between all directories within that partition". Test: +`Suite11-SI004-BlocksFree`, where the root and a subdirectory of a native image report +the same count. + +The **Partition config file** item in **SoftIEC Drive Settings** selects an `.ipr` +file by its absolute Ultimate file-system path (up to 255 characters). An empty +value selects `/Flash/config/iec_partitions.ipr`. The path is saved with the +settings in Flash and in `.cfg` profiles. The file is loaded at firmware startup +and when a different path is applied, including through **Load Settings**; its +layout is therefore active when the user selects **Reboot C64**. A missing file +or a file with no usable partition entry leaves the active layout intact. +A configured file that does not load at startup is retried for up to ten +seconds while USB volumes mount; the standard file is not used in its place. +After that the file is read again only when a different path is applied, or +loaded by hand. The standard file is read at startup and when the path is +cleared. Manual `.ipr` loads and partition edits remain active until another +configured path is applied or the firmware starts. A manual load ends the +startup retry; partition edits made during it are replaced if the configured +file then loads. **Save Partitions** with the name +`default` writes `/Flash/config/iec_partitions.ipr`. These are Ultimate UI +operations; the IEC reset commands retain the behaviour in SI-103 and SI-103a, +and applying the path alone does not reconfigure the IEC processor (SI-103b). + +### 2.2 What the partition model must not do + +**SI-005.** The root of a partition is a real directory. Files can be created in it, +it can be listed, and its blocks free is that of the partition. GAP's principal +objection was that the drive presented its storage devices as directory entries of a +pseudo root that could hold no files. + +--- + +## 3. Command string grammar + +### 3.1 Path syntax + +**SI-010.** The grammar of a name or command argument is + +``` +[@] [partition] [path] [:] name +``` + +with `partition` a decimal number, and `path` a sequence of `/`-delimited +components. A path beginning with `//` starts at the root of the partition; a path +beginning with a single `/` starts at the current directory of the partition; a +missing path means the current directory. Every component is followed by a slash. +The final slash before a name is written, and the name is introduced by a colon. +Sources: HD 9-2 to 9-4 with the worked examples `LOAD"1/UTILITIES/COPIERS/:COPY",12`, +`LOAD"//UTILITIES/COPIERS/:COPY",12`, `LOAD"1//UTILITIES/COPIERS/:COPY",12` and +`LOAD"1//:BOOTQ",12` (HD 7-2); IDE 6.1; GUG, "The root directory is specified by two +leading front slashes. Each subdirectory is added to the path by specifying the +subdirectory name followed by a single trailing slash. The trailing slash is always +required." + +**SI-011.** In `CD`, the colon is optional when the name is preceded by a slash. +Source: HD 9-19, "It is not required that you include the colon before the +subdirectory name, as long as the subdirectory name is preceded by a slash." The HD +states it for `CD` only. An OPEN name without a colon is a plain name, as in +`SD file_open()`, and `MD` and `RD` require the colon (SI-060, SI-063). + +**SI-011a.** A name behind the colon is one component. A slash inside it is a +character of the name, not a path separator, so `CD:SUB/DEEP` looks for a name +containing a slash and answers `71,DIRECTORY ERROR` when no such directory exists. +The path part of SI-010 is the only place a slash separates components. Source: +HD 9-19, where every descent through more than one level writes the components in +the path in front of the colon. + +**SI-012.** A path component may contain wildcards, and the first match is used. +Sources: SD README under CD/MD/RD, "You can use wildcards anywhere in the path"; +IDE 6.2, "These wildcards can be used in path elements or filename too, in this case +the first filename will be matched." + +**SI-013.** The partition number may replace the drive number in any command that +accepts one, except the direct access commands. A direct access channel is bound to +the partition that was current when the channel was opened, and the partition +parameter of `B-R`, `B-W`, `U1`, `U2`, `B-A`, `B-F` and `B-E` is therefore always +written as 0. Source: HD 9-8 and 9-44; GSD "Partition Numbers in Disk Commands". +(IDE 15.5 does not state this rule: IDEDOS direct access addresses sectors by LBA and +has no partition parameter.) + +### 3.2 The left arrow + +**SI-014.** PETSCII `$5F`, the left arrow, means the parent directory when it stands +in the *name* position, that is directly after `CD[n]` or directly after a colon. It +is an ordinary character when it stands in a *path component* position, that is +between slashes. + +| Command | Required result | Source | +| --- | --- | --- | +| `CD<-` | parent directory | HD 9-19, "you can include the back arrow immediately after `CD[n]` to move backwards one directory"; `SD do_chdir()`, `name[0]=='_' && !name[1]` | +| `CD:<-` | parent directory | `SD do_chdir()`, same branch reached through `parse_path`; Greg Nacu measured this on a real CMD HD and on an IDE64 and reported it through the reporter on #877: "cd:<- doesn't go into the directory, it goes up a directory" | +| `CD/<-` | change into the child directory literally named `<-` | Greg Nacu, same measurement, "cd/<- works to go into that directory"; `SD parse_path()` treats a component between slashes with `first_match()` | +| `MD:<-` | create a directory named `<-` | Greg Nacu, same measurement | +| `RD:<-` | remove it | Greg Nacu, same measurement | + +The rule has one consequence worth stating. `CD/<-/OTHERDIR`, going up and then down +again in one command, is not a way up, because the arrow between slashes is a directory +name. The spelling for that is `CD/../OTHERDIR`: `U resolve_directory_path()` accepts `.` +and `..` as path components, and `..` is the spelling GAP singles out as "something that +none of the other devices can do". `Suite8-CD-PARENT-OTHERDIR` in +`software/test/iecdrive/testdrive.cc` covers it. + +**SI-015.** `CD/:<-` goes to the parent. The colon introduces the name, so the arrow +is in the name position and SI-014 applies unchanged. Sources: `SD do_chdir()`, which +reaches its `name[0]=='_'` branch for this spelling; HD 9-19, "The back arrow cannot +be combined with any subdirectory path information", which says the arrow is not a +path element and therefore only ever a name. The reporter wrote on #877 that this +form should enter the directory, but also that he had "no reference for `cd/:<-` +except trying in an emulator". One rule that explains both of Greg Nacu's hardware +measurements is worth more than a second rule for a spelling nothing sends: to enter +a directory named `<-` the command is `CD/<-`. See section 16, C2. + +### 3.3 The command terminator + +**SI-016.** One trailing carriage return is removed from a command before it is +parsed, and a carriage return followed by a line feed at the end is removed as a pair. +CBM DOS also truncates a command at a carriage return that is its second to last byte, +whatever follows it; this drive does not (the difference below). ROM, at `$C2B3`, +reached from the command dispatcher at `$C160`: + +``` +C2B3 A4 A3 LDY $A3 ; bytes received +C2B5 F0 14 BEQ $C2CB ; 0 bytes: keep 0 +C2B7 88 DEY +C2B8 F0 10 BEQ $C2CA ; 1 byte: keep 1 +C2BA B9 00 02 LDA $0200,Y ; last byte +C2BD C9 0D CMP #$0D +C2BF F0 0A BEQ $C2CB ; last byte is CR: length becomes len-1 +C2C1 88 DEY +C2C2 B9 00 02 LDA $0200,Y ; second to last byte +C2C5 C9 0D CMP #$0D +C2C7 F0 02 BEQ $C2CB ; second to last is CR: length becomes len-2 +C2C9 C8 INY +C2CA C8 INY +C2CB 8C 74 02 STY $0274 ; the length the parser uses +``` + +**Difference from the ROM.** The second branch drops a carriage return +second to last only when a line feed follows it, which is what BASIC's `PRINT#` to a +logical file number of 128 or more sends (C64 ROM `$AAD7`). The ROM's branch also cuts a +binary parameter of 13 short, for example the high byte of an `M-R` address or a count +of 13, and the reporter of #877 wrote that "needing an additional CR for some commands +do not need to be reproduced". A lone carriage return, which is an empty command after +the strip, answers `31`, as the ROM does at `$C175` and as sd2iec does. + +**SI-017.** The binary Change Partition command and `U0>` are exempt from SI-016, +because their parameter byte is mandatory and cannot be a terminator: `C`+shifted `P` +followed by a 13 selects partition 13, and `U0>` followed by a 13 selects device 13 +(SI-100), with or without a terminator after it. `SD parse_user()` reads the byte of +`U0>` without a length check, and the ROM reads it at `$0203` regardless of the length. + +**SI-018.** The Position command is exempt from SI-016, because its last parameter +byte is data. Source: `SD parse_position()` begins `command_length = +original_length;`, restoring the length from before the strip. + +**Difference from sd2iec.** The record number +and the offset of a relative file are read from the command as sent, so a 13 in the +offset's place is the offset, as the ROM reads it at `$E23E`. The position in a plain +file (SI-082) is read from the command without its terminator. sd2iec reads it from +the command as sent, which makes the documented BASIC form `"P"+CHR$(ch)+CHR$(lo)` +position to `lo + 13*256`, where here it positions to `lo`, which is what the form GSD +documents means. A +record number sent without an offset and without a terminator, as a machine language +caller sends it, takes both of its bytes. + +**SI-019.** Where the last parameter is optional, the terminator wins, so partition +13 has to be asked for with the terminator sent explicitly. Source: HD 9-16, +"To avoid problems with reading information from Partition 13, the G-P command +should always be sent with a trailing carriage return (CHR$(13))." + +### 3.4 Numeric parameters + +**SI-020.** The numeric parameters of the block and user commands are separated by +any run of spaces, commas or cursor-right characters, and a colon may stand between +the command word and the first parameter. Source: HD 9-5 and 9-6, which show +`PRINT#15,"U1";2;0;1;34`, `PRINT#15,"U1 2 0 1 34"` and `PRINT#15,"U1:";2;0;1;34` +as equivalent; `U parse_block_parameters()` reads them. + +### 3.5 Command length + +**SI-021.** The command channel buffer holds at least 254 bytes, and the name buffer +of a data channel holds at least 254 bytes. Sources: HD 4-6, "the input buffer of +the HD is only 254 characters long"; SD `CONFIG_COMMAND_BUFFER_SIZE`, 120 on the +small AVR boards and 254 on uIEC; GUG, "The total length of the directory path, +including all the slashes is 232 characters", which is the binding number, because a +C64 OS path plus a partition number, a colon and a 16-character name does not fit in +anything smaller. + +**SI-022.** A command longer than the buffer answers `32,SYNTAX ERROR` and is not +executed. Sources: HD B-2, error 32; `SD parse_doscommand()`, which returns +`ERROR_SYNTAX_TOOLONG` when the command fills the buffer; ROM `$C2CE`, which raises +error 32 when the command length reaches 42. + +The rule covers names as well as commands. A command of 254 bytes or +more answers `32` and is not executed. An OPEN name of 254 bytes or more answers `32` as +well and opens nothing, rather than creating or reading a file under its first bytes. + +--- + +## 4. Error codes + +### 4.1 The table + +**SI-030.** The five syntax errors are distinct, and each is raised for one condition. +From HD B-2 and 1541: + +| Code | Meaning | Raised when | +| --- | --- | --- | +| 30 | SYNTAX ERROR (general) | the command letter was recognised and its arguments were not | +| 31 | SYNTAX ERROR (unrecognized command) | the first character is not a command letter | +| 32 | SYNTAX ERROR (command string too long) | the command or the name fills the buffer (SI-022) | +| 33 | SYNTAX ERROR (illegal file name) | a wildcard, or a character a name cannot carry, where one is not accepted | +| 34 | SYNTAX ERROR (missing file name) | no name, or a colon with nothing after it | + +The drive's table of codes and strings is in `U software/io/iec/iec_drive.cc` and the +parser's constants are in `U software/io/iec/cbmdos_parser.h`, where each carries the +condition it stands for as a comment. + +An Ultimate extension is allowed where it cannot be mistaken for a documented command and +does not change the answer to one (precedence rule 5). `XPWD` (SI-066) is the only one. + +**SI-031.** An unrecognised command answers `31`. Verified in ROM at `$C160`: + +``` +C160 20 B3 C2 JSR $C2B3 ; strip the terminator first +C163 B1 A3 LDA ($A3),Y ; first byte of the command +C165 8D 75 02 STA $0275 +C168 A2 0B LDX #$0B ; twelve command letters +C16A BD 89 FE LDA $FE89,X +C16D CD 75 02 CMP $0275 +C170 F0 08 BEQ $C17A ; found: dispatch +C172 CA DEX +C173 10 F5 BPL $C16A +C175 A9 31 LDA #$31 ; not found: error 31 +C177 4C C8 C1 JMP $C1C8 +``` + +and stated in 1541 ("31: SYNTAX ERROR (invalid command). The DOS does not recognize +the command. It must begin with the first character sent.") and HD B-2. The reporter +asked for 31 on #877 on 11 September 2026, having measured `33` for a one-byte +command `CHR$(0)` and for `A`. + +Note the divergence: `SD parse_doscommand()` answers 30 here and reserves 31 for an +empty command. This specification follows HD, 1541, ROM and the reporter's stated +expectation rather than SD, and section 16 records it as C1. + +**SI-032.** Opening a name for writing has four cases, and each has a different +answer. + +| Case | Answer | Source | +| --- | --- | --- | +| wildcard, no `@` | `33` | 1541: "Pattern matching characters cannot be used in the Save command or when Opening files for the purpose of Writing new data"; `SDM file_open()`, which SDU does not do | +| `@`, the pattern matches a file of the same type | replace it, keeping the **matched** file's name rather than the pattern | ROM `$D8FC` falls through on a type match (the ROM says nothing about which name is kept); IDE 7.1; `SD file_open()` for the name rule | +| `@`, the pattern matches a file of a different type, or matches a REL file | `64,FILE TYPE MISMATCH` | ROM `$D8F5` | +| `@`, the pattern matches nothing | `64` | `SD file_open()` | + +The third row is the one that reconciles the sources, and it comes straight out of +the 1541 ROM. The save-with-replace path compares the type of the entry it found +against the type the open asked for: + +``` +D8E1 AD 00 02 LDA $0200 ; first byte of the name +D8E4 C9 40 CMP #$40 ; '@' ? +D8E6 F0 0D BEQ $D8F5 ; yes: the replace path +... +D8F5 A5 E7 LDA $E7 ; the found entry's type byte +D8F7 29 07 AND #$07 ; 0 DEL, 1 SEQ, 2 PRG, 3 USR, 4 REL +D8F9 CD 4A 02 CMP $024A ; the requested type +D8FC D0 67 BNE $D965 ; different -> error 64 +D8FE C9 04 CMP #$04 ; REL? +D900 F0 63 BEQ $D965 ; also error 64 +... +D965 A9 64 LDA #$64 +D967 4C C8 C1 JMP $C1C8 ; CMDERR +``` + +`SAVE` asks for PRG. So `SAVE"@:foo*"` answers `64` on a real drive whenever the +first entry matching `foo*` is not a PRG, which is what the reporter reported on +#877 ("real floppy return 64", 11 September 2026), and it replaces the file when it is. The same check guards the ordinary open +at `$D95C`, which is where the `64` of SI-035 comes from. + +`SDM file_open()` produces the same four answers, by a different route for the last +row; SDU gives the same three but refuses no wildcard on create: + +```c +if (ustrchr(fname, '*') || ustrchr(fname, '?') || (*fname == 160)) { + if (command_buffer[0] == '@') set_error(64); + else set_error(33); + return; +} +``` + +(`src/fileops.c` at `9087321`; commit `a76deb2` introduced the `*` and `?` tests and +the `160` test was added later.) + +**SI-033.** Scratching nothing is not an error. The answer is +`01, FILES SCRATCHED,00,00`, with the space in front of the text that every CBM drive +sends for the codes below 20, as it sends `00, OK`. Sources: HD B-1, "01 FILES SCRATCHED (not an error). +The number of files scratched will be indicated in the track variable"; +`SD parse_scratch()`, which ends unconditionally with +`set_error_ts(ERROR_SCRATCHED,count,0)`; IDE 15.2.2, which shows the count in the +track field. + +**Difference from the CMD manuals.** A scratch whose path does not +exist answers `71,DIRECTORY ERROR` with the partition number, instead of +`01, FILES SCRATCHED,00,00`, so a mistyped path is reported rather than looking like an +empty directory. sd2iec also reports the path error (`SD parse_scratch()`). + +**SI-034.** Selecting a partition that does not exist answers +`77,SELECTED PARTITION ILLEGAL`. Source: HD B-5. + +**SI-035.** Opening a file for writing when one of that name exists, without `@`, +answers `63,FILE EXISTS`. Opening for reading when none exists answers +`62,FILE NOT FOUND`. Opening an existing REL file with a non-REL type answers `64`. +Sources: HD B-3 and B-4; `SD file_open()`. Covered by Suite5 of +`software/test/iecdrive/testdrive.cc`. + +A name is one entry whatever its type, as on a CBM drive, although a host file system +keeps `NAME.SEQ` and `NAME.PRG` apart. So a write of a name that exists as another type +answers `63` without `@`, and `64` with `@`, which is the ROM's check at `$D8F5` +(SI-032) applied to a literal name as well as to a pattern; and a read of an existing +REL file under another type, `LOAD` included, answers `64`. Test: +`Suite11-SI035-TypeOfExistingName`. + +### 4.2 The error codes that are not CBM DOS errors + +**SI-036.** `69,FILESYSTEM ERROR` is an Ultimate code with no counterpart on any +other device. It must not be the answer to a condition that CBM DOS names. +`U IecDrive::set_error_fres()` maps the unmapped `FRESULT` values to it and puts the +raw `FRESULT` in the track variable. Every path that can reach a user must map to a +documented code first. The known case is SI-083. + +`78,BLOCK ACCESS DENIED` is the other Ultimate code. It answers a block command on a +partition rooted in a host directory, which has no tracks or sectors (SI-091), with the +track and sector asked for. No CBM device has a medium without sectors, so no CBM code +names the condition. sd2iec uses 78 for `BUFFER TOO SMALL`, which this drive never +answers (SI-096), and answers `20,READ ERROR` for a sector it cannot reach. The table in +`U iec_drive.cc` also holds 75 and 76, which nothing answers. + +**SI-154.** Reading the command channel clears the error it reported: a second read, with +no command between the two, answers `00, OK,00,00`. Every Commodore drive does this, and a +program that polls the status after each command relies on it, because an error left +standing would be read again as the answer to the next command. The drive clears the +status where it renders it, in `U IecCommandChannel::get_error_string()`. The answer to a +reset is the one exception a caller sees, because `UI` and the two `UJ` forms set `73` +again after the read that cleared it (SI-103). Test: `Suite11-SI154-StatusClears`. + +--- + +## 5. Partition commands + +### 5.1 Change partition + +**SI-040.** `CPn`, with the number in ASCII, and `C` followed by shifted P (`$D0`) +with the number as one binary byte, both select a partition and answer +`02,PARTITION SELECTED,,00`. Sources: HD 9-10, FD, RL, IDE 15.3.1, SD README. +TRACE shows C64 OS using the binary form 29 times in +one boot and the ASCII form once. + +### 5.2 Get partition info + +**SI-041.** `G-P` with no parameter, or with 255, answers for the current partition. +With 0 it answers for the system partition, which this drive does not have, so byte 0 +is 0, meaning "not created", and byte 2 is 0. With any other value it answers for +that partition, and again byte 0 is 0 if it does not exist. +The answer is 30 bytes followed by `CHR$(13)`, laid out as HD 9-15 and 9-16 give it: + +| Byte | Content | +| --- | --- | +| 0 | partition type: 0 not created, 1 native, 2 1541, 3 1571, 4 1581, 5 1581 CP/M, 6 print buffer, 7 foreign, 255 system | +| 1 | reserved, `CHR$(0)` | +| 2 | partition number | +| 3-18 | partition name as shown in the partition directory, padded with shifted spaces (`$A0`) as a CMD partition directory and `SD parse_getpartition()` pad it; all zero for a partition that does not exist | +| 19-21 | start address, high to low | +| 22-26 | reserved, `CHR$(0)` | +| 27-29 | size, high to low | +| 30 | `CHR$(13)` | + +Bytes 19-21 and 27-29 are counted in 512-byte blocks on the HD and the FD and in +256-byte blocks on RAMLink (RL, same page). This drive follows the HD and uses 512. The +size is the size of the image file for a partition rooted in a disk image, and the size of +the volume for one rooted in a host directory, rounded up and clamped to `0xFFFFFF`, +which is what `SD parse_getpartition()` answers with. A D64 that carries error bytes is +therefore a few blocks larger than the sectors its file system holds. Tests: +`Suite11-SI041-PartitionSize`, `Suite11-SI041-NamePadding`. + +**SI-042.** Byte 1 stays zero. The FD redefines it as a disk-information bit field +(FD, Getting Partition Information: bit 7 disk present, bit 6 formatted, bit 5 valid +CMD or CBM format, bit 4 true 1581, bits 3-0 density) and sd2iec writes `0xE2` there, +which decodes as an FD-2000 with a 1.6 MB disk inserted. This drive is not an FD and +must not claim to be one. IDE leaves the byte unused (IDE table 26). + +**SI-043.** The partition type is decided from the geometry of the file system at the +partition's root: no track and sector addressing, or 256 sectors on track 1, is native; +40 sectors is a 1581; and 21 sectors is a 1541, or a 1571 above 42 tracks. That reaches +the same mapping `SD pdir_refill()` reaches from the image type +(`(imagetype & D64_TYPE_MASK) + TYPE_NAT - 1` with `D64_TYPE_DNP == 1`, so a DNP image +lists as native). `$=P` and `G-P` read it from the same function, so they cannot +disagree. + +### 5.3 Partition directory + +**SI-044.** `LOAD"$=P[:pattern][=tp]"` lists the partitions. `tp` is one of `N`, `4`, +`7`, `8`, `C`. Sources: HD 9-14; FD and RL, which drop `C`; SD README. + +**SI-045.** The listing is a header line, one line per partition, and the BASIC end +marker. **There is no blocks free line.** Source: issue #890; GAP, "The partition +directory does not list a blocks free count"; `SD pdir_refill()`, whose last act is + +```c +buf->lastused = 1; +buf->sendeoi = 1; +memset(buf->data,0,2); +``` + +**SI-046.** The number printed before the header name is the number of partitions. +Sources: GAP, "The first number before the partition directory's header line is a +count of how many "user" partitions there are"; `SD load_directory()`, +`buf->data[HEADER_OFFSET_DRIVE] = max_part`. + +**SI-047.** The block count column of each partition line is the partition number. +Sources: GAP, "The typical block size of a directory entry is used for the partition +number"; `SD pdir_refill()`, `dent.blocksize = part + 1`. + +**SI-048.** The type column is the three-character partition type: `NAT`, `41 `, +`71 `, `81 `. Sources: issue #877; SD `filetypes[]` entries 8 to 11. + +**SI-049.** The header name is the drive's name, not a partition's. `SD` uses the +static string `SD2IEC` with id `IK`. This drive uses `ULTIMATE HD` with id `UL 64`, +which `U setup_partition_read()` holds. + +**SI-050.** A `SYSTEM` line is not emitted. `SD` emits one from `syspart_line[]` +immediately after the header, and IDE lists partition 255 as the disk label line. +This drive has no system partition, and SI-041 already answers `G-P 0` with type 0. +Recorded so the omission is deliberate rather than accidental. + +### 5.4 Other partition commands + +**SI-051.** `R-P:newname=oldname` renames a partition. Source: HD 9-14, FD, RL. The +old name is a partition's name and not a path, so the partition list is searched for it, +without regard to case; a name no partition carries answers `77,SELECTED PARTITION +ILLEGAL`. An empty name on either side answers `34` and a command with no `=` answers +`30`. The new name keeps its first sixteen characters, the length of a CMD partition +name, and is what the partition directory, `G-P` and the header of a listing of that +partition's root then show. + +The dash in the second character is what separates `R-P` and `R-H` (SI-064) from a file +rename, as `SD parse_doscommand()` separates them with +`if (command_length > 2 && command_buffer[1] == '-')`. + +The name lives as long as the drive runs. The partition list is written to an `.IPR` +file only when the menu saves it, which is equally true of a partition renamed from the +menu, so the command is as durable as the user interface it shares the list with. + +**SI-052.** `N[n]:name[,id]` formats. Its full behaviour is specified in SI-071. + +**SI-053.** `I[n][:]` initialises. On a device with no removable medium this is a +no-op that answers `00, OK` and frees the user buffers. Sources: HD 9-13, "This +function is performed automatically by the HD, but the command has been implemented +to retain compatibility"; `SD parse_initialize()`, which frees the user buffers. +`I` answers `00, OK`; `UI` answers the 73 message. + +**SI-054 (deliberately unsupported).** `V[n][:]` validates. **Deliberately unsupported**; the drive answers `31`, +which is also what `SD parse_doscommand()` answers, having no `V` in its command switch. + +On a host file system there is nothing to validate: the file system keeps its own +allocation and no program can put it out of step through this drive. Inside a mounted +CBM disk image there is something to validate, and doing it means rebuilding the block +availability map from every directory in the image, following the chain of each entry, +the side sector chain of each relative file and the record chain of each GEOS file, and +recursing into the subdirectories a native image can hold. A walk that misses one of +those chains marks live blocks free, and the damage appears later, when the next write +hands those blocks out again; nothing at the time of the command would show it. Answering +`00, OK` without rebuilding the map would tell a program that the image was checked, which +SI-030 and the position taken for `M-W` (SI-105) both refuse. + +The reporter wrote on #877 that "V not implemented, but that's ok for the time being". + +**SI-055 (out of scope).** The 1581-style sub-partition commands `/[n]:name` and +`/[n]:name,`+`CHR$(st)CHR$(ss)CHR$(sl)CHR$(sh)`+`,C` are not implemented and are out +of scope. They address 1581 emulation partitions, which this drive does not have. +They answer `31,SYNTAX ERROR`, because `/` is not a command letter and SI-030 gives that +answer for anything that is not one. Sources: HD 9-9 and 9-11; 1581 User's Guide, which +gives the same syntax. Test: `Suite11-SI055-SubPartitions`. + +--- + +## 6. Directory commands + +**SI-060.** `MD[n][path]:name` creates a directory. A colon is required; without one, +or with nothing after it, the answer is `34`. A name that begins with a shifted space +answers `34`. A name with a wildcard answers `33`, as a file to be created does (SI-032), +and so does a name that ends in a dot or a space, which a FAT host drops from the name it +creates, so that the directory could not be found again under the name it was made with +(SI-141). Sources: HD 9-17, which states the colon rule as its first guideline; +`SDM parse_mkdir()` for the shifted space, a check SDU does not make; `SD parse_error()`, +which answers 33 for the name FatFs refuses. Tests: `Suite11-SI060-MdColon`, +`Suite11-SI063-RdOnlyDirectories`. + +**SI-061.** `CD[n]{<-|[path][:]name}` changes directory, per SI-010 and SI-014. A +`CD` with nothing to change to, `CD` alone or `CD:`, leaves the directory where it is and +answers `00, OK`. `SD do_chdir()` answers 39 there; the no-op is kept because a program +that sends `CD:` means "stay here", and answering it with an error would fail that +program for no benefit. + +**SI-062.** `CD` into a file whose name has a disk image extension mounts that image +and makes its root the current directory; `CD<-` from the root of a mounted image +unmounts it. Sources: SD README, "CD is also used to mount/unmount image files"; +GSD "Mounting a Disk Image". + +**SI-063.** `RD[n]:name` removes a directory, and nothing else: a file reached by the +same name, a disk image or a host file without an extension, answers `62,FILE NOT FOUND` +and stays, as `SD parse_rmdir()` matches only directories. A colon with nothing after it +is no name and answers `34`, so the directory the drive stands in is not removed from +under it. It takes no path: a `/` anywhere in the +command answers `34`. It refuses a directory that is not empty. Sources: HD 9-19, +"This command does not allow the use of paths in order to avoid problems with +removing a subdirectory which is a parent of the directory in which you are located"; +`SD parse_rmdir()`, which rejects any `/` with `ERROR_SYNTAX_NONAME` and answers +`63,FILE EXISTS` for a directory that still has entries. Tests: `Suite11-SI063-RdNoPath`, +`Suite11-SI063-RdOnlyDirectories`. + +**SI-064.** `R-H[n][path]:newname[,id]` renames the header of a directory. The name is +at most 16 characters and the id two. Sources: HD 9-15; IDE 15.6.5; +`SDM parse_set_header(3)`. The path selects the directory and the name behind the colon +is the new header; with no path it is the current directory of the partition. The name +follows a colon, as for `N`: without one the answer is `34`, so a command whose partition +digits would otherwise become part of the name renames nothing. An empty +name answers `34`, a name with a wildcard `33`, and a path that is not there +`71,DIRECTORY ERROR`. A name longer than sixteen characters keeps its first sixteen +wherever a header shows it. A directory on a host file system is renamed, and so is refused +what `R` refuses a directory: a name ending in a dot or a space answers `33` (SI-141), and a +name another entry lists under `63` (SI-074). Setting the header to its existing name +succeeds; the directory does not collide with itself. + +**Difference from the CMD manuals.** The id is an sd2iec extension. HD 9-15 gives the +syntax as `R-H[n][path]:newname` and names three arguments, the partition, the path and +the new name, so a CMD HD changes the id only when a disk is formatted. +`SDM parse_set_header()` takes an optional id after a comma and sets it, and the sd2iec +spellings `EH`, `XH` and `D` reach it (SI-077). This drive takes the id on all four +spellings, so a program written for either device gets what it asks for, and a command +without an id leaves the id and the DOS version as they are, which is what the CMD +manuals describe. + +What a header is depends on what the directory sits in, and in each case it is what a +listing of that directory shows (SI-065). + +| Directory | Header | What `R-H` changes | +| --- | --- | --- | +| inside a CBM disk image | the disk name in the BAM of the root, or in the header block of a subdirectory | that name; the disk id and the DOS version stay as they are unless an id is given | +| a subdirectory on the host file system | the name the parent holds, which is all a host directory has | the directory's name, and the drive's current directory follows it when it is standing in or below that directory | +| the root of a partition | the partition's name | the partition's name, as `R-P` does (SI-051) | + +C64 OS reads the header for a related reason: GAP says "C64 OS in particular uses the +directory header when creating a favorite... The name of the favorite is taken from the +directory header name." + +The drive asks the file system for the label first and renames the directory only where +the file system has none, so a medium that gains a separate label later needs no change +here. GSD states that "The R-H command is not supported by sd2iec"; the CMD manuals +describe it and this drive follows them. + +**SI-065.** The header line of a directory listing carries the name of the directory +as it appears in its parent, and of the partition when the root is listed. Source: +GAP, "on SoftIEC it tries to show you the current path. This is inconsistent for the +sake of doing something clever, but it breaks the expectation... I would change this +behavior to SD2IEC's way, in the name of compatibility"; `SD fat_getdirlabel()`, +which returns the volume name for the root and otherwise walks `..` to find the entry +whose cluster is the current directory and returns that entry's name. + +**SI-066.** `XPWD` answers with the current partition and its current directory, as +`:`, in upper case and ending in a slash, and it leaves the error channel at +`00, OK`. It is an Ultimate extension, which precedence rule 5 (section 1.2) allows: no +CMD or sd2iec command has that spelling, and nothing else answers the question. The path +is the host spelling of the directory, upper cased, so a component whose CBM name holds +a byte the host escapes shows the escape (SI-141). It reports where the drive stands; +a program that wants to go back there sends the `CD` it went there with. + +--- + +## 7. File commands + +### 7.1 Open + +**SI-070.** The type and access suffixes are `,P`, `,S`, `,U`, `,L`+`CHR$(rl)` and +`,R`, `,W`, `,A`, `,M`. Secondary address 0 reads and secondary address 1 writes, +whatever access the name asks for, and both take PRG when the name gives no type; any +other secondary address reads when the name gives no access, and a write there takes SEQ +when the name gives no type. Sources: HD 9-23 to 9-31 for `,P`, `,S`, `,U`, `,L`, `,R`, +`,W` and `,A`; `SD file_open()` for `,M` (`case 'M': /* Modify */`, which HD does not +document) and for "Force mode+type for secondaries 0/1", which sets the mode +unconditionally and the type only where none was given; `U setup_file_access()` applies +it. Test: `Suite11-SI070-SecondaryForcesMode`. + +`,M` opens the file for reading. A modify reads a file that a write never closed, which +a listing marks with a splat (SI-132), and nothing here refuses to read such a file. The +two sd2iec lines differ: SDM maps modify to read for the same reason, while SDU opens the +file read and write on a FAT file system and says in its own comment that this differs +from the original hardware. This drive follows SDM here, because reading is what the +command means on a Commodore drive and because a write through `,M` would be a second +way to write a file that `,W` and `,A` already cover. Test: `Suite11-SI070-ModifyOpen`. + +**SI-071.** `N[n]:name[,id]` creates or formats a disk image, as sd2iec does, because +this drive has no formattable medium of its own. Source: SD README under `N:` and +`SD fat_format_image()`: + +* If the name ends in a known image extension and no such file exists, an image of + that format is created. `.D64` and `.D41` mean a 1541 image, `.D71` a 1571, `.D81` + a 1581, `.DNP` a native partition image. An id is required. +* For `.DNP` the id is a three digit track count and the image is + `65536 * tracks` bytes, created but not formatted. This rule, the `63` for an existing + DNP below and ids of two or three characters come from SDM (`SDM fat_format_image()`); + SDU refuses to create a DNP, answering `62`, and requires an id of exactly two + characters. +* If the name has no known image extension, `.D64` is appended, and in that case an + existing file is **not** overwritten: the answer is `63,FILE EXISTS`. +* If the file exists and the extension was given explicitly, it is formatted, except + that an existing `.DNP` is refused with `63` whether or not the extension was given + (`SDM fat_format_image()`, `if (ext == NULL || imagetype == IMG_IS_DNP)`; the README + text omits the DNP exception). +* The disk label is the name with the extension removed. It keeps sixteen characters + and the id two, as CBM DOS takes them, so a longer label or id never runs into the + separator and the DOS type the header holds behind them. + +The name buffer holds a 16 character label and a four character extension, so +`N:ABCDEFGHIJKLMNOP.D81,AB` creates a D81 image. + +**SI-071a.** When the directory `N` addresses is inside a mounted disk image, `N` formats +that image rather than creating an image inside it, which is what a program formatting +its disk asks for. The format goes through the file system that holds the image open, so +the block map and the directory that file system caches are the ones rewritten and the +image file keeps its size. A file open on the image answers `60,WRITE FILE OPEN`, because +that file would go on reading and writing blocks the format has handed back. A +subdirectory a native image carries is gone with the format, so the partition falls back +to the deepest directory that still exists. The SDU README says `N:` is ignored for a DNP +image unless the current directory is its root; this drive formats the image from any +directory in it, because the program asked for its disk to be formatted wherever it +stands. + +**SI-072.** A PRG file whose name ends in a disk image extension, or in `.CRT` or +`.TCRT`, is written to the host file system under exactly that name, with no type +extension added. A file of another type with such a name gets its type extension like any +other name. Sources: `SD should_save_raw()`, which `SD fat_open()` consults only for +`TYPE_PRG`; SD README, "PRG files that have D64, D41, D71, D81, DNP or M2I as an +extension will always be written without an x00 header and without any additional PRG +file extension." A file written raw lists under its host name with the type an unknown +extension lists as (section 14.1). Test: `Suite11-SI072-RawNames`. + +### 7.2 Scratch, rename, copy + +**SI-073.** `S[n][path]:pattern[,[n][path]:pattern...]` scratches. Each element gets +its own partition and path, and the list is as long as the command makes it (SI-150). +Directories are skipped. The answer is +`01, FILES SCRATCHED,,00` with the count in the track variable, per SI-033. +Sources: HD 9-27; `SD parse_scratch()`; IDE 15.2.2, whose examples include +`@S/STUFF/:*=OLD,*=BAK,/STUFF/BAK/:*`. Test: `Suite11-SI150-NameLists`. + +**SI-074.** `R[n][path]:newname=[[n][path]:]pattern` renames a file or a subdirectory. +When the source path and the destination path differ, the entry moves. An empty new +name answers `34`. A new name that already exists +answers `63`, unless it differs from the old name only by case and the entry stays in its +directory; an entry that moves meets the names of the directory it moves into, its own +name included. A destination path that does not exist answers `71,DIRECTORY ERROR` with +the partition number. A wildcard in the new name answers `33`, and so does a name ending +in a dot or a space for a directory, for the reason SI-060 gives. Tests: +`Suite11-SI074-RenameChecks`, `Suite11-SI074-MoveChecks`. Sources: HD 9-26, whose section is headed "Renaming Files and +Subdirectories" and which reads "Filenames and Native Mode subdirectory names may be +changed by using either the DOS RENAME or the BASIC 7.0 RENAME command", with +appendix J listing the command as "RENAME (Files and Subdirectories)"; +`SD parse_rename()`, which passes `FLAG_HIDDEN` and no type to `first_match()`, so an +entry of any type is matched, and whose `fat_rename()` renames the host entry, a +directory included; and `SD parse_rename()`'s note that "The 1541 renames the file to +'=' in this case, but I consider that a bug". + +**Difference from the CMD manuals and sd2iec.** `SD parse_rename()` answers `62,FILE +NOT FOUND` when the two paths differ and HD 9-26 requires one partition, where this +drive moves the entry, as IDE 15.2.3 documents. `Suite8-RENAME-P1-TO-P2` in +`software/test/iecdrive/testdrive.cc` asserts the move, and no program has been named +that needs the `62`. A directory cannot move inside itself, where its only entry would +be reached through the directory it names; that answers `71,DIRECTORY ERROR`, and the +check is in `FileManager::rename_impl`, so the browser's Move, FTP and REST are held to it +as well. An x00 file (SI-144) moved this way takes the host name of its new CBM name (SI-144c). A +subdirectory is renamed under its own name: `U do_rename()` resolves the source with +directories allowed, and `CreateIecName()` reports `e_folder` for one, so the +destination is built without a file type extension. See C14. +The directory half was reported on 917 as `@"MD:A` followed by `@"R:B=A` answering +`62,FILE NOT FOUND`, and the reporter's `finit` hits it when it renames `OS` through a +temporary name. + +**SI-075.** `C[n][path]:new=[[n][path]:]name[,[[n][path]:]name...]` copies, and with +more than one source appends them into the target. Path parsing restarts for every +source, and the list is as long as the command makes it (SI-150). The target takes the +file type of the first source. A relative file copies its records: the target has the +record length of the first source, written once, and each source adds its records +without its own header, whatever its layout (SI-084). Relative files mixed with other +types, or relative files of different record lengths, answer `64,FILE TYPE MISMATCH` +and leave no target. Sources: HD 9-28, which caps the +sources at five; SD README under `C:`, which has no cap; `SD parse_copy()`, whose +`savedtype` takes the type from the first source (the README does not state the type +rule), which copies a relative file through `open_rel()` record by record and refuses to +mix it with other types with `ERROR_FILE_TYPE_MISMATCH`. Tests: `Suite11-SI150-NameLists`, +`Suite11-SI075-CopyRelative`. + +**SI-076.** `L[n][path]:name` toggles the lock flag on one file or directory. A +locked file lists with `<` after its type and cannot be scratched; a locked directory +cannot be removed. Sources: HD 9-30; IDE 15.2.4; `SDM parse_lock()`, which toggles +`FLAG_RO`. The reporter raised it on #877. + +`L` finds its entry through the directory, as a +scratch does, so it locks the entry a listing shows under that name rather than the +first host file matching `NAME.???`. On a host file system the lock is the FAT read-only +attribute, which the Ultimate's FTP server and file browser then also respect; in a disk +image it is bit 6 of the file type byte. A scratch skips a locked entry, and also an +unlocked entry of the same name and type that follows a locked one in a disk image, +because deleting by name removes the first entry of that name. + +SDBUGS reports that a scratch of a locked file inside an image is carried out rather than +refused, and expects an error. This drive skips the entry and answers `01, FILES +SCRATCHED` with a count of none, which is what a 1541 answers and what SI-033 gives for a +scratch that matched nothing. An error code would tell a program that something failed +where a Commodore drive reports that nothing was scratched. + +**SI-077.** The sd2iec spellings of the attribute commands, from +`SDM parse_elock()`, `parse_eunlock()`, `parse_ehide()`, `parse_attr()`, +`parse_set_header()` and the dispatch in `parse_doscommand()`. + +**These spellings come from SDM only.** The CMD manuals document `L` (HD 9-30) and +`R-H` (HD 9-15) and no other attribute command, and none of the five functions above is +in SDU, which has no lock command at all: it reads the type byte's lock bit for a listing +and sets it from the FAT read-only attribute. `EL`, `EU`, `EH`, `A` and `XH` therefore +rest on SDM alone, as do the optional id of SI-064 and the image lock of SI-077a. What each of them does to a medium has a second source: the lock is the +type byte bit CMD documents (SI-076), and the image lock is the header's DOS version +byte, which a Commodore drive obeys by refusing to write with error 73 (1541). + +| Command | Effect | +| --- | --- | +| `EL[n][path]:name[,name...]` | set the lock on every entry each name matches | +| `EU[n][path]:name[,name...]` | clear it on every entry each name matches | +| `EH[n][path]:name`, with something other than a colon after the partition number | turn the hidden flag of one entry over | +| `EH[n]:name[,id]`, `XH[n][path]:name[,id]`, `D:name[,id]` | set a directory header, which reaches the same place as `R-H` here (SI-064); all four take the optional id | +| `A:[R][H][A]=name[,name...]` | set exactly the attributes named on every entry each name matches, and clear the others | + +The lock these set and clear is the one `L` turns over (SI-076), so a file `EL` locks is +a file `L` unlocks and a file a scratch skips. `R` in `A` is that lock, `H` is the hidden +flag of SI-134 and `A` is the archive flag, which the drive stores and nothing reads. + +Two differences from the source are deliberate. `SDM parse_elock()` and `parse_eunlock()` +skip directories and `parse_attr()` acts on the first match only; here `EL`, `EU` and `A` +act on every entry the name matches, directories included, because `L` locks a directory +(HD 9-30) and a lock that `EL` and `L` disagreed about would be two locks. `EH`, like `L`, +turns over the flag of the one entry the name finds first. A name that +matches nothing answers `62,FILE NOT FOUND`, and a medium that does not carry the +attribute, such as the hidden flag inside a CBM disk image, answers `30`. + +**SI-077a.** `EL:$` write protects the disk image the directory is in, and `EU:$` lifts +the protection. The lock is the DOS version byte, byte 2 of the header sector: `EL:$` +writes `$3C` into a D64 or D71, `$3D` into a D81 and `$3E` into a DNP, and `EU:$` writes +the format's own `$41`, `$44` or `$48` back. A header whose byte is below `$40` and not 0 +write protects the image, whoever wrote it, so an image locked elsewhere arrives locked. +While it is, every write into the image answers `26,WRITE PROTECT ON` and changes +nothing: a file open for writing, appending or replacing, a relative file, which opens for +reading and writing, a scratch, a rename, `EL` and `EU` of an entry, `N`, `R-H`, `U2`, +`B-W`, `B-A` and `B-F`. Reads are unchanged. On a host directory, which records no such +lock, `EL:$` and `EU:$` answer `30`. Sources: `SDM d64_set_attrib()` for the command and +the values, and `SDM d64_mount()`, which marks an image read only on the same test; 1541, +error 73, for a Commodore drive refusing to write a disk whose version byte is not its own, +which is why the lock travels with the image. The protection belongs to the image's file +system, so the file browser, FTP and REST obey it as well, and a drive emulation that runs +the Commodore DOS refuses to write the disk. Test: `Suite11-SI077-ImageWriteLock`. + +`XH+` and `XH-`, which turn hidden files on and off for every later listing, are one of +SDM's settings commands, which section 19 places out of scope; the filter `=H` asks +for them per listing instead. They answer `30`. + +`D` is a command letter because of `D:`, so an unrecognised argument to it answers `30` +under SI-030. That covers the sd2iec direct sector commands `DI`, `DR` and `DW` of SI-096. +`A` followed by anything other than a colon, and `A:` without an `=`, answer `31`, as +`SD parse_attr()` answers them; a lone `A` is the reporter's SI-031 case, which answers +the same. + +--- + +## 8. Relative files + +**SI-080.** `OPEN lf,dv,sa,"[[n][path]:]name,L,"+CHR$(rl)` creates or opens a +relative file. The comma before the record length byte is part of the syntax: the +1581 User's Guide gives `OPEN 2,8,2,"GRADES,L," + CHR$(100)`, and `SD file_open()` +reads the byte after the next comma. HD 9-31 renders the same form, with OCR damage +that can be read either way. `P`+`CHR$(ch)`+`CHR$(lo)`+`CHR$(hi)`[+`CHR$(of)`] positions to a +record. `ch` is the channel, which programs written to HD 9-32 send as the secondary +address plus 96. Record numbers and byte offsets are 1-based. Positioning beyond the +end answers `50,RECORD NOT PRESENT`, which is not an error when the intent is to +extend the file. Sources: HD 9-31 to 9-33; IDE 15.1.1; GSD "Positioning (seeking) +Within a File". Covered by Suite4 of `software/test/iecdrive/testdrive.cc`. + +The record length is the byte after `,L,`, whatever byte that is, a comma or a colon +included, as `SD file_open()` reads it. A record past the end of the file is not there: +positioning to it grows nothing, and reading it gives one byte of 255 and answers `50` +without moving on, so reading it again answers the same, as `SD fat_file_seek()` does. +The file grows when a record past its end is written: a last record the file ends inside +is completed, every record between it and the one written is an empty record whose first +byte is 255, as a 1541 fills them, and the record written follows. A write protected drive +(SI-102) grows nothing because it writes nothing. Tests: `Suite11-SI080-PastTheLastRecord`, +`Suite11-SI080-RecordLengthBytes`. + +A byte offset given with a record past the end is not kept, so the record written there +starts at its first byte, and an offset past the record length answers `51` whether or not +the record is there. `SD fat_file_seek()` clamps the position to the empty record it +returns, and `SD parse_position()` checks the offset before it seeks. + +**SI-081.** The channel byte of `P` is masked to its low four bits from 19 up, so both +the documented BASIC form `PRINT#15,"P"CHR$(96+ch)` and the bare byte reach the same +channel, while a byte just outside the channel range is still refused. A byte that names +no data channel, and a channel with nothing open on it, answer `70,NO CHANNEL`. Sources: +`SD parse_position()`, `find_buffer(command_buffer[1] & 0x0f)`, which masks +unconditionally and answers `ERROR_NO_CHANNEL` when it finds no buffer; the ROM masks from +19 and answers 70 at `$E207`. Test: `Suite11-SI081-PositionChannel`. + +**SI-082.** `P` also positions inside a plain file, to a 32-bit little-endian byte +offset, with the missing high bytes taken as zero. Sources: SD README under `P`; +GSD "Positioning (seeking) Within a File"; IDE 15.1.1, which documents both the +four-byte form and `F-P`. `U do_set_position()` implements it for `e_file`. A file read +to its end is still open and positions again. An offset past the end of a file open for +reading answers `00, OK` and the next read gives nothing; `SD fat_file_seek()` answers +`50` there, which this drive keeps for relative files, where the record structure makes +the difference meaningful. Test: `Suite11-SI082-PositionAfterEnd`. + +**SI-083.** `P` on a file opened for writing must be able to move beyond the current +end of the file, and a following write must extend the file. Sources: IDE 7, +"Unlike other systems it's possible to seek beyond the end of a file when writing or +modifying and create 'holes'"; the JiffyDOS MD81 sequence the reporter posted on #877 +on 11 September 2026 as a separate `SOFTIEC-TRACE` excerpt (lines #259 to #262; it is +not in TRACE, which is the boot log), which is +`OPEN "FOO.D81,P,W"`, then `P`+`CHR$(4)`+`CHR$($FF)`+`CHR$($7F)`+`CHR$($0C)` to +position to 819199, then one byte, then `CLOSE`. + +A seek on a write channel writes out what the channel holds at the old position and then +moves, without reading the file back, because the file is not open for reading. A medium +that cannot put the file there answers `72,DISK FULL`, which CBM DOS names, rather than +`69` (SI-036). + +**SI-084.** A relative file on the host file system is read in either of the two layouts +in use and in the `R00` wrapper, and written in the two byte layout. Nothing on a user's +medium changes. Reading only one layout silently misreads the other: where the second +byte of an sd2iec file happens to be zero, the record length is right and every record is +then read one byte late, which is why the discriminator below is on the file size rather +than on the record length alone. + +| | header | first record at | file size | +| --- | --- | --- | --- | +| this firmware | two bytes, record length little endian | 2 | `2 + n*r` | +| sd2iec, no wrapper | one byte, the record length | 1 | `1 + n*r` | +| either, with an x00 wrapper | 26 bytes, record length at offset 25 | 26 | `26 + n*r` | + +Sources: `U setup_file_access()` writes `uint16_t wrd = record_size` and +`U seek_record()` uses `const uint32_t c_header = 2`; `SD create_file()` sets +`buf->pvt.fat.headersize = 1` and writes that one byte, and `SD fat_file_seek()` +adds `headersize` to every position; `SD P00_RECORDLEN_OFFSET` is 25, and SD README +says "When x00 support is disabled the first byte of a REL file is assumed to be the +record length". + +**The two plain layouts are told apart by the file size, under two stated +assumptions.** Both put the record length `r` in byte 0, so `r` is known before the +layout is. This firmware's files are `2 + n*r` bytes and sd2iec's are `1 + n*r`, so +`size mod r` is `2 mod r` for one and `1 mod r` for the other. The reader must compare +against `2 mod r`, not against the constant 2: for `r = 2` the residues are 0 and 1. +The two residues coincide only when `r` divides 1, that is only at `r == 1`. HD 9-31 +gives the legal record length as 2 to 254, and for every `r` in that range the test is +exact. A second, cheaper check comes first: byte 1 is zero in this firmware's layout, +because a record length below 256 has a zero high byte, so a non-zero byte 1 settles +it immediately; a zero byte 1 settles nothing, because it may be sd2iec payload. + +The assumptions, and what breaks them: + +1. Both writers pad every record to `r` bytes, so a plain file is never left with a + partial last record. This firmware does so in `U IecChannel::write_record()` + (`memset(buffer + pointer, 0, recordSize - pointer)` then `f->write(buffer, + recordSize, ...)` at a record-aligned `recordOffset`), and sd2iec does so in + `SD fat_file_write()` (`memset(buf->data + buf->lastused + 1, 0, ...)` and + `buf->lastused = buf->recordlen + 1`). A file truncated by something else, for + example a copy tool that stopped early, has an arbitrary residue and is read as + whichever layout the residue happens to select, and no size-based rule can do + better without a wrapper. +2. `r = 1` is outside HD's legal range, but both writers accept it: `U + setup_file_access()` refuses only 0 and values of 256 and above, and + `SD file_open()` refuses only 0. For `r = 1` both residues are 0 and the size + cannot decide. The reader then takes this firmware's two byte layout, because that + is the only plain layout this firmware has ever written, and an sd2iec `r = 1` + file is read one byte late unless it carries an `R00` wrapper. This is a recorded + limitation, not a guarantee. + +An `R00` wrapper is recognised by its extension and `"C64File"` signature (SI-144) +before the size test is applied, so the wrapped layout never enters this comparison. +Empty files are covered: a fresh file is 2 bytes from this firmware and 1 byte from +sd2iec, residues `2 mod r` and 1. + +Inside a disk image the file +system presents a relative file with a two byte header whatever its size, so the one +byte test is not applied there. A relative file opened with a record length is looked up +by its CBM name first, so an existing `R00` file is opened rather than created again +beside it (SI-146). + +--- + +## 9. Direct access + +**SI-090.** `OPEN lf,dv,sa,"#"` allocates a 256-byte buffer on that channel, with the +buffer pointer at byte 1. `"##n"`, exactly three characters, asks for `n` chained +256-byte buffers with the pointer at byte 0; if the name is not exactly three characters +a standard buffer is allocated instead, and so it is for `##0` and for `##` followed by +anything that is not a digit, which ask for no chain at all. `SD open_buffer()` opens +nothing for `##0` and computes a count from any byte; a standard buffer is the answer that +leaves the program a working channel. Sources: SD README "Large buffers", which is the +source for `##n`, for the `70` answer and for the statement that a standard buffer starts +"with the read/write pointer set to byte 1"; GSD "Buffers and Large Buffers". HD 9-40 +documents only `#[bu]`, where `bu` selects a drive buffer number 0 to 29, and says +nothing about the initial pointer. + +`##1` is the standard buffer with its pointer at byte 0. A chain of more than one answers +`70,NO CHANNEL`, which is the answer SD README gives when there is not enough room: a +buffer here is 256 bytes because that is the sector size of every disk image this drive +serves, and the commands that fill a buffer from a medium, `B-R`, `B-W`, `U1` and `U2`, +each move one such sector. sd2iec has larger buffers because its direct sector commands +`DR` and `DW` move 512 bytes, and those are out of scope (SI-096). Answering `70` tells a +program that asked for eight buffers that it did not get them, where handing it one would +not. + +**SI-091.** The parameter forms are, from HD 9-43 to 9-46 and Appendix J: + +| Command | Parameters | +| --- | --- | +| `B-A`, `B-F` | partition, track, sector | +| `B-R`, `B-W`, `B-E`, `U1`, `U2` | channel, partition, track, sector | +| `B-P` | channel, position | + +The long spellings the 1541 manual prints, `BLOCK-READ`, `BLOCK-WRITE`, `BLOCK-ALLOCATE`, +`BLOCK-FREE`, `BUFFER-POINTER` and `BLOCK-EXECUTE`, are the same commands: the letter after +the dash names the command, as the 1541 ROM and `SD parse_block()` read it. On a partition +rooted in a host directory, which has no tracks or sectors, `B-R`, `B-W`, `U1`, `U2`, +`B-A` and `B-F` answer `78,BLOCK ACCESS DENIED` with the track and sector asked for +(section 4.2). A partition rooted in a disk image serves them. + +**SI-091a.** `B-A` of a block that is already allocated answers `65,NO BLOCK` with the +next higher free track and sector, or track 0 when no higher block is free, which is the +answer the 1541-II User's Guide gives for error 65 and HD 9-43 describes; a caller reads +that pair and asks again. `B-F` of a block that is already free answers OK and changes +nothing, because neither manual lists an error for it. sd2iec implements neither command. + + +**SI-092.** `B-P` takes an optional third parameter, the high byte of a 16-bit buffer +position. Source: SD README, "The B-P command supports a third parameter that holds the +high byte of the buffer position, For example, 'B-P 9 4 1' positions to byte 260"; GSD +"The Buffer Pointer". With two parameters the position is the 1541's eight bit one, which +keeps the low byte of what it is given, so `B-P:2,300` positions to byte 44. With three, +the position is sixteen bits, and one past the end of a 256 byte buffer (SI-090) names no +byte the drive can give out and answers `30`. So does `P` on a buffer channel whose +32-bit position (SI-082) is past that end, and the pointer stays where it was. Test: +`Suite11-SI090-BufferPointer`. + +**SI-093.** The partition parameter of a direct access command is ignored; the +channel uses the partition that was current when it was opened. Source: HD 9-8 and +9-44, "The partition number should always be 0 (zero). This is because direct access +commands will always access the partition that was the current partition at the time +the direct access channel was opened"; GSD says the same. + +**SI-094.** `B-R` and `B-W` differ from `U1` and `U2`: they use the first byte of the +block as a length. Sources: HD 9-44 and 9-45; `SD parse_block()`, which sets +`buf->position = 1; buf->lastused = buf->data[0];` for `B-R` and writes +`buf->data[0] = buf->position-1` for `B-W`. + +**SI-095.** `B-E` is not implemented and will not be: it executes 6502 code in drive +memory, which this drive does not have. It answers `30`, because `B` is a recognised +command letter and only the sub-command is not (SI-030). + +**SI-096 (out of scope).** The sd2iec direct sector commands `DI`, `DR` and `DW`, and the error +`78,BUFFER TOO SMALL`, are out of scope. They expose the raw storage device below the +file system, which is not something this firmware should offer over IEC. They answer +`30,SYNTAX ERROR`: `D` is a command letter here, for the header command of SI-077, and +anything after it that is not a colon is refused. Source: SD README under `D`. Tests: +`DI`, `DR` and `DW` in `target/pc/linux/parse`. + +--- + +## 10. Device commands + +**SI-100.** `U0>`+`CHR$(d)` changes the device number, for `d` in 8 to 30. Sources: +HD 9-49; IDE 15.4.1; `SD parse_user()`, which accepts 4 to 30 and recognises the `>` +by `(command_buffer[2] & 0x1f) == 0x1e`. GAP lists this as a gap: "Changing the +device address with u0> command. This is supported on all devices going back to +ancient times, before the 1541. This produces a syntax error in SoftIEC." + +The number is written into the IEC processor's +device number slot without holding the processor in reset, because the command is still +on the bus, and it is not written to the configuration. The number byte is mandatory, so +a 13 in its place is device 13 with or without a terminator after it (SI-017). Tests: +`Suite11-SI100-DeviceNumber`, `Suite11-SI103b-SettingAfterU0`. + +**SI-100a.** `M-W`+`CHR$(119)`+`CHR$(0)`+`CHR$(n)`+data, a memory write to `$0077` with +`n` at least 1, changes the device number to the low five bits of the first data byte, +for a number in 8 to 30, as `U0>` does (SI-100). The number is not written to the +settings. A number outside 8 to 30 answers `30` and leaves the device number unchanged. + +A 1541 listens on the address in `$0077` and talks on the address in `$0078`. Its reset +stores `$48` plus the device jumpers in `$78` and that value EOR `$60` in `$77` (ROM +`$EB45` and `$EB49`), and its ATN handler compares a command byte with `$78` at `$E89B` +and with `$77` at `$E8A9`. Writing both cells is therefore the software way to change a +1541's device number, and it is what the SWAP button of a CMD drive sends to the drive +whose number it takes. The CMD FD asserts ATN itself and sends that drive LISTEN, +secondary address `$6F`, and then `M-W` `$77 $00 $02` followed by the FD's own listen +address and talk address, the last byte with EOI, and UNLISTEN (FDROM `$A57B` to +`$A5A6`, with the command bytes in a table at `$A5A8`). The swap back sends the same +command to the swapped number with the other drive's original addresses. HD 3-1 +describes the SWAP buttons exchanging the HD's number with a 1541 at device 8. Issue +[#933](https://github.com/GideonZ/1541ultimate/issues/933) asks for Software IEC to take +part in that exchange. Sources: ROM as above; FDROM; `SD handle_memwrite()`, which +treats address 119 as "Change device address, 1541 style" and takes +`command_buffer[6] & 0x1f`. + +Difference from the 1541 and sd2iec. The talk address in the second byte is not read: +the drive has one number, and the listen address gives it. A 1541 stores each byte where +it is written, so a write of `$0077` alone leaves it talking on its old number, where +here the whole drive moves. A number outside 8 to 30 answers `30`, the range of SI-100, +where `SD handle_memwrite()` takes any value. A write to `$0078` alone is an `M-W` like +any other and answers `30` (SI-105). Tests: `Suite11-SI100a-MemoryWriteDeviceNumber`, +which sends the FD's bytes on channel 15 without an OPEN, and `iec-dos-commands`, which +sends them over the bus from the C64 and addresses the drive on its new number. + +**SI-101.** `S-8`, `S-9` and `S-D` are the typed aliases for swapping to device 8, +device 9 and back to the configured default. Sources: HD 9-34; IDE 15.4.1. On this drive +there is one drive behind the number, so `S-8` and `S-9` set the device number to 8 and +to 9 and `S-D` returns it to the one the settings hold. The number is not written to the +settings, as `U0>` does not write it (SI-100). + +The command is exactly three characters with a dash in the second, which is how +`SD parse_doscommand()` tells it from a scratch: `S:-8` scratches a file named `-8` and +`S-88` scratches one named `-88`. A third character that is none of `8`, `9` and `D` +answers `30`, because `S` is a command letter and its argument is not (SI-030); that +covers `S-C`, the SCSI pass-through of SI-106. sd2iec answers the whole group `31`, +recognising the form without implementing the swap. + +**SI-102.** `W-1` sets a software write protect for the whole drive and `W-0` clears +it. Sources: HD 9-35; IDE 15.4.10. While it is set, everything that would change a +medium answers `26,WRITE PROTECT ON` and changes nothing, and everything that only reads +works as it does otherwise. The command is exactly three characters, and `W` is a command +letter only for those two, so any other `W` answers `30`. The protection lasts as long as +the drive runs and is not written to the settings, as the device number of `U0>` is not +(SI-100). + +**SI-102a.** The gates the protection is enforced at, which together are every path from +the bus to a medium. + +| Gate | Commands that reach it | +| --- | --- | +| the twelve command handlers that change a medium | `MD`, `RD`, `C`, `N`, `R`, `S`, `R-H`, `R-P`, `L`, `EL`, `EU`, `EH`, `A`, `U2`, `B-W`, `B-A`, `B-F` | +| the file open | a write, an append and a replace, which answer `26` and open nothing | +| the sequential write | a channel opened for writing before `W-1` takes no more bytes, writes nothing more when it closes or is positioned with `P`, and answers `26` | +| the relative file | it opens for reading, and the record write answers `26`, drops the record and leaves the channel open, because the file can still be read | +| the record seek | a record past the end of the file is not created; the answer is `50,RECORD NOT PRESENT` | + +`Suite11-SI102-WriteProtect` sends one command through each gate and then checks that +the medium is unchanged and that reads still work, so a gate left out fails a test rather +than leaving a hole. + +**SI-103.** The three resets are distinct. + +| Command | Effect | Answer | +| --- | --- | --- | +| `UI` | nothing | `73,,00,00` | +| `UI+`, `UI-` | select the serial timing | `00, OK` | +| `UJ` | close every open data channel; keep the current partition, every partition's current directory, and any mounted image | `73,...` | +| `U`+shifted J, `CHR$(202)` | close every open data channel, return every partition to its root, select the default partition | `73,...` | + +None of the three clears the write protect of `W-1` (SI-102) or returns the device number +`U0>`, `S-8` or `S-9` set (SI-100, SI-101): both last as long as the drive runs, and a +reset over the bus is not the drive stopping. `U`+shifted J on sd2iec is +`system_reset()`, which restarts the device and so loses both; here the drive's own Reset +returns the device number and keeps the write protect (SI-103b). Sources: HD 9-51; SD README under `UI/UJ` and `U`; GSD +"Warm, Cold and Hard Reset". + +**SI-103a. None of the three reconfigures the IEC interface.** A reset answers the +transaction it arrived in and performs the state reset once the command channel has been +unlistened, and it never calls `IecInterface::configure()`: nothing about the bus +configuration changes, because the device number, the enable flag and the slot assignment +are the same after a drive reset as before it. + +The reason is that `IecInterface::configure()` opens with + +```cpp +HW_IEC_RESET_ENABLE = 0; +``` + +which holds the IEC processor in reset while it rewrites the device-number slots. Command +handlers run on the "IEC Server" task, inside the bus state machine loop in +`IecInterface::task()`, while the host still has the command channel addressed, so a +reset of the IEC processor from there drops the drive off the bus in the middle of a +handshake and leaves the host waiting on a handshake that never completes. That is the +symptom GAP reports against firmware 3.10a: "cold reset and hard reset 'uj' and 'uJ' seem +to lock up the bus. Needs a STOP+RESTORE to recover". `IecDrive::reset()` is the menu's +reset, which does reconfigure, and a command handler must not reuse it. + +**SI-103b.** A change in the Software IEC settings reconfigures the IEC processor only +when the device number or the enable flag changes. Holding the processor in reset drops a +transfer on the bus, so turning a setting such as **Log Every Operation** on or off must +not do it, and neither must a setting change after `U0>` moved the drive, which leaves it on +the number `U0>` gave. The drive's **Reset**, from the menu or from +`PUT /v1/drives/softiec:reset`, is meant to drop whatever is on the bus: it restarts the +processor in any case and puts the drive back on the device number the settings hold; the +write protect of `W-1` stays. Tests: `Suite11-ResetRestartsProcessor`, +`Suite11-OperationLogNoReconfigure`, `Suite11-SI103b-SettingAfterU0`. + +**SI-104.** `U3` to `U8` and `UC` to `UH` jump into drive memory and are not +implemented; they answer `30`, for the same reason as SI-095. Source: HD 9-51. + +**SI-105 (deliberately unsupported).** The memory commands are implemented as follows. + +* `M-R`+`CHR$(lo)`+`CHR$(hi)`[+`CHR$(n)`] returns `n` bytes over the error channel, + with `n` absent meaning 1 and `n` zero meaning 256. It does not read past a page + boundary. Sources: HD 9-46 and 9-47 for the syntax, zero meaning 256 and the page + boundary; ROM `$CB24` (`LDA $0274 / CMP #$06 / BCC`, one byte when the command is + shorter than six bytes) and `SD handle_memread()` ("Read 1 Byte if no explicit + length was provided") for the absent count. HD does not describe the absent case. +* `M-W`+`CHR$(lo)`+`CHR$(hi)`+`CHR$(n)`+data answers `30` and keeps nothing; the reason + is below. The exception is a write to `$0077`, which changes the device number + (SI-100a). Source for the syntax: HD 9-47. +* `M-E`+`CHR$(lo)`+`CHR$(hi)` answers `98,UNKNOWN DRIVE CODE` and runs nothing; the reason + is below. Source for the syntax: HD 9-48. + +A reply of `M-R` belongs to the command that asked for it: the next command replaces it, +whether or not the reply was read, as it replaces a status (SI-154). Test: +`Suite11-SI105-UnreadReply`. + +What `M-R` returns is specified in section 11. The reporter's position on #877 is +that the count matters more than the content: "M-R should return the number of +queried bytes. I agree we have nothing good to return but we can return each byte to +be 42... That way, a software that does M-R to identify devices is syntactically +happy." C64 OS sends the four probes at every boot (TRACE). + +**`M-W` and `M-E` are deliberately unsupported.** Nothing of what `M-W` writes is kept +and `M-E` runs nothing, so answering `00, OK` would tell a fast loader that its drive +code is in place and running. An `00, OK` means the work was done, which is also why a +clock write of a date that does not exist answers `30` (SI-122). The reporter's request +was for `M-R`, which C64 OS sends four times at boot (TRACE). + +`M-W` answers `30`: the command is recognised and its bytes are not taken. A write to +`$0077` is not drive code: it asks for a change this drive can make, so it makes it and +answers `00, OK` (SI-100a). `M-E` answers +`98,UNKNOWN DRIVE CODE`, which says what is true here and is the answer sd2iec gives when +the code it was sent matches no fast loader it implements: `SD run_loader()` sets +`ERROR_UNKNOWN_DRIVECODE`, code 98, when it reaches the end of its handler table. No +drive code is ever known here, so every `M-E` answers it. A program that meets this code +on an sd2iec meets it here for the same reason. `98` is not a CBM DOS code, and no CMD +device answers it; a program that treats any non-zero code as a refusal is unaffected. + +**SI-106 (out of scope).** `S-C`, the SCSI pass-through of HD 9-39, is out of scope. + +**SI-107.** The setting "IEC Drive" in "SoftIEC Drive Settings" has three values, which +decide the bus and the UCI side of the drive separately: + +| Value | On the serial bus | UCI target (target 5) | `$DF1B`, the number a UCI KERNAL sends there | +| --- | --- | --- | --- | +| Enabled | answers | answers | the device number | +| UCI Only | does not answer | answers | the device number | +| Disabled | does not answer | answers every command with status `05`, module not loaded | 31 | + +UCI Only keeps a KERNAL or program that reaches the drive through the Command Interface +working while a hardware fast loader has the bus to itself, and it shows whether a program +uses UCI and not the bus. With Disabled, a UCI KERNAL finds no device of its own, sends +every device to the bus, and meets `DEVICE NOT PRESENT` on the drive's number. `$DF1B` +holds five bits, and 31 is no device a program opens. UCI Only is the first value and the +default. The task menu's Turn On sets Enabled, and Turn Off sets UCI Only. Source: issue +[#918](https://github.com/GideonZ/1541ultimate/issues/918), where the three values were +proposed and agreed. Tests: `Suite11-SI107-SettingModes`, and `uci-targets`, which reads +`$DF1B`, the drive list and the target's answer for each value. + +--- + +## 11. Device identification + +This section exists because it is the one place where copying another device exactly +would be wrong. + +**SI-110.** The `UI` message is the primary identification and must name this device. +Source: SD README, "If you are the author of a program that needs to detect sd2iec +for some reason, DO NOT use M-R for this purpose. Use the UI command instead and +check the message you get for 'sd2iec' and 'uiec' instead"; GSD "Device Detection". The +message is `73,U64HD ULTIMATE DOS V2.0,00,00`, whose fixed form SI-114 gives. + +**SI-111.** While the drive answers `M-R` out of itself, as SI-112 has it, `M-R` must not +return the signature of a 1541, a 1571, a 1581 or a CMD device, because a program that +reads one of those will then drive this device as that model, and none of those models' +drive code runs here. The rule is about that mismatch, not about the signatures +themselves: a drive that served a real ROM image and behaved as that model, which is what +GEOS and Wheels need and what SI-115 places out of scope, would answer the signature on +purpose. Adding such a mode replaces this requirement rather than breaking it. The +signatures are, read out of the ROM images in this repository: + +| Address | 1541 | 1571 | 1581 | CMD | +| --- | --- | --- | --- | --- | +| `$FEA4` | `CA CC` | `CA CC` | `FF FF` | `"HD"`, the fifth and sixth bytes of `"CMD HD"` at `$FEA0` | +| `$E5C5` | `35 34` = `"54"` | `35 37` = `"57"` | `FF FF` | | +| `$A6E8` | outside the ROM | `48 C9` | `35 38` = `"58"` | | + +The two bytes at `$E5C5` and `$A6E8` are the model digits inside the drive's power-up +message. The CMD signature is documented by its own manual: HD 9-47 gives the +detection example `PRINT#15,"M-R"CHR$(160)CHR$(254)CHR$(6)` followed by +`IF A$="CMD HD"`, that is six bytes from `$FEA0`. + +TRACE shows C64 OS reading exactly `$FEA4`, `$E5C5`, `$A6E8` and `$0002`, two bytes +each, before falling back to `UI`. The probe strings are literal bytes inside +`OS/LIBRARY/IEC.LIB.R`. + +**SI-112.** `M-R` returns the requested number of bytes, up to the end of the page +(SI-105), every byte `$00`, at every address. There is no address table and no exception. + +Three things follow from that choice and each is a reason for it. + +* The byte count is what makes a probe well formed. A device that answers a syntax + error to `M-R` is not merely unidentifiable, it is broken from the caller's point + of view, which is what TRACE shows happening to C64 OS. The reporter's + position on #877 was the same, and he proposed 42; the count is the part both + positions agree on. +* `$00` matches none of the model signatures in SI-111, so no caller can conclude + 1541, 1571, 1581 or CMD. +* `$00` is the one value sd2iec deliberately returns for a detection address: + `{ 0xfffe, { 0x00, 0x00 }, 0xff }` in `SD drive_magics`, commented "Disable AR6 + fastloader". Returning it everywhere gives every fastloader that probes the same + answer that makes Action Replay 6 fall back to the KERNAL loader. + +**SI-113.** This drive does **not** implement sd2iec's `drive_magics` table, which +returns bytes chosen to put DreamLoad, ULoad Model 3 and Krill's loader into 1541 or +1571 mode. Those values are correct for sd2iec because sd2iec reimplements those +loaders. This drive implements none of them, so a loader that concluded "1541" from a +faked byte would go on to upload drive code with `M-W` and call it with `M-E`, and +then wait for a response that is never coming. Answering `$00` makes the same loader +fall back to the standard serial protocol, which works. + +**SI-114.** Identification of this drive is the `UI` string, and its format is fixed +here so that software can rely on it: `73,U64HD ULTIMATE DOS V2.0,00,00`. The +leading token is the device family and the trailing token is the DOS version. A +future revision may raise the version; it may not change the family token, and it may +not introduce a memory signature at `$FEA0` or anywhere else. Software that needs to +recognise this drive matches on the string, which is also what SD README tells +authors to do for sd2iec: "DO NOT use M-R for this purpose. Use the UI command +instead." That C64 OS already copes with this is not an assumption: the boot in TRACE +falls through all four `M-R` probes to `UI` and succeeds. + +**SI-115 (out of scope).** The sd2iec `XR` mechanism, which serves a real drive ROM image from a file +for `M-R` so that GEOS and Wheels can identify a drive, is out of scope. Sources: +SD README under `XR` and under GEOS and Wheels; GAP does not ask for it. The +reporter asked on #877 that the documentation state plainly that there is no GEOS and +no Wheels support, which belongs in `GideonZ/1541u-documentation` rather than here. + +Out of scope means this document does not require the mechanism and no test holds the +drive to it. It does not mean it cannot be added; SI-111 says which requirement such a +mode would replace. + +--- + +## 12. Real time clock + +**SI-120.** `T-RA`, `T-RB`, `T-RD` and `T-RI` read the clock and `T-WA`, `T-WB`, +`T-WD` and `T-WI` set it. The `A` format is +`"dow. mo/da/yr hr:mi:se xM"+CHR$(13)` with the day of week four characters followed +by a space, from `SUN.`, `MON.`, `TUES`, `WED.`, `THUR`, `FRI.`, `SAT.`. The `B` and +`D` formats are nine bytes: day of week, year, month, day, hour in 12-hour form, +minute, second, an AM or PM flag, and `CHR$(13)`, BCD-coded for `B`. The year byte of +`D` counts from 1900, so 2026 is 126, as `SD parse_timeread()` writes it; a write takes a +two-digit year as well, by the rule of SI-121. The `I` format +is the ISO 8601 subset `"YYYY-MM-DDThh:mm:ss dow"+CHR$(13)`. Sources: HD 9-36 to +9-38; IDE 15.4.8; SD README under `T-R and T-W`; GSD "Realtime Clock". + +The clock the drive answers with is its own, and a write changes nothing else. The drive +keeps the difference between the moment written and the system clock, in seconds, and a +read answers the system clock plus that difference, so the drive's clock runs on with the +system clock. The system clock is the Ultimate's real time clock, which the firmware sets +from the network by SNTP while the network setting "SNTP Enable" is on, as it is by +default (`software/network/sntp_time.cc`), in the time zone the network settings name. +The file browser, FTP, REST and the time stamps the file system writes keep reading the +system clock. A reset of the drive clears the difference: the Reset from the menu or the +drives route, `UJ` and `U`+shifted J. Until a write, and after a reset, a read answers the +system clock as it reads, its day of week included. A write that is refused answers +`30,SYNTAX ERROR` and keeps the difference as it was. + +**SI-121.** Each write form carries the fields of the matching read form, at the same +offsets. + +| Form | After `T-Wx` | Shortest accepted | +| --- | --- | --- | +| `A` | `dow. mo/da/yr hr:mi:se xM`, the day of week matched on its first two characters, the space and the marker optional | 26 bytes | +| `B` | day of week, year, month, day, hour in 12-hour form, minute, second, PM flag, all BCD | 12 bytes | +| `D` | the same eight fields in binary | 12 bytes | +| `I` | `YYYY-MM-DDThh:mm:ss`, with the day of week a `T-RI` answer ends in accepted and ignored | 23 bytes | + +Source: `SD parse_timewrite()`, which is also the source for the rules below. + +* The day of week of the `A`, `B` and `D` forms is checked for its range and not kept: + a read after a write derives it from the date, because the drive keeps only a + difference in seconds. A CMD drive stores the day of week it is sent without checking + it against the date, so a program that sends one the date does not have reads back a + different one here. The `I` form carries none. +* A twelve in a 12-hour hour field is midnight or noon, and the PM flag adds half a day. + The `A` form without its marker is a 24-hour time. +* A two-digit year below 80 is in this century and from 80 in the last one. +* A `CHR$(13)` inside the binary fields of `B` and `D` is data. Only a terminator after + the last field of a form is dropped (SI-016). + +**SI-122.** A write is refused with `30` when a field is out of range: a month outside 1 +to 12, a day outside the length of that month in that year, a day of week above 6, an +hour above 23, a minute or a second above 59, a BCD field whose nibbles are not digits, +or a year outside 1980 to 2079, which is what two BCD digits counted from the epoch hold. +`SD parse_timewrite()` checks the same ranges apart from the length of the month; that +check is added here because a 31 February would otherwise be read back as a different +date. + +**SI-123.** Every field sits at a fixed offset and every separator is checked. A field +written to another width is refused, where `SD parse_timewrite()` reads a number of any +width and then skips one character. The `A` form's AM or PM marker is at a fixed offset +in that source as well, so a command whose earlier fields are of another width cannot be +read consistently in any case. A command is exactly as long as its form: the `A` form is +26 bytes without the marker and 29 with a space, `A` or `P`, and `M`; the `I` form is 23 +bytes, or 27 with a space and the day of week a `T-RI` answer ends in. Anything else, +a marker that is not `AM` or `PM` included, answers `30`. `SD parse_timewrite()` ignores a +marker it does not recognise, which here would leave the clock twelve hours wrong for a +`PM` typed shifted. Test: `test_clock_commands` in `target/pc/linux/parse`. + +--- + +## 13. Directory listings + +### 13.1 Layout + +**SI-130.** A listing is a BASIC program: a two-byte load address `$0401`, then per +line a two-byte link pointer, a two-byte line number carrying the block count, the +text, and a zero; the program ends with two zero bytes. Source: `SD dirheader[]`, +`{1, 4, /* BASIC start address */ 1, 1, /* next line pointer */ 0, 0, ...}`. + +This is invisible to `LOAD"$",dv`, which is a relocating load, and to `LIST`, which +uses the link only as an end marker, and to a program that reads `$` as a file and +skips two bytes. It is wrong for `LOAD"$",dv,1`, an absolute load, which would place +the listing at `$0101`. + +**SI-131.** Byte 4 of the header, the low byte of the header line's BASIC line +number, is the partition number for a file listing and the number of partitions for a +partition listing. See SI-046. + +**SI-132.** The file type field is followed by `<` when the entry is locked, then by `H` +when it carries the hidden attribute, and it is preceded by `*` when the entry was not +closed. A line for a hidden entry reads `PRG