Information wants to be free...

Gould 1604 Oscilloscope Repair

I have gotten hold of a Gould DRO 1604 oscilloscope from 1989. It would power on, but the display was severely distorted and looked like this:

Gould 1604 Before


I cracked open the case and first of all removed a leaking battery, which is not related to the display problem, but important to fix as soon as possible:

Gould 1604 Battery


Luckily there is a service manual available for this particular oscilloscope, which helps a lot in giving troubleshooting tips and places to measure. I first discovered that pin 4 of U803 (the Y DAC chip) had -3.3V but the service manual said it should be either -2.8V or -4.2V, depending on the "dot joining" state. This led me to Q811 (a MOSFET controlling the "dot join") which had a strange voltage of -3.41V on it's gate, where it should have been either 0V or -5V. According to the circuit diagram the gate of Q811 is pulled by a resistor connected to the -12V power rail.

I measured the -12V rail, and this was only around -11V which is too low. This rail is controlled by a LM377T linear regulator, which is adjusted by a set of resistors and capacitors. I checked the three associated resistors R1, R2 and R16 and they all had the correct values. However, the two capacitors C15 and C16 had correct capacitance but horrible ESR value of 23 and 33 ohms.

Here are the two bad capacitors, with blue casing:

Gould 1604 Old Capacitors


Which i promptly replaced with new ones:

Gould 1604 New Capacitors


This fixed the -12V power rail, which now measures around actual -12 volts, and the display is now working:

Gould 1604 After


Topic: Repair, by Kjetil @ 04/12-2020, Article Link

Toshiba Satellite Pro 410CDT Tweaks

I got hold of an old Toshiba Satellite Pro 410CDT laptop with a Pentium 90MHz processor, which I have cleaned up and refurbished. Since I already got tons of Linux boxes I figured to use this a "DOS Gaming Laptop" instead. It has a Sound Blaster compatible ESS688 sound chipset and a Adlib compatible FM synthesizer, making this perfect for that use.

Important notice! The internal batteries in this had already started to shown signs of leakage, the typical turquoise spots:

Toshiba 410CDT Batteries

I immediately removed the batteries and cleaned up the spots with vinegar. It will now complain about lost CMOS settings every time, but I can live with that for now.

Another challenge is that this laptop has no floppy drive, since that is swappable with a CD-ROM drive that I (only) got instead. To be able to install DOS I used QEMU to install it on a virtual drive, then removed the original hard drive from the laptop and DD'd over the virtual drive to it.

I knew the hard drive was 815394816 bytes, meaning 1592568 512-byte sectors, so a virtual drive can be made like this:

dd if=/dev/zero of=Toshiba_DOS.dd bs=512 count=1592568
          


QEMU is launched like this:

qemu-system-i386 -drive format=raw,file=Toshiba.dd -cpu pentium -m 32 -monitor stdio -fda DOS_Floppy_1.dd
          


One can then use the QEMU monitor to change and eject virtual floppies like so:

change floppy0 DOS_Floppy_2.dd
change floppy0 DOS_Floppy_3.dd
eject floppy0
          


Afterwards it is also possible to loopback mount he virtual hard drive to put more stuff on there, like tools and games. Since the first partition starts at sector 63, an offset of 32256 bytes must be used:

sudo mount -o loop,offset=32256 Toshiba_DOS.dd /mnt/loop/
          


I used one of those USB-to-IDE adapter and the virtual hard drive is typically DD'd back just like this:

dd if=Toshiba_DOS.dd of=/dev/sdd bs=512 status=progress
          


Finally, for reference, here is the "AUTOEXEC.BAT" file I ended up using for the laptop:

C:\DOS\SMARTDRV.EXE /X
@ECHO OFF
PROMPT $p$g
PATH C:\DOS;C:\VI;C:\MSKERMIT;C:\PKZIP
SET TEMP=C:\DOS
MODE CON CODEPAGE PREPARE=((850) C:\DOS\EGA.CPI)
MODE CON CODEPAGE SELECT=850
LOADHIGH=C:\DOS\KEYB NO,,C:\DOS\KEYBOARD.SYS
LOADHIGH=C:\DOS\DOSKEY.COM
LOADHIGH=C:\DRIVERS\MOUSE.COM
LOADHIGH=C:\DRIVERS\MSCDEX.EXE /D:MSCD001 /L:D
C:\ESSUTIL\ESSVOL.EXE /V:8 /L:8 /W:8 /M:0 /C:8 /S:8
SET BLASTER=A220 I7 D1 T6 P330 H5
          


And the "CONFIG.SYS" file:

DEVICE=C:\DOS\HIMEM.SYS
DEVICE=C:\DOS\EMM386.EXE NOEMS
DOS=HIGH,UMB
COUNTRY=047,,C:\DOS\COUNTRY.SYS
DEVICEHIGH=C:\DOS\SETVER.EXE
DEVICEHIGH=C:\DOS\DISPLAY.SYS CON=(EGA,,1)
FILES=50
BUFFERS=10,0
DEVICEHIGH=C:\DRIVERS\OAKCDROM.SYS /D:MSCD001
          


Topic: Configuration, by Kjetil @ 15/11-2020, Article Link

Compaq Deskpro XL 5133 with Red Hat 5.2

I decided to install the classic Red Hat Linux 5.2 distribution on my classic Compaq Deskpro XL 5133 machine. The 5.2 version is one of the more well known from the late 90's, and several others have used this to experience the past. It is using the 2.0.36 version of the Linux kernel.

Before any of the SW installation could take place, the on-board battery had to be changed to be able to keep the system configuration intact. Luckily the battery is a Lithium type, so it doesn't leak, but it was soldered in place. I changed it with a CR2032 battery holder, which works fine.

CR2032 battery holder replacement


After configuring the system with the special Compaq floppy disks (there is no BIOS setup menu!) I was able to install Red Hat 5.2 using the CD-ROM without any trouble. The machine has a Matrox Millennium VGA card which works fine in X Windows and a on-board AMD PCnet32 Ethernet controller working out of the box.

The troublesome part was getting the audio to work, which is classified as "Compaq Deskpro XL Business Audio", but is in reality a "Microsoft Sound System" compatible chip of the AD1847 type:

AD1847JP SoundPort Chip


When playing any audio, it would stutter and the following error would appear:

Sound: DMA (output) timed out - IRQ/DRQ config error?
          

I tried all kinds of different IRQ and DMA settings, but to no avail. To troubleshoot further I setup a QEMU emulated environment also with Red Hat 5.2 to be able to quickly recompile the ad1848.o module device driver.

I figured out that in vanilla Linux 2.0.36 the sound drivers are not modularized, and Red Hat had actually applied a patch to modularize them. So this exact setup had to be re-recreated. The original sources can be found here as "kernel-2.0.36-0.7.src.rpm". But these still needs to be patched, where I did the following:

tar -xvzf linux-2.0.35.tar.gz
gunzip 2.0.36-pre-patch-14.gz
gunzip sound.diff.gz
patch -p0 < 2.0.36-pre-patch-14
patch -p0 < sound.diff
mv linux linux-2.0.36
patch -p0 < kernel-2.0.36-sound-new.patch
cp kernel-2.0.36-i386.config linux-2.0.36/.config
          

Yes, the original sources is actually Linux 2.0.35, but with a patch to bump it up to 2.0.36!

After enabling debugging flags, I eventually found out that this stock driver is detecting the audio chip wrongly as a "OPTi 82C930" chip, which in turn causes the IRQ status to be read from the wrong register!

Here is my own patch to fix this problem and enabling the debug:

--- ad1848.c.orig    2020-08-30 12:42:45.362175159 +0200
+++ ad1848.c    2020-08-30 12:42:52.142175232 +0200
@@ -37,6 +37,9 @@
 
 #include "soundmodule.h"
 
+#define DEBUGXL
+#define DDB
+
 #define DEB(x)
 #define DEB1(x)
 #include "sound_config.h"
@@ -1532,10 +1535,19 @@
     {
         if ((tmp1 = ad_read(devc, i)) != (tmp2 = ad_read(devc, i + 16)))
         {
-            DDB(printk("ad1848 detect step F(%d/%x/%x) - OPTi chip???\n", i, tmp1, tmp2));
-            if (!ad1847_flag)
-                optiC930 = 1;
-            break;
+            if (deskpro_xl)
+            {
+                DDB(printk("Deskpro XL, so assuming AD1847\n"));
+                ad1847_flag = 1;
+                break;
+            }
+            else
+            {
+                DDB(printk("ad1848 detect step F(%d/%x/%x) - OPTi chip???\n", i, tmp1, tmp2));
+                if (!ad1847_flag)
+                    optiC930 = 1;
+                break;
+            }
         }
     }
 
@@ -1688,7 +1700,10 @@
                         }
                         else
                         {
-                            devc->model = MD_4231;
+                            if (! deskpro_xl)
+                            {
+                                devc->model = MD_4231;
+                            }
                         }
                 }
             }
@@ -1708,6 +1723,7 @@
     if (devc->model == MD_1848 && ad1847_flag)
         devc->chip_name = "AD1847";
 
+    DDB(printk("ad1848_detect() - '%s' (%d)\n", devc->chip_name, devc->model));
 
     return 1;
 }
          

Or you can download my recompiled version here.

The /etc/conf.modules section ended up being like this for the driver:

alias sound ad1848
alias midi opl3
options opl3 io=0x388
options ad1848 io=0x530 irq=9 dma=1,0 type=2 deskpro_xl=1
          


Compaq Deskpro XL 5133


Topic: Configuration, by Kjetil @ 01/11-2020, Article Link

Amitech Amiga Mouse Repair

I have an Amiga mouse that behaved so poorly that it was unusable. The symptom was that movement was barely detected, if at all at some times. After digging around on the Internet I found that one possible cause is the IR emitter and IR photo-transistors that are used to generate the quadrature encoder pulses.

I ordered replacements from my local dealer, specifically:
* OP 750A - IR phototransistor 850 nm 30 V Side Looking, Optek

IR phototransistors


* IRL 81A - IR emitter 860nm 100mA 1.3V THT, Osram Opto Semiconductors

IR emitters


And soldered on these replacements:

Amitech mouse replacements


This is indeed what was causing the problems and the mouse is now working again:

Amitech Denmark Logo


Topic: Repair, by Kjetil @ 03/10-2020, Article Link

Linux Distribution for LOADLIN

This is a similar project to the Linux Distribution for 386SX but this with some different goals. Most importantly to boot it with LOADLIN directly from DOS and keeping the root filesystem in RAM using Cramfs. In addition, I wanted to have functioning SLIP support.

I ended up using these specific software versions:
* linux-2.4.37.11
* gcc-3.4.6
* busybox-1.19.4
* uClibc-0.9.33.2
* binutils-2.32

Get the necessary scripts, configuration and patches here to make it yourself. Or just get the completed kernel and root filesystem here.

For easy reference, here is the script to compile everything:

#!/bin/bash
set -e

TARGET="i386-linux-uclibc"
PREFIX="${HOME}/opt/gcc-${TARGET}/"
SYSROOT="${PREFIX}/${TARGET}/sysroot"

GCC_SRC="gcc-3.4.6.tar.bz2"
BINUTILS_SRC="binutils-2.32.tar.xz"
UCLIBC_SRC="uClibc-0.9.33.2.tar.xz"
LINUX_SRC="linux-2.4.37.11.tar.xz"
BUSYBOX_SRC="busybox-1.19.4.tar.bz2"

export PATH="${PREFIX}bin:$PATH"

# Prepare Prefix and System Root
if [ -d "$SYSROOT" ]; then
  echo "Old system root directory detected, please remove it."
  exit 1
else
  mkdir -p "$SYSROOT/usr"
fi

# Prepare Build Directories:
if [ -d build ]; then
  echo "Old build directory detected, please remove it."
  exit 1
else
  mkdir -p build/binutils
  mkdir -p build/gcc-stage1
  mkdir -p build/gcc-stage2
  mkdir -p build/uclibc
  mkdir -p build/linux
  mkdir -p build/busybox
fi

# Unpack Sources:
if [ -d source ]; then
  cd source
  tar -xvjf "$GCC_SRC"
  tar -xvJf "$BINUTILS_SRC"
  tar -xvJf "$UCLIBC_SRC" -C ../build/uclibc
  tar -xvJf "$LINUX_SRC" -C ../build/linux
  tar -xvjf "$BUSYBOX_SRC" -C ../build/busybox
  cd -
else
  echo "No source directory, please download sources."
  exit 1
fi

# Patch gcc-3.4.6:
cd "source/gcc-3.4.6/gcc/config/i386/"
if ! fgrep --silent "inhibit_libc" linux.h; then
  patch -p 0 < ../../../../../gcc-3.4.6-linux.h.patch
fi
cd -

# Patch linux-2.4.37.11:
cd "build/linux/linux-2.4.37.11/include/linux/"
if ! fgrep --silent "<linux/types.h>" filter.h; then
  patch -p 0 < ../../../../../linux-2.4.37.11-filter.h.patch
fi
cd -

# Install Linux 2.4 Headers:
cd build/linux/linux-*
make ARCH=i386 mrproper
make ARCH=i386 include/linux/version.h
make ARCH=i386 symlinks
mkdir -p "$SYSROOT/usr/include/asm"
cp -v -R -H include/asm "$SYSROOT/usr/include"
cp -v -R include/asm-generic "$SYSROOT/usr/include"
cp -v -R include/linux "$SYSROOT/usr/include"
touch "${SYSROOT}/usr/include/linux/autoconf.h"
cd -

# Build binutils:
cd build/binutils
../../source/binutils-*/configure --target="$TARGET" --prefix="$PREFIX" --with-sysroot="$SYSROOT" --disable-werror --enable-languages=c,c++ --enable-shared --without-newlib --disable-libgomp --enable-fast-install=N/A
make all-{binutils,gas,ld}
make install-{binutils,ld,gas}
cd -

# Build Stage 1 GCC3:
cd build/gcc-stage1
../../source/gcc-3*/configure --target="$TARGET" --prefix="$PREFIX" --with-sysroot="$SYSROOT" --with-cpu=i386 --disable-fast-install --disable-werror --disable-multilib --enable-languages=c --without-headers --disable-shared --disable-libssp --disable-libmudflap --with-newlib --disable-c99 --disable-libgomp --disable-threads
make all-gcc
make install-gcc
cd -

# Install uClibc Headers:
cd build/uclibc/uClibc-*
cp -v ../../../config-uclibc .config
sed -i -e "s%KERNEL_HEADERS=.*%KERNEL_HEADERS=\"$SYSROOT/usr/include/\"%" .config
make ARCH=i386 PREFIX="$SYSROOT" install_headers
cd -

# Build uClibc:
cd build/uclibc/uClibc-*
make ARCH=i386 PREFIX="$SYSROOT"
make ARCH=i386 PREFIX="$SYSROOT" install
cd -

# Build Stage 2 GCC3:
cd build/gcc-stage2
../../source/gcc-3*/configure --target="$TARGET" --prefix="$PREFIX" --with-sysroot="$SYSROOT" --with-cpu=i386 --enable-fast-install=N/A --disable-werror --enable-languages=c,c++ --disable-shared --without-newlib --disable-libgomp --disable-threads
make all-gcc
make install-gcc
cd -

# Build Linux 2.4:
cd build/linux/linux-*
cp -v ../../../config-linux .config
make ARCH=i386 CROSS_COMPILE=i386-linux-uclibc- oldconfig
make ARCH=i386 CROSS_COMPILE=i386-linux-uclibc- dep
make ARCH=i386 CROSS_COMPILE=i386-linux-uclibc- bzImage
cd -

# Build Busybox:
cd build/busybox/busybox-*
cp -v ../../../config-busybox .config
make CROSS_COMPILE=i386-linux-uclibc-
cd -
          


And here is the script to make the root filesystem:

#!/bin/bash
set -e

ROOTFS="`pwd`/rootfs/"

TARGET="i386-linux-uclibc"
PREFIX="${HOME}/opt/gcc-${TARGET}/"
SYSROOT="${PREFIX}/${TARGET}/sysroot"

export PATH="${PREFIX}bin:$PATH"

if [ -d "$ROOTFS" ]; then
  echo "Old root FS directory detected, please remove it."
  exit 1
fi
mkdir -p "$ROOTFS"

# Install Busybox:
cd build/busybox/busybox-*
make CROSS_COMPILE=i386-linux-uclibc- CONFIG_PREFIX="$ROOTFS" install
cd -

# Create some essential directories
cd "$ROOTFS"
mkdir etc
mkdir etc/init.d
mkdir lib
mkdir proc
mkdir sys
mkdir tmp
mkdir root
mkdir dev
mkdir dev/pts
cd -

# Initial rc.S:
cat > rcS <<EOF
#!/bin/sh
mount -t proc /proc /proc
mount -t devpts /dev/pts /dev/pts
mount -t tmpfs /tmp /tmp
loadkmap < /etc/no-latin1.bmap
hostname busybox
EOF
mv -v rcS "$ROOTFS/etc/init.d/"

# Initial inittab:
cat > inittab <<EOF
::sysinit:/etc/init.d/rcS
::respawn:-/bin/sh
::ctrlaltdel:/sbin/reboot
::shutdown:/bin/umount -a -r
::restart:/sbin/init
EOF
mv -v inittab "$ROOTFS/etc/"

# Copy this system's keymap:
loadkeys -b /usr/share/kbd/keymaps/i386/qwerty/no-latin1.map.gz > "$ROOTFS/etc/no-latin1.bmap"

# Make everything root user:
sudo chown -R root:root "$ROOTFS"

# Create some critical devices:
sudo mknod "$ROOTFS/dev/tty" c 5 0
sudo mknod "$ROOTFS/dev/console" c 5 1
sudo mknod -m 0666 "$ROOTFS/dev/null" c 1 3

# Create some useful devices:
sudo mknod "$ROOTFS/dev/rtc" c 10 135
sudo mknod "$ROOTFS/dev/tty0" c 4 0
sudo mknod "$ROOTFS/dev/tty1" c 4 1
sudo mknod "$ROOTFS/dev/tty2" c 4 2
sudo mknod "$ROOTFS/dev/tty3" c 4 3
sudo mknod "$ROOTFS/dev/ttyS0" c 4 64
sudo mknod "$ROOTFS/dev/ttyS1" c 4 65
sudo mknod "$ROOTFS/dev/fd0" b 2 0
sudo mknod "$ROOTFS/dev/fd1" b 2 1
sudo mknod "$ROOTFS/dev/root" b 4 0
sudo mknod "$ROOTFS/dev/lp0" c 6 0

# SetUID on busybox binary:
sudo chmod +s "$ROOTFS/bin/busybox"

# Make rcS executable:
sudo chmod +x "$ROOTFS/etc/init.d/rcS"

# Make Compressed ROM archive:
mkfs.cramfs rootfs rootfs.cramfs
          


Instead of using LOADLIN, it is actually easy to start this with QEMU as well, like so:

qemu-system-i386 -kernel bzImage -initrd rootfs.cramfs
          


Topic: Configuration, by Kjetil @ 12/09-2020, Article Link

Outlaws in Wine

I have made an effort in getting the classic LucasArts game Outlaws working in Wine with music, which is essential due to its excellent soundtrack. This is a similar to my other effort with M.I.A., except this time the music playback mechanism is more advanced. I had to make additional hacks to the Wine "mcicda" library to make it pause and resume in the middle of tracks.

Here is a rough guide for the commands required for installation. Also, when the installation asks about DirectX 3.0A, just skip this.

mkdir -p ~/opt/outlaws
mkdir ~/opt/outlaws/cd1 # Then copy files from CD1 into here.
mkdir ~/opt/outlaws/cd2 # Then copy files from CD2 into here.
echo "OUTLAWS_1" > ~/opt/outlaws/cd1/.windows-label
echo "OUTLAWS_2" > ~/opt/outlaws/cd2/.windows-label
ln -s "cd1" ~/opt/outlaws/drive_d
WINEARCH=win32 WINEPREFIX=~/opt/outlaws winecfg # D: = "drive_d" = CD-ROM
WINEARCH=win32 WINEPREFIX=~/opt/outlaws wine ~/opt/outlaws/drive_d/SETUP.EXE
          


I had to enable the "Virtual Desktop" setting with "winecfg" for certain stuff like menus to work. I also just configured my X windows resolution to 800x600 before playing the game.

To make the music playback work, a lot of additional steps are required. First the patched "mcicda.dll", which can be downloaded here. This should placed at "~/opt/outlaws/drive_c/windows/system32/mcicda.dll"

Here is the patched code in case you want to compile it yourself, using the Wine 4.0.2 source code as a basis:

--- mcicda.c.orig	2020-08-22 14:22:13.861217377 +0200
+++ mcicda.c	2020-08-22 14:22:18.323217425 +0200
@@ -20,11 +20,21 @@
  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
  */
 
+#define MPLAYER_FIFO_LOCATION "/tmp/mplayer.fifo"
+#define TOC_FILE_LOCATION "/tmp/toc.txt"
+
 #include "config.h"
 #include <stdarg.h>
 #include <stdio.h>
 #include <string.h>
 
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <limits.h>
+#include <time.h>
+
 #define WIN32_NO_STATUS
 #include "windef.h"
 #include "winbase.h"
@@ -79,10 +89,211 @@
 typedef HRESULT(WINAPI*LPDIRECTSOUNDCREATE)(LPCGUID,LPDIRECTSOUND*,LPUNKNOWN);
 static LPDIRECTSOUNDCREATE pDirectSoundCreate;
 
+static int mplayer_current_track = 0;
+static int mplayer_current_min   = 0;
+static int mplayer_current_sec   = 0;
+static int mplayer_current_frame = 0;
+static struct timespec mplayer_playback_started = {0,0};
+
+static void mplayer_command(const char *command)
+{
+    int fd, written;
+
+    fd = open(MPLAYER_FIFO_LOCATION, O_NONBLOCK | O_WRONLY);
+    if (fd == -1) {
+        TRACE("No pipe\n");
+        return;
+    }
+
+    written = write(fd, command, strlen(command));
+    if (written <= 0) {
+        TRACE("Write failed\n");
+    }
+
+    close(fd);
+}
+
 static BOOL device_io(HANDLE dev, DWORD code, void *inbuffer, DWORD insize, void *outbuffer, DWORD outsize, DWORD *retsize, OVERLAPPED *overlapped)
 {
     const char *str;
-    BOOL ret = DeviceIoControl(dev, code, inbuffer, insize, outbuffer, outsize, retsize, overlapped);
+
+    int track_no, min, sec, frame;
+    BOOL ret = TRUE;
+    CDROM_TOC *toc;
+    CDROM_SUB_Q_DATA_FORMAT *qfmt;
+    SUB_Q_CHANNEL_DATA *qdata;
+    FILE *fh;
+    char buf[16];
+    struct timespec now;
+
+    *retsize = 0;
+
+    switch (code) {
+    case IOCTL_CDROM_READ_TOC:
+        toc = (CDROM_TOC *)outbuffer;
+        *retsize = CDROM_TOC_SIZE;
+
+        toc->Length[0] = 0;
+        toc->Length[1] = 0;
+        toc->FirstTrack = 1;
+        toc->LastTrack = 1;
+
+        // Set up first track as data track.
+        toc->TrackData[0].TrackNumber = 1;
+        toc->TrackData[0].Control = 0x4;
+        toc->TrackData[0].Address[1] = 0;
+        toc->TrackData[0].Address[2] = 0;
+        toc->TrackData[0].Address[3] = 0;
+
+        // Get other audio tracks from toc file.
+        fh = fopen(TOC_FILE_LOCATION, "r");
+        if (fh == NULL) {
+          TRACE("IOCTL_CDROM_READ_TOC, Failed to open: %s\n", TOC_FILE_LOCATION);
+          break;
+        }
+
+        while (fgets(buf, sizeof(buf), fh) != NULL)
+        {
+          sscanf(buf, "%02d:%02d:%02d", &min, &sec, &frame);
+
+          toc->TrackData[toc->LastTrack].TrackNumber = toc->LastTrack + 1;
+          toc->TrackData[toc->LastTrack].Control = 0;
+          toc->TrackData[toc->LastTrack].Address[1] = min;
+          toc->TrackData[toc->LastTrack].Address[2] = sec;
+          toc->TrackData[toc->LastTrack].Address[3] = frame;
+
+          toc->LastTrack++;
+
+          TRACE("IOCTL_CDROM_READ_TOC, Track %d = %02d:%02d:%02d\n", toc->LastTrack, min, sec, frame);
+        }
+
+        toc->LastTrack--; // Remove the last dummy track:
+
+        fclose(fh);
+        break;
+
+    case IOCTL_CDROM_STOP_AUDIO:
+        mplayer_command("stop\n");
+        break;
+
+    case IOCTL_CDROM_PAUSE_AUDIO:
+        mplayer_command("stop\n");
+        break;
+
+    case IOCTL_CDROM_READ_Q_CHANNEL:
+        qfmt  = (CDROM_SUB_Q_DATA_FORMAT *)inbuffer;
+        qdata = (SUB_Q_CHANNEL_DATA *)outbuffer;
+        *retsize = sizeof(SUB_Q_CHANNEL_DATA);
+
+        if (qfmt->Format == IOCTL_CDROM_CURRENT_POSITION)
+        {
+            qdata->CurrentPosition.FormatCode = IOCTL_CDROM_CURRENT_POSITION;
+            qdata->CurrentPosition.Control = 0;
+            qdata->CurrentPosition.ADR = 0;
+            qdata->CurrentPosition.TrackNumber = mplayer_current_track;
+            qdata->CurrentPosition.IndexNumber = 0;
+
+            clock_gettime(CLOCK_MONOTONIC, &now);
+            TRACE("IOCTL_CDROM_READ_Q_CHANNEL, Started = %lu.%lu\n",
+                mplayer_playback_started.tv_sec, mplayer_playback_started.tv_nsec);
+            TRACE("IOCTL_CDROM_READ_Q_CHANNEL, Now = %lu.%lu\n", now.tv_sec, now.tv_nsec);
+
+            min = (now.tv_sec - mplayer_playback_started.tv_sec) / 60;
+            sec = (now.tv_sec - mplayer_playback_started.tv_sec) % 60;
+            frame = (now.tv_nsec - mplayer_playback_started.tv_nsec);
+            if (frame < 0) {
+                frame = 0 - frame;
+                sec--;
+                if (sec < 0) {
+                  sec = 59;
+                  min--;
+                }
+            }
+            frame = (frame / 10000000) * 0.75;
+
+            if (mplayer_current_min > 0 ||
+                mplayer_current_sec > 0 ||
+                mplayer_current_frame > 0)
+            {
+                min += mplayer_current_min;
+                sec += mplayer_current_sec;
+                if (sec >= 60) {
+                    sec -= 60;
+                    min++;
+                }
+                frame += mplayer_current_frame;
+                if (frame >= 76) {
+                    frame -= 76;
+                    sec++;
+                    if (sec >= 60) {
+                        sec -= 60;
+                        min++;
+                    }
+                }
+            }
+
+            qdata->CurrentPosition.TrackRelativeAddress[0] = 0;
+            qdata->CurrentPosition.TrackRelativeAddress[1] = min;
+            qdata->CurrentPosition.TrackRelativeAddress[2] = sec;
+            qdata->CurrentPosition.TrackRelativeAddress[3] = frame;
+
+            qdata->CurrentPosition.AbsoluteAddress[0] = 0;
+            qdata->CurrentPosition.AbsoluteAddress[1] = min;
+            qdata->CurrentPosition.AbsoluteAddress[2] = sec;
+            qdata->CurrentPosition.AbsoluteAddress[3] = frame;
+
+            fh = fopen(TOC_FILE_LOCATION, "r");
+            if (fh == NULL) {
+              TRACE("IOCTL_CDROM_READ_Q_CHANNEL, Failed to open: %s\n", TOC_FILE_LOCATION);
+              break;
+            }
+
+            track_no = 2;
+            while (fgets(buf, sizeof(buf), fh) != NULL)
+            {
+                if (track_no == mplayer_current_track) {
+                    sscanf(buf, "%02d:%02d:%02d", &min, &sec, &frame);
+                    qdata->CurrentPosition.AbsoluteAddress[1] += min;
+                    qdata->CurrentPosition.AbsoluteAddress[2] += sec;
+                    if (qdata->CurrentPosition.AbsoluteAddress[2] >= 60) {
+                        qdata->CurrentPosition.AbsoluteAddress[2] -= 60;
+                        qdata->CurrentPosition.AbsoluteAddress[1]++;
+                    }
+                    qdata->CurrentPosition.AbsoluteAddress[3] += frame;
+                    if (qdata->CurrentPosition.AbsoluteAddress[3] >= 76) {
+                        qdata->CurrentPosition.AbsoluteAddress[3] -= 76;
+                        qdata->CurrentPosition.AbsoluteAddress[2]++;
+                        if (qdata->CurrentPosition.AbsoluteAddress[2] >= 60) {
+                            qdata->CurrentPosition.AbsoluteAddress[2] -= 60;
+                            qdata->CurrentPosition.AbsoluteAddress[1]++;
+                        }
+                    }
+                    break;
+                }
+                track_no++;
+            }
+
+            fclose(fh);
+
+            TRACE("IOCTL_CDROM_READ_Q_CHANNEL, Current Track = %d\n", mplayer_current_track);
+            TRACE("IOCTL_CDROM_READ_Q_CHANNEL, Rel Pos = %02d:%02d:%02d\n",
+                qdata->CurrentPosition.TrackRelativeAddress[1],
+                qdata->CurrentPosition.TrackRelativeAddress[2],
+                qdata->CurrentPosition.TrackRelativeAddress[3]);
+            TRACE("IOCTL_CDROM_READ_Q_CHANNEL, Abs Pos = %02d:%02d:%02d\n",
+                qdata->CurrentPosition.AbsoluteAddress[1],
+                qdata->CurrentPosition.AbsoluteAddress[2],
+                qdata->CurrentPosition.AbsoluteAddress[3]);
+        }
+        else
+        {
+           TRACE("IOCTL_CDROM_READ_Q_CHANNEL, Unknown format: %d\n", qfmt->Format);
+        }
+        break;
+
+    default:
+        break;
+    }
 
 #define XX(x) case (x): str = #x; break
     switch (code)
@@ -906,6 +1117,9 @@
     SUB_Q_CHANNEL_DATA          data;
     CDROM_TOC			toc;
 
+    int track_no, min, sec, frame;
+    char command[PATH_MAX];
+
     TRACE("(%04X, %08X, %p);\n", wDevID, dwFlags, lpParms);
 
     if (lpParms == NULL)
@@ -914,6 +1128,35 @@
     if (wmcda == NULL)
 	return MCIERR_INVALID_DEVICE_ID;
 
+    mplayer_command("stop\n");
+
+    track_no = MCI_TMSF_TRACK(lpParms->dwFrom);
+    min      = MCI_TMSF_MINUTE(lpParms->dwFrom);
+    sec      = MCI_TMSF_SECOND(lpParms->dwFrom);
+    frame    = MCI_TMSF_FRAME(lpParms->dwFrom);
+    TRACE("Track no: %d (%02d:%02d:%02d)\n", track_no, min, sec, frame);
+
+    snprintf(command, PATH_MAX, "loadfile track%02d.flac\n", track_no);
+    mplayer_command(command);
+
+    mplayer_current_track = track_no;
+    clock_gettime(CLOCK_MONOTONIC, &mplayer_playback_started);
+
+    if (min > 0 || sec > 0 || frame > 0) {
+      mplayer_current_min = min;
+      mplayer_current_sec = sec;
+      mplayer_current_frame = frame;
+
+      sec += (min * 60);
+      frame *= 1.333333;
+      TRACE("Seek to: %d.%02d\n", sec, frame);
+
+      snprintf(command, PATH_MAX, "seek %d.%02d 2\n", sec, frame);
+      mplayer_command(command);
+    }
+
+    return 0; // Because of hijacking, this ends here.
+
     if (!MCICDA_ReadTOC(wmcda, &toc, &br))
         return MCICDA_GetError(wmcda);
          


To make music playback work as painlessly as possible, I have once again made a script to start the game:

#!/bin/sh
export WINEPREFIX=~/opt/outlaws

MPLAYER_FIFO=/tmp/mplayer.fifo
TOC_FILE=/tmp/toc.txt
MPLAYER_PID_FILE=/tmp/mplayer.pid

function mplayer_stop {
  if [ -f "$MPLAYER_PID_FILE" ]; then
    kill `cat "$MPLAYER_PID_FILE"`
    rm -f "$MPLAYER_PID_FILE"
  fi
  rm -f "$MPLAYER_FIFO"
}

function mplayer_start {
  if [ ! -p "$MPLAYER_FIFO" ]; then
    mkfifo "$MPLAYER_FIFO"
  fi
  cd "${WINEPREFIX}/drive_d"
  mplayer -vo null -idle -slave -input file=$MPLAYER_FIFO 1&>/dev/null &
  echo "$!" > "$MPLAYER_PID_FILE"
  cd -
}

CD_NO="0"
while [ "$CD_NO" != "1" ] && [ "$CD_NO" != "2" ]; do
  read -p "CD number? [1 or 2] " CD_NO
done

MODE="0"
while [ "$MODE" != "g" ] && [ "$MODE" != "c" ]; do
  read -p "Start [g]ame or [c]hange CD only? " MODE
done

mplayer_stop

rm -f "${WINEPREFIX}/drive_d"
ln -s "cd$CD_NO" "${WINEPREFIX}/drive_d"
cp "${WINEPREFIX}/drive_d/toc.txt" "$TOC_FILE"

mplayer_start

if [ "$MODE" == "c" ]; then
  # If only changing CD, exit now.
  exit 0
fi

(cd "${WINEPREFIX}/drive_c/Program Files/LucasArts/Outlaws" && WINEARCH=win32 wine OLWIN.EXE)

mplayer_stop
rm -f "$TOC_FILE"
          

The same script is also used to change the CD while the game is running, as this is required in some instances.

The CD audio tracks should be ripped to FLAC format and be placed as track02.flac to track08.flac in "~/opt/outlaws/cd1/" for CD1, followed by track02.flac to track09.flac in "~/opt/outlaws/cd2/" for CD2. In addition, you will need a couple of "Table of Contents" files for each CD. These will inform the patched "mcicda.dll" file about the length of each track.

Put the following in "~/opt/outlaws/cd1/toc.txt"

00:00:00
03:16:64
07:34:64
11:23:01
15:13:33
19:58:24
23:39:66
27:15:61
          


Put the following in "~/opt/outlaws/cd2/toc.txt"

00:00:00
04:42:15
10:16:03
13:41:47
20:55:08
24:58:10
30:09:45
33:50:23
36:16:17
          


Enjoy!

Topic: Configuration, by Kjetil @ 24/08-2020, Article Link

Booting DOS from PS/2 BASIC

I have a old standalone motherboard from an IBM PS/2 Model 80. The PS/2 systems have a different kind of floppy connector and floppy drive, so one cannot simply connect a regular PC floppy drive without doing some hardware modifications. But fortunately, most of the PS/2 systems have IBM Cassette BASIC in ROM chips on the motherboard and will boot that in case everything else fails.

Someone else has already managed to boot some software from BASIC, so I took it a step further and was able to boot DOS as well. My work is based on the previous Serial Port Floppy Drive Emulation tricks to emulate the floppy drive over the COM1 port. The assembly program presented here will attempt boot a floppy image. Unfortunately I have not been able to boot the reference disk yet...

Once booted into BASIC, it is technically possible to input the complete program by hand (by keyboard):

1 data 233,157,0,184,192,7,142,192,49,219,184,1,2,185,1,0,49,210
2 data 205,19,234,0,124,0,0,251,128,250,0,117,90,128,252,2,116,5
3 data 128,252,3,117,74,83,81,82,80,80,80,232,76,0,136,224,232,71
4 data 0,136,200,232,66,0,136,232,232,61,0,136,208,232,56,0,136,240
5 data 232,51,0,90,48,246,184,0,2,247,226,137,193,88,128,252,3,116
6 data 11,232,49,0,38,136,7,67,226,247,235,9,38,138,7,232,18,0
7 data 67,226,247,88,90,89,91,48,228,248,202,2,0,234,121,0,121,0
8 data 82,186,248,3,238,186,253,3,236,36,32,132,192,116,249,90,195,82
9 data 186,250,3,236,36,14,60,4,117,246,186,248,3,236,90,195,186,251
10 data 3,236,12,128,238,186,248,3,176,12,238,186,249,3,176,0,238,186
11 data 251,3,236,36,127,238,186,250,3,176,6,238,186,251,3,176,3,238
12 data 186,249,3,236,12,1,238,49,192,142,216,250,232,0,0,88,91,45
13 data 210,0,137,198,184,48,0,142,192,191,0,0,185,157,0,46,138,4
14 data 38,136,5,70,71,226,246,62,161,76,0,38,163,119,0,62,161,78
15 data 0,38,163,121,0,62,199,6,76,0,22,0,62,140,6,78,0,49
16 data 192,62,163,0,4,251,180,9,176,33,183,0,179,4,185,3,0,205
17 data 16,180,0,205,22,234,0,0,48,0
99 def seg=1984:a=0:for i=0 to 297:read j:poke a+i,j:next:call a
          

However, it is very easy to make a mistake and this work is very tedious.
Instead it's a lot better to chain-load the program using the same method from the GitHub link.

The steps are as follows, assuming you are on a Linux box:
1) Make sure that the serial port on your system is set correctly:

stty -F /dev/ttyS0 9600 raw
          


2) Enter and run the chain-loader in BASIC on the PS/2 system:

1 data 14,7,184,227,0,153,137,215,205,20,185,19,1,180,2,205,20,158,120,249,252,170,226,245,81,195
2 def seg=256:a=65432:for i=0 to 25:read j:poke a+i,j:next:call a
          


3) Send the assembled program directly through the serial port:

cat sfdboot.bin > /dev/ttyS0
          


4) Start the serial port floppy drive emulator with a bootable image:

./serialfd -d /dev/ttyS0 -a floppy.img
          


5) If everything went well, there should be three red exclamation marks on the PS/2 system, press any key to commence the booting from the emulated image.

In the case of booting MS-DOS it should look something like this:

Starting MS-DOS...


Here is the assembly code, assembled with NASM as follows: nasm sfdboot.asm -fbin -o sfdboot.bin

org 0x0 ; Position independent.
bits 16
cpu 8086

COM1_BASE equ 0x3f8
COM1_THR  equ COM1_BASE + 0 ; Transmitter Holding Buffer
COM1_RBR  equ COM1_BASE + 0 ; Receiver Buffer
COM1_IER  equ COM1_BASE + 1 ; Interrupt Enable Register
COM1_FCR  equ COM1_BASE + 2 ; FIFO Control Register
COM1_IIR  equ COM1_BASE + 2 ; Interrupt Identification Register
COM1_LCR  equ COM1_BASE + 3 ; Line Control Register
COM1_LSR  equ COM1_BASE + 5 ; Line Status Register
COM1_DLL  equ COM1_BASE + 0 ; Divisor Latch Low Byte
COM1_DLH  equ COM1_BASE + 1 ; Divisor Latch High Byte

RESIDENT_SEGMENT equ 0x0030 ; Bootstrap stack area.

section .text
start:
  jmp main

resident_code_start:
  ; Setup ES:BX to point at bootloader address 07C0:0
  mov ax, 0x07C0
  mov es, ax
  xor bx, bx

  ; Read VBR into bootloader memory area:
  mov ax, 0x0201
  mov cx, 0x0001
  xor dx, dx
  int 0x13

  ; Jump to bootloader:
  jmp 0x0:0x7C00

int13_interrupt:
  ; Allow other interrupts:
  sti

  ; Check if accessing drive 0 (A:)
  ; If not, then jump to original interrupt instead.
  cmp dl, 0
  jne original_int13

  ; Only operation 0x02 (Read) and 0x03 (Write) are forwarded.
  ; The rest are bypassed directly and returns OK.
  cmp ah, 2
  je _int13_interrupt_ah_ok
  cmp ah, 3
  jne _int13_interrupt_end
_int13_interrupt_ah_ok:

  ; Save registers:
  push bx
  push cx
  push dx

  ; Save sectors and operation information on stack for use later:
  push ax
  push ax
  push ax

  ; Register AL already set.
  call com_port_send
  mov al, ah
  call com_port_send
  mov al, cl
  call com_port_send
  mov al, ch
  call com_port_send
  mov al, dl
  call com_port_send
  mov al, dh
  call com_port_send

  ; Retrieve sector information (stack AL) into DL register:
  pop dx
  xor dh, dh

  mov ax, 512
  mul dx ; DX:AX = AX * DX
  mov cx, ax

  ; Determine receive (Read) or send (Write) from operation (stack AH):
  pop ax
  cmp ah, 3
  je _int13_interrupt_send_loop

_int13_interrupt_recv_loop:
  call com_port_recv
  mov [es:bx], al
  inc bx
  loop _int13_interrupt_recv_loop
  jmp _int13_loop_done

_int13_interrupt_send_loop:
  mov al, [es:bx]
  call com_port_send
  inc bx
  loop _int13_interrupt_send_loop

_int13_loop_done:

  ; Retrieve sector information (stack AL) as sectors handled:
  pop ax

  ; Restore registers:
  pop dx
  pop cx
  pop bx

_int13_interrupt_end:
  ; AL register will have same value as upon entering routine.
  xor ah, ah ; Code 0 (No Error)
  clc ; Clear error bit.
  retf 2

original_int13:
  jmp original_int13:original_int13 ; Will be overwritten runtime!

; Send contents from AL on COM1 port:
com_port_send:
  push dx
  mov dx, COM1_THR
  out dx, al
  mov dx, COM1_LSR
_com_port_send_wait:
  in al, dx
  and al, 0b00100000 ; Empty Transmit Holding Register
  test al, al
  jz _com_port_send_wait
  pop dx
  ret

; Return contents in AL on COM1 port:
com_port_recv:
  push dx
_com_port_recv_wait:
  mov dx, COM1_IIR
  in al, dx
  and al, 0b00001110 ; Identification
  cmp al, 0b00000100 ; Enable Received Data Available Interrupt
  jne _com_port_recv_wait
  mov dx, COM1_RBR
  in al, dx
  pop dx
  ret

resident_code_end:

main:
  ; Set Baudrate on COM1 to 9600, divisor = 12:
  mov dx, COM1_LCR
  in al, dx
  or al, 0b10000000 ; Set Divisor Latch Access Bit (DLAB).
  out dx, al

  mov dx, COM1_DLL
  mov al, 0xc
  out dx, al
  
  mov dx, COM1_DLH
  mov al, 0
  out dx, al

  mov dx, COM1_LCR
  in al, dx
  and al, 0b01111111 ; Reset Divisor Latch Access Bit (DLAB).
  out dx, al

  ; Disable and clear FIFO on COM1, to put it in 8250 compatibility mode:
  mov dx, COM1_FCR
  mov al, 0b00000110 ; Clear both FIFOs.
  out dx, al
  ; NOTE: Not tested what happens if this is run on an actual 8250 chip...

  ; Set mode on COM1 to 8 data bits, no parity and 1 stop bit:
  mov dx, COM1_LCR
  mov al, 0b00000011 ; 8-N-1
  out dx, al

  ; Enable interrupt bit on COM1:
  mov dx, COM1_IER
  in al, dx
  or al, 0b00000001 ; Enable Received Data Available Interrupt
  out dx, al

  ; Interact directly with IVT:
  xor ax, ax
  mov ds, ax ; Data Segment now 0000
  cli ; Disable Interrupts

  call get_ip
get_ip:
  pop ax ; IP
  pop bx ; CS
  sub ax, (get_ip - resident_code_start)
  mov si, ax ; "resident_code_start" now in SI.

  ; Copy the code to a new resident area using CS:SI -> ES:DI
  mov ax, RESIDENT_SEGMENT
  mov es, ax
  mov di, 0
  mov cx, (resident_code_end - resident_code_start)
_copy_to_resident_area:
  mov byte al, [cs:si]
  mov byte [es:di], al
  inc si
  inc di
  loop _copy_to_resident_area

  ; Save old interrupt handler:
  ; ES = RESIDENT_SEGMENT
  mov ax, [ds:0x4c]
  mov word [es:original_int13 - resident_code_start + 1], ax
  mov ax, [ds:0x4e]
  mov word [es:original_int13 - resident_code_start + 3], ax

  ; Overwrite with new interrupt handler:
  ; ES = RESIDENT_SEGMENT
  mov word [ds:0x4c], (int13_interrupt - resident_code_start)
  mov word [ds:0x4e], es

  ; Zero out COM1 port address in BDA to avoid DOS interference:
  ; DOS can set baudrate to 2400 at startup, which will cause issues.
  xor ax, ax
  mov word [ds:0x400], ax

  sti ; Enable Interrupts

  ; Indicate on screen "Ready for Loading" after key press:
  mov ah, 0x9  ; Write character and attribute at cursor position.
  mov al, 0x21 ; Character = '!'
  mov bh, 0    ; Page Number = 0
  mov bl, 0x4  ; Color = Red
  mov cx, 0x3  ; Number of Times = 3
  int 0x10

  ; Read any key press:
  mov ah, 0x0  ; Read keystroke.
  int 0x16

  ; Jump to new resident area:
  jmp RESIDENT_SEGMENT:0
          


The code is also uploaded to the serialfd GitHub repository in case of future changes and improvements.

Topic: Scripts and Code, by Kjetil @ 02/08-2020, Article Link

Serial Port Floppy Drive Emulation

While working on another project I needed to figure out a way to emulate a floppy drive. After doing some research I learned more about how the Interrupt Vector Table on PCs work and how TSR programs operate under DOS. So the result is a DOS TSR program that intercepts BIOS INT 13H calls and forwards these over the serial port to a remote Linux box that operates on a floppy disk image.

I have borrowed some code from my previous Kermit project that also uses x86 assembly with serial ports. This program also shares some of the same limitations; hard coded with baudrate 9600 on the COM1 port. The TSR has been tested on the Bochs emulator and on a real 25MHz 80486SX PC.

Here is the TSR part of the program, assembled with NASM as follows: nasm serialfd.asm -fbin -o serialfd.com

org 0x100
bits 16
cpu 8086

COM1_BASE equ 0x3f8
COM1_THR  equ COM1_BASE + 0 ; Transmitter Holding Buffer
COM1_RBR  equ COM1_BASE + 0 ; Receiver Buffer
COM1_IER  equ COM1_BASE + 1 ; Interrupt Enable Register
COM1_FCR  equ COM1_BASE + 2 ; FIFO Control Register
COM1_IIR  equ COM1_BASE + 2 ; Interrupt Identification Register
COM1_LCR  equ COM1_BASE + 3 ; Line Control Register
COM1_LSR  equ COM1_BASE + 5 ; Line Status Register
COM1_DLL  equ COM1_BASE + 0 ; Divisor Latch Low Byte
COM1_DLH  equ COM1_BASE + 1 ; Divisor Latch High Byte

section .text
start:
  jmp main

int13_interrupt:
  ; Allow other interrupts:
  sti

  ; Check if accessing drive 0 (A:) or drive 1 (B:)
  ; If not, then jump to original interrupt instead.
  cmp dl, 0
  je _int13_interrupt_dl_ok
  cmp dl, 1
  jne original_int13
_int13_interrupt_dl_ok:

  ; Only operation 0x02 (Read) and 0x03 (Write) are forwarded.
  ; The rest are bypassed directly and returns OK.
  cmp ah, 2
  je _int13_interrupt_ah_ok
  cmp ah, 3
  jne _int13_interrupt_end
_int13_interrupt_ah_ok:

  ; Save registers:
  push bx
  push cx
  push dx

  ; Save sectors and operation information on stack for use later:
  push ax
  push ax
  push ax

  ; Register AL already set.
  call com_port_send
  mov al, ah
  call com_port_send
  mov al, cl
  call com_port_send
  mov al, ch
  call com_port_send
  mov al, dl
  call com_port_send
  mov al, dh
  call com_port_send

  ; Retrieve sector information (stack AL) into DL register:
  pop dx
  xor dh, dh

  mov ax, 512
  mul dx ; DX:AX = AX * DX
  mov cx, ax

  ; Determine receive (Read) or send (Write) from operation (stack AH):
  pop ax
  cmp ah, 3
  je _int13_interrupt_send_loop

_int13_interrupt_recv_loop:
  call com_port_recv
  mov [es:bx], al
  inc bx
  loop _int13_interrupt_recv_loop
  jmp _int13_loop_done

_int13_interrupt_send_loop:
  mov al, [es:bx]
  call com_port_send
  inc bx
  loop _int13_interrupt_send_loop

_int13_loop_done:

  ; Retrieve sector information (stack AL) as sectors handled:
  pop ax

  ; Restore registers:
  pop dx
  pop cx
  pop bx

_int13_interrupt_end:
  ; AL register will have same value as upon entering routine.
  xor ah, ah ; Code 0 (No Error)
  clc ; Clear error bit.
  retf 2

original_int13:
  jmp original_int13:original_int13 ; Will be overwritten runtime!

; Send contents from AL on COM1 port:
com_port_send:
  push dx
  mov dx, COM1_THR
  out dx, al
  mov dx, COM1_LSR
_com_port_send_wait:
  in al, dx
  and al, 0b00100000 ; Empty Transmit Holding Register
  test al, al
  jz _com_port_send_wait
  pop dx
  ret

; Return contents in AL on COM1 port:
com_port_recv:
  push dx
_com_port_recv_wait:
  mov dx, COM1_IIR
  in al, dx
  and al, 0b00001110 ; Identification
  cmp al, 0b00000100 ; Enable Received Data Available Interrupt
  jne _com_port_recv_wait
  mov dx, COM1_RBR
  in al, dx
  pop dx
  ret

; TSR end marker:
tsr_end:

main:
  ; NOTE: No protection to prevent TSR from being loaded twice or more!

  ; Set Baudrate on COM1 to 9600, divisor = 12:
  mov dx, COM1_LCR
  in al, dx
  or al, 0b10000000 ; Set Divisor Latch Access Bit (DLAB).
  out dx, al

  mov dx, COM1_DLL
  mov al, 0xc
  out dx, al
  
  mov dx, COM1_DLH
  mov al, 0
  out dx, al

  mov dx, COM1_LCR
  in al, dx
  and al, 0b01111111 ; Reset Divisor Latch Access Bit (DLAB).
  out dx, al

  ; Disable and clear FIFO on COM1, to put it in 8250 compatibility mode:
  mov dx, COM1_FCR
  mov al, 0b00000110 ; Clear both FIFOs.
  out dx, al
  ; NOTE: Not tested what happens if this is run on an actual 8250 chip...

  ; Set mode on COM1 to 8 data bits, no parity and 1 stop bit:
  mov dx, COM1_LCR
  mov al, 0b00000011 ; 8-N-1
  out dx, al

  ; Enable interrupt bit on COM1:
  mov dx, COM1_IER
  in al, dx
  or al, 0b00000001 ; Enable Received Data Available Interrupt
  out dx, al

  ; Call DOS to get original interrupt handler:
  mov al, 0x13
  mov ah, 0x35
  int 0x21
  mov word [original_int13 + 3], es
  mov word [original_int13 + 1], bx

  ; Call DOS to set interrupt handler:
  mov al, 0x13
  mov ah, 0x25
  ; DS is already same as CS, no need to change.
  mov dx, int13_interrupt
  int 0x21

  ; Terminate and Stay Resident:
  mov dx, tsr_end
  shr dx, 1
  shr dx, 1
  shr dx, 1
  shr dx, 1
  add dx, 0x11 ; Add 0x1 for remainder and 0x10 for PSP.
  mov ax, 0x3100
  int 0x21
          


And here the Linux counterpart in C, just compile with GCC:

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
#include <sys/ioctl.h>
#include <string.h>

#define REGISTER_AL 0
#define REGISTER_AH 1
#define REGISTER_CL 2
#define REGISTER_CH 3
#define REGISTER_DL 4
#define REGISTER_DH 5

#define SECTOR_SIZE 512
#define HEADS_PER_CYLINDER_DEFAULT 2

#define OPERATION_READ_DISK_SECTORS 0x02
#define OPERATION_WRITE_DISK_SECTORS 0x03

static uint16_t get_sectors_per_track(FILE *fh)
{
  uint16_t spt;

  fseek(fh, 24, SEEK_SET); /* Offset in Volume Boot Record. */

  if (fread(&spt, sizeof(uint16_t), 1, fh) != 1) {
    return 0; /* Error */
  }

  /* Currently handling 720K and 1.44M floppies. */
  if (spt == 9 || spt == 18) {
    return spt; /* Valid */
  }

  return 0; /* Invalid */
}

static void display_help(char *progname)
{ 
  fprintf(stderr, "Usage: %s <options>\n", progname);
  fprintf(stderr, "Options:\n"
     "  -h          Display this help and exit.\n"
     "  -d DEVICE   Use TTY DEVICE.\n"
     "  -a IMAGE    Floppy IMAGE for A:\n"
     "  -b IMAGE    Floppy IMAGE for B:\n"
     "  -H HPC      Force HPC heads per cylinder.\n"
     "  -S SPT      Force SPT sectors per track.\n"
     "  -v          Verbose debugging output.\n"
     "\n");
}

int main(int argc, char *argv[])
{
  int result = EXIT_SUCCESS;
  int i, c, arg;
  int cylinder, sector, lba;
  struct termios attr;
  unsigned char registers[6];
  int debug_output = 0;
  char *tty_device = NULL;
  int tty_fd = -1;
  FILE *fh;
  char *floppy_a_image = NULL;
  char *floppy_b_image = NULL;
  FILE *floppy_a_fh = NULL;
  FILE *floppy_b_fh = NULL;
  uint16_t floppy_a_spt = 0;
  uint16_t floppy_b_spt = 0;
  int spt = 0;
  int hpc = HEADS_PER_CYLINDER_DEFAULT;
  char *operation;

  while ((c = getopt(argc, argv, "hd:a:b:H:S:v")) != -1) {
    switch (c) {
    case 'h':
      display_help(argv[0]);
      return EXIT_SUCCESS;

    case 'd':
      tty_device = optarg;
      break;

    case 'a':
      floppy_a_image = optarg;
      break;

    case 'b':
      floppy_b_image = optarg;
      break;

    case 'H':
      hpc = atoi(optarg);
      break;

    case 'S':
      spt = atoi(optarg);
      break;

    case 'v':
      debug_output = 1;
      break;

    case '?':
    default:
      display_help(argv[0]);
      return EXIT_FAILURE;
    }
  }

  if (tty_device == NULL) {
    fprintf(stderr, "Please specify a TTY!\n");
    display_help(argv[0]);
    return EXIT_FAILURE;
  }

  if (floppy_a_image == NULL && floppy_b_image == NULL) {
    fprintf(stderr, "Please specify at least one floppy image!\n");
    display_help(argv[0]);
    return EXIT_FAILURE;
  }

  if (hpc == 0) {
    fprintf(stderr, "Invalid heads per cylinder!\n");
    return EXIT_FAILURE;
  }

  /* Open serial TTY device. */
  tty_fd = open(tty_device, O_RDWR | O_NOCTTY);
  if (tty_fd == -1) {
    fprintf(stderr, "open() on TTY device failed with errno: %d\n", errno);
    return EXIT_FAILURE;
  }

  /* Set TTY into a very raw mode. */
  memset(&attr, 0, sizeof(struct termios));
  attr.c_cflag = B9600 | CS8 | CLOCAL | CREAD;
  attr.c_cc[VMIN] = 1;

  if (tcsetattr(tty_fd, TCSANOW, &attr) == -1) {
    fprintf(stderr, "tcgetattr() on TTY device failed with errno: %d\n", errno);
    close(tty_fd);
    return EXIT_FAILURE;
  }

  /* Make sure TTY "Clear To Send" signal is set. */
  arg = TIOCM_CTS;
  if (ioctl(tty_fd, TIOCMBIS, &arg) == -1) {
    fprintf(stderr, "ioctl() on TTY device failed with errno: %d\n", errno);
    close(tty_fd);
    return EXIT_FAILURE;
  }

  /* Get information about floppy A: */
  if (floppy_a_image != NULL) {
    floppy_a_fh = fopen(floppy_a_image, "r+b");
    if (floppy_a_fh == NULL) {
      fprintf(stderr, "fopen() for floppy A: failed with errno: %d\n", errno);
      result = EXIT_FAILURE;
      goto main_end;
    }

    if (spt == 0) {
      floppy_a_spt = get_sectors_per_track(floppy_a_fh);
    } else {
      floppy_a_spt = spt;
    }
    if (floppy_a_spt == 0) {
      fprintf(stderr, "Invalid sectors per track for floppy A:\n");
      result = EXIT_FAILURE;
      goto main_end;
    }
  }

  /* Get information about floppy B: */
  if (floppy_b_image != NULL) {
    floppy_b_fh = fopen(floppy_b_image, "r+b");
    if (floppy_b_fh == NULL) {
      fprintf(stderr, "fopen() for floppy B: failed with errno: %d\n", errno);
      result = EXIT_FAILURE;
      goto main_end;
    }

    if (spt == 0) {
      floppy_b_spt = get_sectors_per_track(floppy_b_fh);
    } else {
      floppy_b_spt = spt;
    }
    if (floppy_b_spt == 0) {
      fprintf(stderr, "Invalid sectors per track for floppy B:\n");
      result = EXIT_FAILURE;
      goto main_end;
    }
  }

  /* Process input and output. */
  while (1) {
    for (i = 0; i < 6; i++) {
      if (read(tty_fd, &registers[i], sizeof(unsigned char)) != 1) {
        fprintf(stderr, "read() failed with errno: %d\n", errno);
        result = EXIT_FAILURE;
        goto main_end;
      }
    }

    if (debug_output) {
      fprintf(stderr, "AL: 0x%02x\n", registers[REGISTER_AL]);
      fprintf(stderr, "AH: 0x%02x\n", registers[REGISTER_AH]);
      fprintf(stderr, "CL: 0x%02x\n", registers[REGISTER_CL]);
      fprintf(stderr, "CH: 0x%02x\n", registers[REGISTER_CH]);
      fprintf(stderr, "DL: 0x%02x\n", registers[REGISTER_DL]);
      fprintf(stderr, "DH: 0x%02x\n", registers[REGISTER_DH]);
    }

    if (registers[REGISTER_DL] == 0x00) {
      spt = floppy_a_spt;
      fh = floppy_a_fh;
    } else if (registers[REGISTER_DL] == 0x01) {
      spt = floppy_b_spt;
      fh = floppy_b_fh;
    } else {
      fprintf(stderr, "Error: Invalid drive number: %02x\n",
        registers[REGISTER_DL]);
      result = EXIT_FAILURE;
      goto main_end;
    }

    /* CX =       ---CH--- ---CL---
     * cylinder : 76543210 98
     * sector   :            543210
     * LBA = ( ( cylinder * HPC + head ) * SPT ) + sector - 1
    */

    cylinder = ((registers[REGISTER_CL] & 0xc0) << 2)
      + registers[REGISTER_CH];
    sector = registers[REGISTER_CL] & 0x3f;
    lba = ((cylinder * hpc + registers[REGISTER_DH]) * spt) + sector - 1;

    if (debug_output) {
      fprintf(stderr, "Cylinder: %d\n", cylinder);
      fprintf(stderr, "Sector  : %d\n", sector);
      fprintf(stderr, "SPT     : %d\n", spt);
      fprintf(stderr, "HPC     : %d\n", hpc);
      fprintf(stderr, "LBA     : %d\n", lba);
      fprintf(stderr, "Offset  : 0x%x\n", lba * SECTOR_SIZE);
    } else {
      switch (registers[REGISTER_AH]) {
      case OPERATION_READ_DISK_SECTORS:
        operation = "Read";
        break;
      case OPERATION_WRITE_DISK_SECTORS:
        operation = "Write";
        break;
      default:
        operation = "Unknown";
        break;
      }
      fprintf(stderr, "%s %c: sector=%d, cylinder=%d count=%d\n",
        operation, (registers[REGISTER_DL] == 0x00) ? 'A' : 'B',
        sector, cylinder, registers[REGISTER_AL]);
    }

    if (fh != NULL) {
      if (fseek(fh, lba * SECTOR_SIZE, SEEK_SET) == -1) {
        fprintf(stderr, "fseek() failed with errno: %d\n", errno);
        result = EXIT_FAILURE;
        goto main_end;
      }
    }

    switch (registers[REGISTER_AH]) {
    case OPERATION_READ_DISK_SECTORS:
      if (debug_output) {
        fprintf(stderr, "READ SECTOR DATA:\n");
      }
      for (i = 0; i < (SECTOR_SIZE * registers[REGISTER_AL]); i++) {
        if (fh != NULL) {
          c = fgetc(fh);
        } else {
          c = 0xFF; /* Dummy data if image is not loaded. */
        }
        if (debug_output) {
          fprintf(stderr, "%02x ", c);
          if (i % 16 == 15) {
            fprintf(stderr, "\n");
          }
        }
        write(tty_fd, &c, sizeof(unsigned char));
      }
      break;

    case OPERATION_WRITE_DISK_SECTORS:
      if (debug_output) {
        fprintf(stderr, "WRITE SECTOR DATA:\n");
      }
      for (i = 0; i < (SECTOR_SIZE * registers[REGISTER_AL]); i++) {
        read(tty_fd, &c, sizeof(unsigned char));
        if (fh != NULL) {
          fputc(c, fh);
        }
        if (debug_output) {
          fprintf(stderr, "%02x ", c);
          if (i % 16 == 15) {
            fprintf(stderr, "\n");
          }
        }
      }
      if (fh != NULL) {
        fflush(fh);
      }
      break;

    default:
      fprintf(stderr, "Error: Unhandled operation: %02x\n",
        registers[REGISTER_AH]);
      result = EXIT_FAILURE;
      goto main_end;
    }
  }

main_end:
  if (tty_fd != -1) close(tty_fd);
  if (floppy_a_fh != NULL) fclose(floppy_a_fh);
  if (floppy_b_fh != NULL) fclose(floppy_b_fh);

  return result;
}
          


I have also uploaded the code to GitHub in case case of further improvements in the future.

Topic: Scripts and Code, by Kjetil @ 03/07-2020, Article Link

Kermit in x86 Assembly

This is kind of a follow up to my other project on file transfers in DOS. I have made a huge improvement by implementing the Kermit Protocol in 16-bit x86 assembly language. Instead of relying on the horrible BIOS service routines, this program interfaces directly to the 8250/16550 UART chip on the PC.

The purpose of this program is bootstrapping, so it has several limitations. It is based loosely on the "Baby Kermit" BASIC program that can be found in the official Kermit manuals. It's hard coded to run at 9600 baud with 8-N-1 parameters on the COM1 port. Both sending and receiving is performed by hogging the CPU and busy-waiting. I recommend to use this program as a means to transfer the real full-feature MS-DOS Kermit.

Apart from testing the program in both the DOSBox and Bochs emulators, I have also tried it on two real machines. On a 8MHz 8088 XT-class machine, it gets some transmission errors, but those are corrected. On a 25MHz 80486SX it runs fine without any errors.

I have uploaded the code to GitHub in case of further improvements, by me or anyone else. But here is the first version, assembled with NASM as follows: nasm kermit.asm -fbin -o kermit.com

org 0x100
bits 16
cpu 8086

COM1_BASE equ 0x3f8
COM1_THR  equ COM1_BASE + 0 ; Transmitter Holding Buffer
COM1_RBR  equ COM1_BASE + 0 ; Receiver Buffer
COM1_IER  equ COM1_BASE + 1 ; Interrupt Enable Register
COM1_FCR  equ COM1_BASE + 2 ; FIFO Control Register
COM1_IIR  equ COM1_BASE + 2 ; Interrupt Identification Register
COM1_LCR  equ COM1_BASE + 3 ; Line Control Register
COM1_LSR  equ COM1_BASE + 5 ; Line Status Register
COM1_DLL  equ COM1_BASE + 0 ; Divisor Latch Low Byte
COM1_DLH  equ COM1_BASE + 1 ; Divisor Latch High Byte

RECV_BUFFER_SIZE equ 100 ; As per Kermit documentation.
SEND_BUFFER_SIZE equ 16 ; No packets sent from this program exceed this.
PACKET_DATA_SIZE equ 94 ; Receive buffer size - 6 fields/terminator.

section .text
start:
  ; Set Baudrate on COM1 to 9600, divisor = 12:
  mov dx, COM1_LCR
  in al, dx
  or al, 0b10000000 ; Set Divisor Latch Access Bit (DLAB)
  out dx, al

  mov dx, COM1_DLL
  mov al, 0xc
  out dx, al
  
  mov dx, COM1_DLH
  mov al, 0
  out dx, al

  mov dx, COM1_LCR
  in al, dx
  and al, 0b01111111 ; Reset Divisor Latch Access Bit (DLAB)
  out dx, al

  ; Disable and clear FIFO on COM1, to put it in 8250 compatibility mode:
  mov dx, COM1_FCR
  mov al, 0b00000110 ; Clear both FIFOs.
  out dx, al

  ; Set mode on COM1 to 8 data bits, no parity and 1 stop bit:
  mov dx, COM1_LCR
  mov al, 0b00000011 ; 8-N-1
  out dx, al

  ; Enable interrupt bit on COM1:
  mov dx, COM1_IER
  in al, dx
  or al, 0b00000001 ; Enable Received Data Available Interrupt
  out dx, al

  ; Initialize sequence number:
  mov byte [send_seq_no], 0

  ; Initialize retransmit message in send buffer:
  mov byte [send_buffer],     0x01 ; 'MARK' Start marker (Ctrl-A)
  mov byte [send_buffer + 1], 35   ; 'LEN' Packet length of 3 (+ 32)
  mov byte [send_buffer + 2], 32   ; 'SEQ' Sequence number 0 (+ 32)
  mov byte [send_buffer + 3], 'N'  ; 'TYPE' Packet type 'N' meaning NAK
  mov byte [send_buffer + 4], 0x33 ; 'CHECK' Checksum 0x13 (+ 32)
  mov byte [send_buffer + 5], 0x13 ; Terminator (Carriage Return)
  mov word [send_buffer_index], 6

  ; Get Send Initialization packet, exchange parameters...

  mov dx, message_waiting
  call print_string
  call get_valid_packet

  mov byte al, [packet_type]
  cmp al, 'S' ; 'S' = Send Initiation
  je _handle_s_packet

  ; Simplified version of error message: "<?> Packet in S State"
  mov byte [packet_data], al
  mov byte [packet_data + 1], 'S'
  mov byte [packet_type], 'E' ; 'E' = Error
  mov word [packet_data_len], 2
  call send_packet
  jmp _main_end

_handle_s_packet:
  ; Override local EOL marker from sender if available:
  mov byte al, [packet_data_len]
  cmp al, 4
  jb _acknowledge_s_packet
  mov byte bl, [packet_data + 4] ; 'EOL'
  sub bl, 32
  mov [eol_marker], bl

  ; Override local CTL marker from sender if available:
  cmp al, 5
  jb _acknowledge_s_packet
  mov byte bl, [packet_data + 5] ; 'QCTL'
  mov [ctl_marker], bl

_acknowledge_s_packet:
  mov byte [packet_type], 'Y' ; 'Y' = Acknowledgement (ACK)
  mov byte [packet_data],     72  ; 'MAXL'
  mov byte [packet_data + 1], 42  ; 'TIME'
  mov byte [packet_data + 2], 32  ; 'NPAD'
  mov byte [packet_data + 3], 64  ; 'PADC'
  mov byte [packet_data + 4], 45  ; 'EOL' = 0x0d (+ 32)
  mov byte [packet_data + 5], 35  ; 'QCTL' = '#'
  mov byte [packet_data + 6], 'N' ; 'QBIN' = 'N' = Will not do 8-bit quoting.
  mov byte [packet_data + 7], '1' ; 'CHKT' = '1' = Single character checksum.
  mov word [packet_data_len], 8
  call send_packet

_wait_for_file_header_packet:
  ; Get a File Header packet. If a B packet comes, we're all done:
  call get_valid_packet

  mov byte al, [packet_type]
  cmp al, 'B' ; 'B' = Break transmission
  je _handle_b_packet
  cmp al, 'F' ; 'F' = File Header
  je _handle_f_packet

  ; Simplified version of error message: "<?> Packet in F State"
  mov byte [packet_data], al
  mov byte [packet_data + 1], 'F'
  mov byte [packet_type], 'E' ; 'E' = Error
  mov word [packet_data_len], 2
  call send_packet
  jmp _main_end

_handle_b_packet:
  call send_acknowledgement_packet
  jmp _main_end

_handle_f_packet:
  mov dx, message_receiving
  call print_string

  ; Dollar terminate the received filename:
  mov word di, [packet_data_len]
  mov byte [packet_data + di], '$'
  mov dx, packet_data
  call print_string

  ; Zero terminate the received filename:
  mov byte [packet_data + di], 0

  ; Call DOS to create new file and handle.
  mov ah, 0x3c
  mov cx, 0 ; Standard attributes.
  ; DX already containing pointer to packet data.
  int 0x21
  jc _handle_f_packet_error
  mov [file_handle], ax

  call send_acknowledgement_packet

_wait_for_data_packet:
  ; Get Data packets. If a Z packet comes, the file is complete:
  call get_valid_packet

  mov byte al, [packet_type]
  cmp al, 'Z' ; 'Z' = End of file
  je _handle_z_packet
  cmp al, 'D' ; 'D' = Data Packet
  je _handle_d_packet

  ; Simplified version of error message: "<?> Packet in D State"
  mov byte [packet_data], al
  mov byte [packet_data + 1], 'D'
  mov byte [packet_type], 'E' ; 'E' = Error
  mov word [packet_data_len], 2
  call send_packet
  jmp _main_end

_handle_z_packet:
  ; Call DOS to close file handle.
  mov ah, 0x3e
  mov bx, [file_handle]
  int 0x21

  call send_acknowledgement_packet

  mov dx, message_ok
  call print_string

  jmp _wait_for_file_header_packet

_handle_d_packet:
  ; Call DOS to write to file.
  mov ah, 0x40
  mov word bx, [file_handle]
  mov word cx, [packet_data_len]
  mov dx, packet_data
  int 0x21
  jc _handle_d_packet_error

  call send_acknowledgement_packet

  jmp _wait_for_data_packet

_handle_f_packet_error:
  ; Send error code 'C', since new file could not be created.
  mov byte [packet_data], 'C'
  mov byte [packet_type], 'E' ; 'E' = Error
  mov word [packet_data_len], 1
  call send_packet
  jmp _main_end

_handle_d_packet_error:
  ; Send error code 'W', since new file could not be written to.
  mov byte [packet_data], 'W'
  mov byte [packet_type], 'E' ; 'E' = Error
  mov word [packet_data_len], 1
  call send_packet
  jmp _main_end

_main_end:
  mov dx, message_done
  call print_string

  ; Disable interrupt bit on COM1:
  mov dx, COM1_IER
  in al, dx
  and al, 0b11111110 ; Disable Received Data Available Interrupt
  out dx, al

  ; Exit to DOS.
  mov ah, 0x4c
  int 0x21

; PROCEDURE: get_valid_packet
;
; INPUT:
;   N/A
;
; OUTPUT:
;   ds:[packet_type]
;   ds:[packet_data]
;   ds:[packet_data_len]
;
get_valid_packet:
  push ax
  push bx
  push cx

  ; Try to get a valid packet with the desired sequence number.

  mov cx, 5 ; Retry maximum 5 times.
_get_valid_packet_loop:
  call recv_packet

  mov byte al, [recv_seq_no]
  mov byte bl, [send_seq_no]
  cmp al, bl
  jne _get_valid_packet_resend
  mov byte al, [packet_type]
  cmp al, 'Q' ; 'Q' = Block check error
  je _get_valid_packet_resend
  jmp _get_valid_packet_return ; Got a valid packet.

_get_valid_packet_resend:
  call com_port_send ; Contains a retransmit message in send buffer already.

  push dx
  mov dl, '%' ; Indicate retry.
  call print_character
  pop dx

  loop _get_valid_packet_loop ; Until CX = 0

  mov byte [packet_type], 'T' ; 'T' = Timeout

_get_valid_packet_return:
  pop cx
  pop bx
  pop ax
  ret

; PROCEDURE: send_acknowledgement_packet
;
; INPUT:
;   N/A
;
; OUTPUT:
;   N/A
;
send_acknowledgement_packet:
  mov byte [packet_type], 'Y' ; 'Y' = Acknowledgement (ACK)
  mov word [packet_data_len], 0
  call send_packet
  ret

; PROCEDURE: send_packet
;
; INPUT:
;   ds:[packet_type]
;   ds:[packet_data]
;   ds:[packet_data_len]
;   
; OUTPUT:
;   N/A
;
send_packet:
  push ax
  push bx
  push cx
  push di
  push si

  mov di, send_buffer
  mov byte [di], 0x01
  inc di

  mov word ax, [packet_data_len]
  add al, 35 ; 32 + 3 bytes for 'SEQ', 'TYPE' & 'CHECK'
  mov bl, al ; Checksum = LEN
  mov byte [di], al
  inc di

  mov byte al, [send_seq_no]
  add al, 32
  add bl, al ; Checksum += SEQ
  mov byte [di], al
  inc di

  mov byte al, [packet_type]
  add bl, al ; Checksum += TYPE
  mov byte [di], al
  inc di

  mov si, packet_data
  mov word cx, [packet_data_len]
  test cx, cx
  jz _send_packet_empty
_send_packet_loop:
  mov al, [si]
  mov [di], al
  add bl, al ; Checksum += DATA
  inc di
  inc si

  loop _send_packet_loop ; Until CX = 0
_send_packet_empty:

  ; Calculate checksum:
  mov cl, bl
  and cl, 192
  shr cl, 1 ; 8086 is limited to one shift at a time.
  shr cl, 1
  shr cl, 1
  shr cl, 1
  shr cl, 1
  shr cl, 1
  add cl, bl
  and cl, 63
  add cl, 32
  mov byte [di], cl
  inc di

  mov byte al, [eol_marker]
  mov byte [di], al

  mov word ax, [packet_data_len]
  add ax, 6 ; Add 'MARK', 'LEN', 'SEQ', 'TYPE' 'CHECK' and terminator.
  mov word [send_buffer_index], ax

  call com_port_send

  ; Increment packet sequence number:
  inc byte [send_seq_no]
  and byte [send_seq_no], 63 ; Always reduce to 6 bits.

  push dx
  mov dl, '.'; Indicate ACK sent.
  call print_character
  pop dx

  pop si
  pop di
  pop cx
  pop bx
  pop ax
  ret

; PROCEDURE: com_port_send
;
; INPUT:
;   ds:[send_buffer]
;   ds:[send_buffer_index]
;   
; OUTPUT:
;   N/A
;
com_port_send:
  push ax
  push cx
  push dx
  push si

  mov si, 0
  mov word cx, [send_buffer_index]
_com_port_send_byte:

  mov dx, COM1_THR
  mov byte al, [send_buffer + si]
  out dx, al

  mov dx, COM1_LSR
_com_port_send_wait:
  in al, dx
  and al, 0b00100000 ; Empty Transmit Holding Register
  test al, al
  jz _com_port_send_wait ; Busy wait...

  inc si
  loop _com_port_send_byte ; Until CX = 0

  pop si
  pop dx
  pop cx
  pop ax
  ret

; PROCEDURE: recv_packet
;
; INPUT:
;   N/A
;   
; OUTPUT:
;   ds:[packet_type]
;   ds:[packet_data]
;   ds:[packet_data_len]
;   ds:[recv_seq_no]
;
recv_packet:
  push ax
  push bx
  push cx
  push dx
  push di
  push si

  call com_port_recv

  ; Look for 'MARK' start marker 0x01 (Ctrl-A) in buffer:
  mov si, -1
_recv_packet_look_for_marker:
  inc si
  mov ax, [recv_buffer_index]
  cmp si, ax
  jge _recv_packet_fail ; Reached end of buffer.
  mov byte al, [recv_buffer + si]
  cmp al, 0x01 ; (Ctrl-A)
  jne _recv_packet_look_for_marker
  ; Start position now in SI register.

  ; Copy initial packet fields:
  ; * Using AL for data.
  ; * Using BL for checksum.
  ; * Using CX for packet length.
  inc si
  xor cx, cx
  mov byte cl, [recv_buffer + si] ; Packet 'LEN' field.
  mov bl, cl ; Checksum = LEN
  sub cx, 35 ; 32 + 3 bytes for 'SEQ', 'TYPE' & 'CHECK'
  inc si
  mov byte al, [recv_buffer + si] ; Packet 'SEQ' field.
  add bl, al ; Checksum += SEQ
  sub al, 32
  mov byte [recv_seq_no], al
  inc si
  mov byte al, [recv_buffer + si] ; Packet 'TYPE' field.
  add bl, al ; Checksum += TYPE
  mov byte [packet_type], al
  inc si
  ; Packet length now in CX register.
  ; Checksum now in BL register.
  ; Start of data position now in SI register.

  mov word [packet_data_len], cx
  test cx, cx
  jz _recv_packet_checksum ; Zero size packet, skip decoding/copying.

  ; Copy packet data:
  ; * Using AL for data.
  ; * Using BL for checksum.
  ; * Using CX for packet length.
  ; * Using DL for comparisons and temporary storage.
  ; * Using DH for decode flag.
  xor dh, dh
  mov di, packet_data
_recv_packet_copy:
  mov byte al, [recv_buffer + si] ; Packet 'DATA' field.
  add bl, al ; Checksum += DATA
  mov byte dl, [packet_type]
  cmp dl, 'S' ; 'S' = Send Initiation
  jne _recv_packet_decode ; Type 'S' packets shall not be decoded!
  mov [di], al ; Copy un-decoded.
  jmp _recv_packet_increment

_recv_packet_decode:
  cmp dh, 0
  jne _recv_packet_decode_flag_not_set_1
  mov byte dl, [ctl_marker]
  cmp dl, al
  jne _recv_packet_decode_flag_not_set_1
  mov dh, 1
  dec byte [packet_data_len] ; Decoding reduces resulting packet size.
  jmp _recv_packet_increment_source_only

_recv_packet_decode_flag_not_set_1:
  cmp dh, 1
  jne _recv_packet_decode_flag_not_set_2
  xor dh, dh

  mov dl, al
  and dl, 127
  cmp dl, 62
  jng _recv_packet_decode_flag_not_set_2
  cmp dl, 96
  jg _recv_packet_decode_flag_not_set_2
  xor al, 64

_recv_packet_decode_flag_not_set_2:
  mov [di], al
_recv_packet_increment:
  inc di
_recv_packet_increment_source_only:
  inc si
  loop _recv_packet_copy ; Until CX = 0

_recv_packet_checksum:
  ; Calculate and check checksum:
  mov dl, bl
  and dl, 192
  shr dl, 1 ; 8086 is limited to one shift at a time.
  shr dl, 1
  shr dl, 1
  shr dl, 1
  shr dl, 1
  shr dl, 1
  add dl, bl
  and dl, 63
  mov byte al, [recv_buffer + si] ; Packet 'CHECK' field.
  sub al, 32
  cmp al, dl
  jne _recv_packet_fail

  ; All OK!
  jmp _recv_packet_ok

_recv_packet_fail:
  mov byte [packet_type], 'Q' ; 'Q' = Block check error
_recv_packet_ok:
  pop si
  pop di
  pop dx
  pop cx
  pop bx
  pop ax
  ret

; PROCEDURE: com_port_recv
;
; INPUT:
;   N/A
;   
; OUTPUT:
;   ds:[recv_buffer]
;   ds:[recv_buffer_index]
;
com_port_recv:
  push ax
  push dx
  push di

  mov di, 0
_com_port_recv_byte:

  mov dx, COM1_IIR
_com_port_recv_wait:
  in al, dx
  and al, 0b00001110 ; Identification
  cmp al, 0b00000100 ; Enable Received Data Available Interrupt
  jne _com_port_recv_wait ; Busy wait...

  mov dx, COM1_RBR
  in al, dx

  cmp di, RECV_BUFFER_SIZE
  jb _com_port_recv_copy
  mov di, 0 ; Reset and wrap to prevent overflow.
_com_port_recv_copy:
  mov byte [recv_buffer + di], al
  inc di

  ; Keep reading until a terminator 0x0d (Carriage Return) arrives:
  cmp al, 0x0d
  jne _com_port_recv_byte

  mov word [recv_buffer_index], di

  pop di
  pop dx
  pop ax
  ret

; PROCEDURE: print_character
;
; INPUT:
;   dl
;   
; OUTPUT:
;   N/A
;
print_character:
  push ax
  push dx
  ; Call DOS to display character:
  mov ah, 0x2
  ; DL set by caller...
  int 0x21
  pop dx
  pop ax
  ret

; PROCEDURE: print_string
;
; INPUT:
;   dx
;   
; OUTPUT:
;   N/A
;
print_string:
  push ax
  ; Call DOS to display string:
  mov ah, 0x9
  ; DS is already same as CS, no need to change.
  ; DX set by caller...
  int 0x21
  pop ax
  ret

section .data:
recv_buffer_index:
  dw 0 ; 16-bit word due to SI/DI registers.
recv_buffer:
  times RECV_BUFFER_SIZE db 0

send_buffer_index:
  dw 0 ; 16-bit word due to SI/DI registers.
send_buffer:
  times SEND_BUFFER_SIZE db 0

send_seq_no:
  db 0
recv_seq_no:
  db 0

packet_type:
  db 0
packet_data_len:
  dw 0 ; 16-bit word due to SI/DI registers.
packet_data:
  times PACKET_DATA_SIZE db 0

ctl_marker:
  db '#'  ; Default
eol_marker:
  db 0x0d ; Default

file_handle:
  dw 0

message_waiting:
  db "Waiting...", 0x0d, 0x0a, "$"
message_receiving:
  db "Receiving: $"
message_ok:
  db "(OK)", 0x0d, 0x0a, "$"
message_done:
  db "(DONE)", 0x0d, 0x0a, "$"
          


For convenience, here is an example of commands to send a file with C-Kermit on Linux:

set modem type none
set line /dev/ttyUSB0
set carrier-watch off
set speed 9600
set flow none
set parity none
set stop-bits 1
send <filename>
          


Topic: Scripts and Code, by Kjetil @ 06/06-2020, Article Link

M.I.A. in Wine

M.I.A.: Missing In Action is a relatively unknown game that came out for Windows back in 1998. I got the game back then in my childhood as part of some bundle with a new computer. I do remember the game being fun, but I had issues getting it to run later on because it will only install on Windows 98. Fast forward some 20 years, Wine has now become a better Windows than Windows on Linux in many aspects, especially running older games.
I have been using Wine version 4.0.2 for these experiments.

Using some tricks I finally got to run and play this on Linux! In order to get there I had do spend some time with both Winedbg and OllyDbg debuggers to figure out what the game tried to do and failed on.

The first problem was the detection of the CDs, which I figured out it does by calling GetVolumeInformationA() and looking at the volume label. This is fixed by creating a ".windows-label" file in the emulated CD drive with the correct label.

The second problem was getting the CD audio to work correctly. Apart from having to fake this somehow, the game uses the ancient Media Control Interface which still have some missing features (bugs?) in Wine at the time of writing. Maybe this will be fixed in an upcoming version, but I had no time to wait for that. The root of the problem is that Wine returns the code (as string) "1088" instead of the string "audio" when the game asks what type of track is on the CD. The quickest way to fix this is to simply patch the game binary to look for that other string.

To actually play the CD audio without the CDs I figured out it was easiest to hack the Wine "mcicda.dll" library and make it call MPlayer to play the tracks as .FLAC files. This is done in MPlayer's FIFO mode to avoid blocking anything.

A third problem is that the in-game video cutscenes, using Smacker Video Technology still does not play correctly in Wine. The symptom is that the video may play for some seconds, but then just hangs. Since it's possible to bypass this by hitting Escape, I have simply ignored this for now.

Anyway, the common steps to install and run are as follows:
1) Create a new directory to store a Wine prefix for M.I.A.:
mkdir -p ~/opt/mia
2) Run winecfg on the prefix, in 32-bit mode, and set it has "Windows 98":
WINEARCH=win32 WINEPREFIX=~/opt/mia winecfg
3) Create two directories for each M.I.A. CD in the prefix:
mkdir ~/opt/mia/cd1
mkdir ~/opt/mia/cd2
4) Copy the CD contents into the respective directories.
Either directly from the CDs or ISO images mounted as loopback devices.
5) Create fake volume labels for each CD, as needed by the game:
echo "MIA_VOL1" > ~/opt/mia/cd1/.windows-label
echo "MIA_VOL2" > ~/opt/mia/cd2/.windows-label
6) Create a symbolic link kalled "drive_d" pointing to "cd1"
ln -s "cd1" ~/opt/mia/drive_d
7) Run winecfg again to map D: to the newly created "drive_d" directory.
Also set the type as "CD-ROM".
WINEARCH=win32 WINEPREFIX=~/opt/mia winecfg
8) Allow low memory to be mapped, since it is needed by M.I.A. installer.
sudo sysctl vm.mmap_min_addr=0
9) Start the M.I.A. installation through Wine,
WINEARCH=win32 WINEPREFIX=~/opt/mia wine ~/opt/mia/drive_d/mia.exe
10) When prompted for installation of installation type...
Select "Leave ground textures on CD".
This is needed because the installer has issues finding CD #2.
11) Run the following script to easily start the game:

#!/bin/sh
export WINEPREFIX=~/opt/mia

sudo sysctl vm.mmap_min_addr=0 # Wine needs to be allowed to map low memory.

CD_NO=0
while [ "$CD_NO" != "1" ] && [ "$CD_NO" != "2" ]; do
  read -p "CD Number? (1 or 2) " CD_NO
done

rm -f "${WINEPREFIX}/drive_d"
ln -s "cd$CD_NO" "${WINEPREFIX}/drive_d"

(cd "${WINEPREFIX}/drive_c/MIA" && WINEARCH=win32 wine miarel.exe -avhpd)
          


If you also want the in-game music, some additional steps are required:
12) Assuming all tracks are ripped from the CD's in FLAC format.
4 audio tracks from CD #1 named from "track02.flac" to "track05.flac".
5 audio tracks from CD #2 mamed from "track02.flac" to "track06.flac".
Copy .flac files into the root of each respective directory "cd1" and "cd2".
13) Patch the "mcicda.dll" file in ~/opt/mia/drive_c/windows/system32/
14) Patch the "miarel.exe" file in ~/opt/mia/drive_c/MIA/
15) Run the following modified script to start the game:

#!/bin/sh
export WINEPREFIX=~/opt/mia

MPLAYER_FIFO=/tmp/mplayer.fifo # Do not change, hardcoded in patched mcicda.dll

sudo sysctl vm.mmap_min_addr=0 # Wine needs to be allowed to map low memory.

CD_NO=0
while [ "$CD_NO" != "1" ] && [ "$CD_NO" != "2" ]; do
  read -p "CD Number? (1 or 2) " CD_NO
done

rm -f "${WINEPREFIX}/drive_d"
ln -s "cd$CD_NO" "${WINEPREFIX}/drive_d"

if [ ! -p "$MPLAYER_FIFO" ]; then
  mkfifo "$MPLAYER_FIFO"
fi

cd "${WINEPREFIX}/drive_d"
mplayer -idle -slave -input file=$MPLAYER_FIFO 1&>/dev/null &
MPLAYER_PID=$!
cd -

(cd "${WINEPREFIX}/drive_c/MIA" && WINEARCH=win32 wine miarel.exe -avhpd)

kill $MPLAYER_PID
rm -f "$MPLAYER_FIFO"
          


To patch "miarel.exe", open it in a hex-editor and go to offset 0x1427c4. At this location the string "audio" should be present. Replace this with 0x31 0x30 0x38 0x38 0x00 which represents the string "1088" with an additional NULL terminator.

Patching "mcicda.dll" is more complicated as it requires a rebuild of Wine. Get the Wine source code and apply the following source code patch to "./dlls/mcicda/mcicda.c":

--- mcicda.c.orig	2020-05-13 17:55:02.433346437 +0200
+++ mcicda.c	2020-05-13 17:54:53.230346338 +0200
@@ -25,6 +25,12 @@
 #include <stdio.h>
 #include <string.h>
 
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <unistd.h>
+#include <limits.h>
+
 #define WIN32_NO_STATUS
 #include "windef.h"
 #include "winbase.h"
@@ -79,10 +85,72 @@
 typedef HRESULT(WINAPI*LPDIRECTSOUNDCREATE)(LPCGUID,LPDIRECTSOUND*,LPUNKNOWN);
 static LPDIRECTSOUNDCREATE pDirectSoundCreate;
 
+static void mplayer_command(const char *command)
+{
+    int fd, written;
+
+    fd = open("/tmp/mplayer.fifo", O_NONBLOCK | O_WRONLY);
+    if (fd == -1) {
+        TRACE("No pipe\n");
+        return;
+    }
+
+    written = write(fd, command, strlen(command));
+    if (written <= 0) {
+        TRACE("Write failed\n");
+    }
+
+    close(fd);
+}
+
 static BOOL device_io(HANDLE dev, DWORD code, void *inbuffer, DWORD insize, void *outbuffer, DWORD outsize, DWORD *retsize, OVERLAPPED *overlapped)
 {
     const char *str;
-    BOOL ret = DeviceIoControl(dev, code, inbuffer, insize, outbuffer, outsize, retsize, overlapped);
+//    BOOL ret = DeviceIoControl(dev, code, inbuffer, insize, outbuffer, outsize, retsize, overlapped);
+
+    int i;
+    BOOL ret = TRUE;
+    CDROM_TOC *toc;
+
+    *retsize = 0;
+
+    switch (code) {
+    case IOCTL_CDROM_READ_TOC:
+        toc = (CDROM_TOC *)outbuffer;
+
+        toc->FirstTrack = 1;
+        toc->LastTrack = 6;
+
+        // Set up first track as data track.
+        toc->TrackData[0].TrackNumber = 1;
+        toc->TrackData[0].Control = 0x4;
+        toc->TrackData[0].Address[1] = 0;
+        toc->TrackData[0].Address[2] = 0;
+        toc->TrackData[0].Address[3] = 0;
+
+        // Set up remaining tracks as dummy audio tracks.
+        for (i = 1; i < toc->LastTrack; i++) {
+            toc->TrackData[i].TrackNumber = i + 1;
+            toc->TrackData[i].Control = 0;
+            toc->TrackData[i].Address[1] = i;
+            toc->TrackData[i].Address[2] = 0;
+            toc->TrackData[i].Address[3] = 0;
+        }
+
+        *retsize = CDROM_TOC_SIZE;
+        break;
+
+    case IOCTL_CDROM_STOP_AUDIO:
+        mplayer_command("stop\n");
+        break;
+
+    case IOCTL_CDROM_PAUSE_AUDIO:
+        mplayer_command("stop\n");
+        break;
+
+    default:
+        break;
+    }
 
 #define XX(x) case (x): str = #x; break
     switch (code)
@@ -906,6 +974,9 @@
     SUB_Q_CHANNEL_DATA          data;
     CDROM_TOC			toc;
 
+    int track_no;
+    char command[PATH_MAX];
+
     TRACE("(%04X, %08X, %p);\n", wDevID, dwFlags, lpParms);
 
     if (lpParms == NULL)
@@ -914,6 +985,20 @@
     if (wmcda == NULL)
 	return MCIERR_INVALID_DEVICE_ID;
 
+    // HIJACK START
+
+    mplayer_command("stop\n");
+
+    track_no = MCI_TMSF_TRACK(lpParms->dwFrom);
+    TRACE("Track no: %d\n", track_no);
+
+    snprintf(command, PATH_MAX, "loadfile track%02d.flac\n", track_no);
+    mplayer_command(command);
+
+    return 0;
+
+    // HIJACK END
+
     if (!MCICDA_ReadTOC(wmcda, &toc, &br))
         return MCICDA_GetError(wmcda);
          

To build the DLL file, it should be enough to run ./configure and make on the Wine source code. The resulting file will be named "mcicda.dll.so" but can be renamed to "mcicda.dll".

Topic: Configuration, by Kjetil @ 24/05-2020, Article Link

Amiga 500 Capacitor Replacement

I recently replaced all the electrolytic capacitors on my Commodore Amiga 500. This was originally for troubleshooting and diagnostics purposes, but sometimes it is a good idea anyway because electrolytic capacitors are prone to drying up and become worse over time. I understand that this varies a lot between manufacturers and production batches, so it's not always the case. As for the Amiga 500, there seems to be some dispute.

Anyway, in this process I had to come up with a easy way to track the work while soldering. So I made this "map" with all the capacitors and their values. It might be helpful to others later:

Amiga 500 Capacitor Locations


Note that this is a Amiga 500 revision 5 board, so others might be different.

Topic: Repair, by Kjetil @ 01/05-2020, Article Link

Dell 2005FPW Display Resolution Fix

I have an old Dell 2005FPW LCD display from around 2005. I had some problems getting this to display the native 1680x1050 resolution in Linux. Instead it would always want to display 1280x1024, and everything would look ugly. The cause of this seems to be bad EDID data being sent by the monitor, because I managed to fix it by manually creating a EDID firmware file with a resolution of 1680x1050 and the refresh rate forced to 59Hz, instead of the more common 60Hz.

There is a nice piece of software here on GitHub to create EDID firmware files from X modeline configuration. I used this together with this handy Online modeline generator.

Here is the modeline generated from the online tool:

# 1680x1050 @ 59.00 Hz (GTF) hsync: 64.07 kHz; pclk: 144.55 MHz
Modeline "1680x1050_59.00" 144.55 1680 1784 1968 2256 1050 1051 1054 1086 -HSync +Vsync
          


I had to trim away the excess ".00" from the string, or else the EDID firwmare file would be too big, 131 bytes instead of 128 bytes, so this should be the actual input to the 'modeline2edid' tool in the EDID generator package:

Modeline "1680x1050_59" 144.55 1680 1784 1968 2256 1050 1051 1054 1086 -HSync +Vsync
          


For reference, here is a hexdump of the newly created EDID firmware:

00000000  00 ff ff ff ff ff ff 00  31 d8 00 00 00 00 00 00  |.ÿÿÿÿÿÿ.1Ø......|
00000010  05 16 01 03 6d 2b 1b 78  ea 5e c0 a4 59 4a 98 25  |....m+.xê^À¤YJ.%|
00000020  20 50 54 00 00 00 b3 00  01 01 01 01 01 01 01 01  | PT...³.........|
00000030  01 01 01 01 01 01 77 38  90 40 62 1a 24 40 68 b8  |......w8.@b.$@h¸|
00000040  13 00 b5 11 11 00 00 1e  00 00 00 ff 00 4c 69 6e  |..µ........ÿ.Lin|
00000050  75 78 20 23 30 0a 20 20  20 20 00 00 00 fd 00 3b  |ux #0.    ...ý.;|
00000060  3d 3f 41 0f 00 0a 20 20  20 20 20 20 00 00 00 fc  |=?A...      ...ü|
00000070  00 31 36 38 30 78 31 30  35 30 5f 35 39 0a 00 e1  |.1680x1050_59..á|
          


The file needs to be loaded by putting it in /lib/firmware/edid/ and adding this to the Linux boot kernel parameters:

drm.edid_firmware=edid/1680x1050.bin
          


After this, the resolution became correct in both the framebuffer console and X on the computer where I use this LCD display. The computer has a NVIDIA GeForce FX 5200 graphics gard with the "nouveau" driver in use.

Topic: Configuration, by Kjetil @ 02/04-2020, Article Link

NCR System 3330 Dallas RTC Mod

The Dallas DS12887 RTC inside my NCR System 3330 PC had died a long time ago. Unfortunately, this made the machine unbootable from the hard drive, since it would forget the hard drive settings on each restart. Instead of finding a replacement, like for the Commodore PC 30-III, I opted for the external battery modification instead. I got this working with just two regular AA 1.5V alkaline batteries, a huge success!

The initial error on every startup was as follows:

NCR Battery Power Lost


Fortunately, the Dallas RTC is a in a socket on this machine, easily extracted:

NCR Dallas RTC Extracted


To perform the mod, two sections of the case needs to be opened, which I did with a Dremel tool:

NCR Dallas RTC Dremeled


Afterwards, it's possible to solder on leads for a new battery:

NCR Dallas RTC with new battery leads


I installed a new 2xAA battery holder inside the case, connected to the RTC:

NCR Dallas RTC external battery


The machine is now working again, settings can be saved to CMOS and booting from hard drive is possible:

NCR Powered On


Topic: Repair, by Kjetil @ 14/03-2020, Article Link

Reverse SSH Tunnel Listener

The Reverse SSH Tunnel Launcher script I posted a while ago has some limitations. The worst part is that the tunnel is only open for 5 minutes, leaving too little time to get any work done. This is kind of by design, to prevent having these connections open and "live" when not in use.

The solution to this limitation is another small script, this time just hacked together as a Bourne shell script. Take a look:

#!/bin/sh

while /bin/true; do
  if /bin/netstat -tln | fgrep 127.0.0.1:1337 > /dev/null; then
    ssh localhost -p 1337 screen -d -m ssh -v -R 1338:localhost:22 -N -p 22 192.168.0.1
    echo "New tunnel established!"
    exit
  fi
  sleep 10
done
          


This script will loop forever and wait for a socket to appear on the port (1337) opened by the original launcher. Once this happens, a new tunnel is created (on port 1338) in parallel which will persist forever through a screen session.

Topic: Scripts and Code, by Kjetil @ 02/02-2020, Article Link

Strawman

This is a game project I have had lying around for many years, which I finally made into something usable. The initial idea was to make a side-scroller using the SDL library, and the project codename was "Strawman", so that just became the title as well.

The end result is a highly configurable yet simple game. The map data is stored in a text file and can be easily changed. The "game engine" itself is configured through a bunch of #define macros.

Here's a screenshot:

Strawman screenshot


And the corresponding part of the map data, rotated by 90 degrees on purpose, so adding more lines makes the map longer horizontally:

#
# P
#
###
###  #  CCC
###  #E CCC
###  #  CCC
###
#
#E
#
#
#
##

        # CC
#       # CC
##      # CC
###
####
          


The source code is released under the MIT license and can be downloaded here.

Topic: Open Source, by Kjetil @ 01/01-2020, Article Link