diff --git a/build/conf/local.conf b/build/conf/local.conf index c4d666646f..ee193eae21 100644 --- a/build/conf/local.conf +++ b/build/conf/local.conf @@ -8,6 +8,7 @@ BB_NUMBER_THREADS = "20" IB_PLATFORM ?= "virt64" # IB_PLATFORM ?= "rpi4_64" # IB_PLATFORM ?= "verdin-imx8mp" +# IB_PLATFORM ?= "pc64" # On the QEMU-emulated platforms (virt32/virt64) a full BSP build # (build.sh bsp-so3 / bsp-linux) also builds the QEMU emulator when its binary @@ -47,6 +48,7 @@ IB_BUILD_QEMU ?= "1" PREFERRED_VERSION_so3:virt32 = "6.4.0" PREFERRED_VERSION_so3:virt64 = "6.4.0" PREFERRED_VERSION_so3:rpi4_64 = "6.4.0" +PREFERRED_VERSION_so3:pc64 = "6.4.0" # --- Configs (kernel defconfig) --- # standalone and guest share the plain defconfig; capsule has its own. @@ -56,6 +58,7 @@ PREFERRED_VERSION_so3:rpi4_64 = "6.4.0" IB_CONFIG:so3:virt64 ?= "virt64_fb_defconfig" IB_CONFIG:so3:virt32 ?= "virt32_fb_defconfig" IB_CONFIG:so3:rpi4_64 ?= "rpi4_64_defconfig" +IB_CONFIG:so3:pc64 ?= "pc64_defconfig" # --- ITS (boot-image selection) --- # virt64: pick exactly ONE of standalone / guest / capsule. @@ -136,6 +139,12 @@ IB_CONFIG:avz:verdin-imx8mp ?= "verdin-imx8mp_avz_defconfig" IB_BOOT_CHAIN ?= "uboot" +# x86 PC (QEMU): GRUB loads SO3, its device tree and its root filesystem as +# multiboot2 modules, from the boot partition of the disk image. + +IB_BOOT_CHAIN:pc64 = "grub" +IB_BOOT_STAGES_SUPPORTED:pc64 = "grub" + # ATF / OP-TEE platform identifiers for QEMU virt (used on the chains that # carry them). Mirrors edgem1's virt64 settings. @@ -270,6 +279,7 @@ IB_STORAGE_MODE:virt64 ?= "soft" # IB_STORAGE_MODE:verdin-imx8mp ?= "hard" IB_STORAGE_MODE:virt32 ?= "soft" +IB_STORAGE_MODE:pc64 ?= "soft" IB_STORAGE_MODE:rpi4_64 ?= "hard" # Verdin: deploy the imx-boot + SO3 ITB via a TEZI image set (see bsp_verdin-imx8mp.inc) @@ -306,6 +316,7 @@ IB_ROOTFS_SIZE ?= "2G" # Target partition for the main rootfs IB_ROOTFS_PARTITION:virt32 = "p2" +IB_ROOTFS_PARTITION:pc64 = "p2" IB_ROOTFS_PARTITION:virt64 = "p2" IB_ROOTFS_PARTITION:rpi4_64 = "p2" @@ -322,6 +333,8 @@ IB_PLAT_CPU:virt32 = "arm" IB_PLAT_CPU:virt64 = "aarch64" IB_PLAT_CPU:rpi4_64 = "aarch64" +IB_PLAT_CPU:pc64 = "x86_64" + IB_TOOLCHAIN:arm = "arm-linux-gnueabihf" IB_TOOLCHAIN:virt64 = "aarch64-none-linux-gnu" IB_TOOLCHAIN:rpi4_64 = "aarch64-none-linux-gnu" @@ -334,6 +347,7 @@ IB_TOOLCHAIN:rpi4_64 = "aarch64-none-linux-gnu" IB_MUSL_TOOLCHAIN_DIR = "${TMPDIR}/toolchains" IB_MUSL_TARGET:aarch64 = "aarch64-linux-musl" IB_MUSL_TARGET:arm = "arm-linux-musleabihf" +IB_MUSL_TARGET:x86_64 = "x86_64-linux-musl" # Debug options # IB_USR_BUILD_TYPE = "Release" diff --git a/build/meta-bsp/classes/bsp.bbclass b/build/meta-bsp/classes/bsp.bbclass index 3529a1c68b..4339ca508c 100644 --- a/build/meta-bsp/classes/bsp.bbclass +++ b/build/meta-bsp/classes/bsp.bbclass @@ -152,10 +152,12 @@ do_deploy_boot_chain[nostamp] = "1" # filesystem:do_fs_check because a chain may write its first stage into the # raw area of the card (bsp_virt64.inc, IB_FIRST_STAGE_FROM_CARD): on a fresh # tree the storage image must exist before, not be created by do_deploy after. -do_deploy_boot_chain[depends] = "uboot:do_build filesystem:do_fs_check" +do_deploy_boot_chain[depends] = "filesystem:do_fs_check" python () { extra = [] + if d.getVar('IB_CHAIN_HAS_UBOOT'): + extra.append("uboot:do_build") if d.getVar('IB_CHAIN_HAS_ATF'): extra.append("atf:do_build") if d.getVar('IB_CHAIN_HAS_OPTEE'): diff --git a/build/meta-bsp/recipes-bsp/bsp/files/bsp_pc64.inc b/build/meta-bsp/recipes-bsp/bsp/files/bsp_pc64.inc new file mode 100644 index 0000000000..9bc4486db8 --- /dev/null +++ b/build/meta-bsp/recipes-bsp/bsp/files/bsp_pc64.inc @@ -0,0 +1,83 @@ +# Copyright (c) 2026 EDGEMTech SA + +# Deployment on the QEMU x86_64 PC (pc64). +# +# GRUB plays the part of U-Boot: its core image sits right after the MBR, +# ahead of p1, and it loads the SO3 ELF with the device tree and the root +# filesystem as multiboot2 modules, all three read from p1. There is no ITB. + +IB_PC64_GRUB_MODULES = "biosdisk part_msdos fat multiboot2 normal configfile serial terminal echo test" + +do_itb:pc64 () { + bbnote "pc64: no ITB, GRUB loads the kernel, the device tree and the rootfs from p1" +} + +def __pc64_grub_cfg(): + return ("set timeout=0\n" + "serial --unit=0 --speed=115200\n" + "terminal_input serial console\n" + "terminal_output serial console\n" + "\n" + "menuentry \"SO3 (pc64)\" {\n" + "\tmultiboot2 /so3.elf\n" + "\tmodule2 /pc64.dtb dtb\n" + "\tmodule2 /rootfs.fat rootfs\n" + "}\n") + +def __do_platform_boot_chain(d): + """Install GRUB in the raw area of the disk image: boot.img in the MBR + code area (the partition table is left alone) and the core image from + sector 1, where boot.img and the core image's own blocklist expect it by + default. The core image embeds every module it needs, so p1 only holds + grub.cfg.""" + import os + import subprocess + + fs_dir = os.path.join(d.getVar('IB_DIR'), "filesystem") + store = os.path.join(fs_dir, "work", "sdcard.img.%s" % d.getVar('IB_PLATFORM')) + grub_dir = "/usr/lib/grub/i386-pc" + core = os.path.join(fs_dir, "grub-core.img") + + if not os.path.isfile(store): + bb.fatal("no storage image at %s — run init_storage.sh first" % store) + + if not os.path.isfile(os.path.join(grub_dir, "boot.img")): + bb.fatal("%s/boot.img is missing: install grub-pc-bin" % grub_dir) + + subprocess.run(["grub-mkimage", "-O", "i386-pc", "-d", grub_dir, "-o", core, + "-p", "(hd0,msdos1)/boot/grub"] + d.getVar('IB_PC64_GRUB_MODULES').split(), + check=True) + + # p1 starts at 1 MiB (fs_arm_common): the core image must end before. + + if 512 + os.path.getsize(core) > 1024 * 1024: + bb.fatal("GRUB core image too big for the gap before p1") + + subprocess.run(["dd", "if=%s/boot.img" % grub_dir, "of=%s" % store, "bs=440", "count=1", + "conv=notrunc,fsync"], check=True) + subprocess.run(["dd", "if=%s" % core, "of=%s" % store, "bs=512", "seek=1", + "conv=notrunc,fsync"], check=True) + +def __do_platform_deploy(d): + import os + import shutil + + p1 = d.getVar('IB_FILESYSTEM_PATH') + "/p1" + so3 = os.path.join(d.getVar('IB_SO3_PATH'), "so3") + + files = { + os.path.join(so3, "so3"): "so3.elf", + os.path.join(so3, "dts", "pc64.dtb"): "pc64.dtb", + os.path.join(d.getVar('IB_ROOTFS_PATH'), "rootfs.fat"): "rootfs.fat", + } + + for src, dst in files.items(): + if not os.path.isfile(src): + bb.fatal(src + " is missing ...") + + shutil.copyfile(src, os.path.join(p1, dst)) + + os.makedirs(os.path.join(p1, "boot", "grub"), exist_ok=True) + + with open(os.path.join(p1, "boot", "grub", "grub.cfg"), "w") as f: + f.write(__pc64_grub_cfg()) diff --git a/build/meta-bsp/recipes-bsp/bsp/files/bsp_x86-qemu.inc b/build/meta-bsp/recipes-bsp/bsp/files/bsp_x86-qemu.inc deleted file mode 100644 index 84bb1e385a..0000000000 --- a/build/meta-bsp/recipes-bsp/bsp/files/bsp_x86-qemu.inc +++ /dev/null @@ -1,10 +0,0 @@ -# Copyright (c) 2025-2026 EDGEMTech SA - -# Deployment on a QEMU/x86 PC compatible platform - - -def __do_platform_deploy(d): - - print("Deploying on x86_qemu platform ...") - - diff --git a/build/meta-bsp/recipes-bsp/so3/bsp-so3_1.0.0.bb b/build/meta-bsp/recipes-bsp/so3/bsp-so3_1.0.0.bb index 4b42e7171c..48d4d4c623 100644 --- a/build/meta-bsp/recipes-bsp/so3/bsp-so3_1.0.0.bb +++ b/build/meta-bsp/recipes-bsp/so3/bsp-so3_1.0.0.bb @@ -34,6 +34,7 @@ do_attach_infrabase[noexec] = "1" # U-Boot) by the uboot recipe. verdin additionally needs the AVZ hypervisor # (bundled by the AVZ+SO3 ITS), so its dependency set is overridden to add it. IB_BSP_BUILD_DEPENDS = "usr-so3:do_build uboot:do_build" +IB_BSP_BUILD_DEPENDS:pc64 = "usr-so3:do_build so3:do_build" IB_BSP_BUILD_DEPENDS:verdin-imx8mp = "usr-so3:do_build uboot:do_build avz:do_build" do_build[depends] = "${IB_BSP_BUILD_DEPENDS}" diff --git a/build/meta-filesystem/classes/fs_pc64.bbclass b/build/meta-filesystem/classes/fs_pc64.bbclass new file mode 100644 index 0000000000..1043a0ff12 --- /dev/null +++ b/build/meta-filesystem/classes/fs_pc64.bbclass @@ -0,0 +1,6 @@ +# Copyright (c) 2026 EDGEMTech SA + +# Storage of the x86 PC: same layout as the ARM platforms, p1 (FAT, boot) +# starting at 1 MiB leaves room for the GRUB core image after the MBR. + +inherit fs_arm_common diff --git a/build/meta-filesystem/classes/fs_x86-pc.bbclass b/build/meta-filesystem/classes/fs_x86-pc.bbclass deleted file mode 100644 index d4ac1c2e04..0000000000 --- a/build/meta-filesystem/classes/fs_x86-pc.bbclass +++ /dev/null @@ -1,71 +0,0 @@ -# Copyright (c) 2025-2026 EDGEMTech SA - -# TODO: move to a Python function - -# Specific task description for formatting -# the storage of x86 platform with one partition. -# -# bitbake runs unprivileged; each privileged tool is invoked with -# `sudo -n` and assumes the caller pre-opened a sudo session. - -do_filesystem_platform_init_storage () { - - # Partition layout is as follows: - # - Partition #1: 8 GB with rootfs including kernel image and GRUB - - if [ "${IB_STORAGE_MODE}" = "soft" ]; then - # Create image first - bbnote "Creating sdcard.img.${IB_PLATFORM} ..." - - dd_size=512M - - truncate -s $dd_size ${WORKDIR}/sdcard.img.${IB_PLATFORM} - - devname=$(sudo -n losetup --partscan --find --show ${WORKDIR}/sdcard.img.${IB_PLATFORM}) - - # Keep device name only without /dev/ - devname=${devname#"/dev/"} - - bbnote "Linking the storage image ${IB_DIR}" - - mkdir -p ${WORKDIR}/filesystem - - ln -fs ${WORKDIR}/sdcard* ${IB_DIR}/filesystem/ - - else - devname=${IB_DEVICE:${IB_PLATFORM}} - fi - - bbnote "devname is defined as $devname" - - # Create the partition layout this way - - sudo -n parted -s /dev/"$devname" mklabel msdos mkpart primary ext4 1MiB 100% - - bbnote Waiting... - - # Give a chance to the real SD-card to be sync'd - sleep 2s - - if [[ "$devname" = *[0-9] ]]; then - export devname="${devname}p" - fi - - set +e - - sudo -n mke2fs -F -t ext4 /dev/"$devname"1 - sudo -n e2label /dev/"$devname"1 rootfs - - set -e - - # Only this image's loop devices: -D would detach every one on the - # host (see utils_loop_detach in utils.bbclass). - if [ "${IB_STORAGE_MODE}" = "soft" ]; then - for dev in $(sudo -n losetup --noheadings --output NAME \ - --associated ${WORKDIR}/sdcard.img.${IB_PLATFORM}); do - sudo -n losetup --detach "$dev" - done - fi - - bbnote "Done! The storage is now initialized" -} diff --git a/build/meta-filesystem/classes/fs_x86-qemu.bbclass b/build/meta-filesystem/classes/fs_x86-qemu.bbclass deleted file mode 100644 index ead0466f19..0000000000 --- a/build/meta-filesystem/classes/fs_x86-qemu.bbclass +++ /dev/null @@ -1,73 +0,0 @@ -# Copyright (c) 2025-2026 EDGEMTech SA - -# Specific task description for formatting -# the storage of QEMU/x86 platform with one partition. -# -# bitbake runs unprivileged; root ops go through utils_sudo (`sudo -n`). - -def do_filesystem_platform_init_storage(d): - - import os - import subprocess - - IB_STORAGE_MODE = d.getVar('IB_STORAGE_MODE') - IB_PLATFORM = d.getVar('IB_PLATFORM') - IB_DIR = d.getVar('IB_DIR') - WORKDIR = d.getVar('WORKDIR') - - store_filename = "sdcard.img." + IB_PLATFORM - - # Partition layout is as follows: - # - Partition #1: 8 GB with rootfs including kernel image and GRUB - - if IB_STORAGE_MODE != "soft": - raise ValueError("Cannot be a hard storage deployment ...") - - # Create image first - print("Creating " + store_filename) - - dd_size = "8G" - - subprocess.run(["truncate", "-s", dd_size, os.path.join(WORKDIR, store_filename)]) - - devname = utils_sudo(["losetup", "--partscan", "--find", "--show", - os.path.join(WORKDIR, "sdcard.img.{}".format(IB_PLATFORM))], - capture_output=True, text=True).stdout.strip() - - # Keep device name only without /dev/ - devname = devname.replace("/dev/", "") - - print("devname is defined as", devname) - - print("Linking the storage image", IB_DIR) - - os.makedirs(os.path.join(IB_DIR, "filesystem"), exist_ok=True) - - target_link = os.path.join(IB_DIR, "filesystem/"+store_filename) - source_link = os.path.join(WORKDIR, store_filename) - - # Check if the symbolic link already exists - if os.path.islink(target_link): - # Remove the existing symbolic link - os.unlink(target_link) - - os.symlink(source_link, target_link) - - # Create the partition layout this way - fdisk_input = "o\nn\np\n\n\n\n\n\nw\n" - utils_sudo(["fdisk", "/dev/{}".format(devname)], input=fdisk_input.encode()) - - print("Waiting ...") - - # Give a chance to the real SD-card to be sync'd - time.sleep(1) - - if devname[-1].isdigit(): - devname += "p" - - utils_sudo(["mke2fs", "-F", "-t", "ext4", "/dev/{}1".format(devname)]) - utils_sudo(["e2label", "/dev/{}1".format(devname), "rootfs"]) - - utils_loop_detach(os.path.join(WORKDIR, store_filename)) - - print("Done! The storage is now initialized") diff --git a/build/meta-linux/recipes-linux/linux/linux_6.12.bb b/build/meta-linux/recipes-linux/linux/linux_6.12.bb index e42e41e4e6..b11dccf9f4 100644 --- a/build/meta-linux/recipes-linux/linux/linux_6.12.bb +++ b/build/meta-linux/recipes-linux/linux/linux_6.12.bb @@ -44,20 +44,15 @@ do_build () { cd ${IB_TARGET} - if [ "${IB_PLATFORM}" = "x86-qemu" -o "${IB_PLATFORM}" = "x86-pc" ]; then - make -j${CORES} bzImage + if [ "${IB_PLATFORM}" = "bbb" ]; then + make -j${CORES} zImage else - - if [ "${IB_PLATFORM}" = "bbb" ]; then - make -j${CORES} zImage - else - make ${IB_KMAKE_ARGS} -j${CORES} Image - fi - - # Compile the device tree files - make ${IB_KMAKE_ARGS} dtbs + make ${IB_KMAKE_ARGS} -j${CORES} Image fi + # Compile the device tree files + make ${IB_KMAKE_ARGS} dtbs + } do_clean[nostamp] = "1" diff --git a/build/meta-qemu/classes/qemu.bbclass b/build/meta-qemu/classes/qemu.bbclass index b9062ffa94..f4518d738c 100644 --- a/build/meta-qemu/classes/qemu.bbclass +++ b/build/meta-qemu/classes/qemu.bbclass @@ -15,7 +15,7 @@ qemu_do_configure () { # Fixed order, so the same targets always give the same configure line. tlist="" - for t in arm-softmmu aarch64-softmmu; do + for t in arm-softmmu aarch64-softmmu x86_64-softmmu; do if [ "$t" = "${QEMU_TARGET}" ] || ls build/$t/qemu-system-* >/dev/null 2>&1; then tlist="${tlist:+$tlist,}$t" fi diff --git a/build/meta-qemu/recipes-qemu/qemu/qemu_8.2.2.bb b/build/meta-qemu/recipes-qemu/qemu/qemu_8.2.2.bb index d1d3f2eafd..282cb2c138 100644 --- a/build/meta-qemu/recipes-qemu/qemu/qemu_8.2.2.bb +++ b/build/meta-qemu/recipes-qemu/qemu/qemu_8.2.2.bb @@ -43,6 +43,7 @@ IB_UPDIFF_EXCLUDE = "build subprojects GNUmakefile" QEMU_TARGET:virt32 = "arm-softmmu" QEMU_TARGET:virt64 = "aarch64-softmmu" +QEMU_TARGET:pc64 = "x86_64-softmmu" QEMU_OPTS = "--enable-slirp --disable-attr --disable-werror --disable-docs --enable-sdl" do_clean[nostamp] = "1" diff --git a/build/meta/classes/base.bbclass b/build/meta/classes/base.bbclass index a74d94738c..9132aabfdb 100644 --- a/build/meta/classes/base.bbclass +++ b/build/meta/classes/base.bbclass @@ -27,6 +27,8 @@ THISDIR = "${@os.path.dirname(d.getVar('FILE'))}" # # atf + optee + uboot + avz + mcuboot # +# or "grub" alone on x86, where GRUB loads the payload instead of U-Boot. +# # So "uboot" is U-Boot alone, "atf+optee+uboot+avz" is the edge-m1 capsule # chain, "uboot+mcuboot" is U-Boot handing over to MCUboot, and "mcuboot" is # MCUboot as the first stage with no U-Boot at all. @@ -77,7 +79,7 @@ def ib_normalize_boot_axes(d): # boot failures came from them disagreeing: a CI cell whose ITS name said # one thing and whose deploy said another, and twice a guest ITB carrying # a bootloader's payload as though it were bootable on its own. - STAGES = ("atf", "optee", "uboot", "avz", "mcuboot") + STAGES = ("atf", "optee", "grub", "uboot", "avz", "mcuboot") # What each stage requires of the ones before it. A chain is valid when # its stages are a subsequence of STAGES and every requirement is met. @@ -125,9 +127,14 @@ def ib_normalize_boot_axes(d): bb.fatal("IB_BOOT_CHAIN=\"%s\": \"%s\" needs %s in the chain." % (chain, stage, " and ".join('"%s"' % m for m in missing))) - if "uboot" not in stages and "mcuboot" not in stages: + # GRUB is the x86 counterpart of U-Boot: one or the other, never both. + + if "grub" in stages and len(stages) > 1: + bb.fatal("IB_BOOT_CHAIN=\"%s\": \"grub\" runs alone." % chain) + + if "uboot" not in stages and "mcuboot" not in stages and "grub" not in stages: bb.fatal("IB_BOOT_CHAIN=\"%s\" has nothing that can enter a payload.\n" - "A chain needs \"uboot\" or \"mcuboot\"." % chain) + "A chain needs \"uboot\", \"mcuboot\" or \"grub\"." % chain) chain = "+".join(stages) diff --git a/docker/build-env/packages.txt b/docker/build-env/packages.txt index 180227bfc6..86525e9d94 100644 --- a/docker/build-env/packages.txt +++ b/docker/build-env/packages.txt @@ -150,6 +150,13 @@ gcc-arm-linux-gnueabihf g++-arm-linux-gnueabihf gcc-arm-none-eabi +# --- x86 PC (pc64) ----------------------------------------------------- +# GRUB for the pc64 disk image: grub-mkimage builds the core image, and +# boot.img goes into the MBR. + +grub-pc-bin +grub-common + # --- documentation ------------------------------------------------------ # `dbuild.sh make -C doc html` builds doc/ (Sphinx + the Read the Docs theme), # so the doc toolchain lives here too and nothing has to be installed on a diff --git a/scripts/build.sh b/scripts/build.sh index 45e574c368..36ba4c80e5 100755 --- a/scripts/build.sh +++ b/scripts/build.sh @@ -47,7 +47,7 @@ pr_help() printf "$progname -x usr-so3 Build the SO3 user space\n" printf "$progname bsp-so3 Build the full SO3 BSP\n" printf "$progname -v -c bsp-so3 Clean and rebuild the BSP, verbose\n\n" - printf "On virt32/virt64, a BSP build (bsp-so3/bsp-linux) also builds QEMU when its\n" + printf "On virt32/virt64/pc64, a BSP build (bsp-so3/bsp-linux) also builds QEMU when its\n" printf "binary is still missing, so the tree is runnable with st.sh right away.\n" printf "Set IB_BUILD_QEMU=\"0\" in build/conf/local.conf to skip that.\n" } @@ -182,7 +182,7 @@ localconf_get() | tail -1 | awk -F'"' '{print $2}' } -# On the QEMU-emulated platforms (virt32/virt64), a full BSP build should yield +# On the QEMU-emulated platforms (virt32/virt64/pc64), a full BSP build should yield # a runnable emulator without a separate `build.sh qemu` step. Build QEMU here # when its binary is still missing — a bootstrap only: an already-built emulator # is left untouched, so the inner build loop pays nothing and the qemu-hacking @@ -204,6 +204,7 @@ maybe_bootstrap_qemu() case "$(localconf_get IB_PLATFORM)" in virt64) _qbin="qemu-system-aarch64" ;; virt32) _qbin="qemu-system-arm" ;; + pc64) _qbin="qemu-system-x86_64" ;; *) return 0 ;; esac diff --git a/scripts/st.sh b/scripts/st.sh index 687f96053a..b0220e282f 100755 --- a/scripts/st.sh +++ b/scripts/st.sh @@ -56,7 +56,7 @@ done set -- "${POSARGS[@]}" USR_OPTION=$1 # QEMU_BIN is selected per IB_PLATFORM below (qemu-system-aarch64 for -# virt64, qemu-system-arm for virt32). +# virt64, qemu-system-arm for virt32, qemu-system-x86_64 for pc64). # One guest at a time. Every instance attaches the same disk image with # file.locking=off, so a second one writes into the filesystem the first is @@ -259,6 +259,24 @@ launch_qemu() { fi + if [ "$IB_PLATFORM" == "pc64" ]; then + QEMU_BIN="$IB_ROOT_DIR/qemu/build/qemu-system-x86_64" + echo Starting on pc64 + # SO3 on a QEMU PC: GRUB in the MBR of the disk image boots SO3 from p1 + # (bsp_pc64.inc), on COM1 muxed onto stdio. Single CPU: the x86 port is + # uniprocessor. isa-debug-exit lets the root process end QEMU. + ${QEMU_BIN} $@ ${USR_OPTION} \ + -chardev stdio,id=char0,mux=on,signal=off \ + -mon chardev=char0 \ + -serial chardev:char0 \ + -M pc \ + -drive file=filesystem/sdcard.img.pc64,format=raw,file.locking=off \ + -m 512 \ + ${DISPLAY_OPT} \ + -device isa-debug-exit \ + -gdb tcp::${GDB_PORT} + fi + QEMU_RESULT=$? } diff --git a/so3/so3/Makefile b/so3/so3/Makefile index fb38c6ddfd..00969075fd 100644 --- a/so3/so3/Makefile +++ b/so3/so3/Makefile @@ -317,13 +317,13 @@ KBUILD_CPPFLAGS += -I$(saved-output)include -I$(srctree)/include -I$(srctree)/in KBUILD_CPPFLAGS += -fno-builtin -ffreestanding -nostdinc -isystem $(gccincdir) KBUILD_CFLAGS := -g -O0 -fno-common -Wall -Wstrict-prototypes $(KBUILD_CPPFLAGS) -KBUILD_CFLAGS := -mlittle-endian -Wall -Wundef -Wstrict-prototypes -Wno-trigraphs -fno-strict-aliasing -fno-common -Werror-implicit-function-declaration -Wno-format-security -std=gnu89 -fno-PIE -fno-dwarf2-cfi-asm -fno-ipa-sra -funwind-tables -fno-delete-null-pointer-checks -Wno-frame-address -Wframe-larger-than=1024 \ +KBUILD_CFLAGS := -Wall -Wundef -Wstrict-prototypes -Wno-trigraphs -fno-strict-aliasing -fno-common -Werror-implicit-function-declaration -Wno-format-security -std=gnu89 -fno-PIE -fno-dwarf2-cfi-asm -fno-ipa-sra -funwind-tables -fno-delete-null-pointer-checks -Wno-frame-address -Wframe-larger-than=1024 \ -fno-stack-protector -Wno-unused-but-set-variable -Wno-unused-const-variable -fomit-frame-pointer -fno-var-tracking-assignments -g -Wdeclaration-after-statement -Wno-pointer-sign -fno-strict-overflow -fno-merge-all-constants -fmerge-constants -fno-stack-check -fconserve-stack \ -Werror=implicit-int -Werror=strict-prototypes -Werror=date-time -Werror=incompatible-pointer-types -Werror=designated-init -fno-function-sections -fno-data-sections KBUILD_AFLAGS_KERNEL := -I. -I$(srctree)/. KBUILD_CFLAGS_KERNEL := -I. -I$(srctree)/. -I$(srctree)/lib/libfdt -KBUILD_AFLAGS := -g -D__ASSEMBLY__ -mlittle-endian -fno-PIE -funwind-tables -Wa,-gdwarf-2 +KBUILD_AFLAGS := -g -D__ASSEMBLY__ -fno-PIE -funwind-tables -Wa,-gdwarf-2 DEFSYM_FLAGS = \ --defsym=CONFIG_NR_CPUS=$(CONFIG_NR_CPUS) \ @@ -345,14 +345,27 @@ LDFLAGS += --defsym=LOAD_OFFSET=0x80000 SRCARCH := $(patsubst "%",%,$(CONFIG_ARCH)) +LDFLAGS_ARCH := -no-enum-size-warning + ifeq ($(CONFIG_ARCH_ARM32),y) -KBUILD_CFLAGS += -mabi=aapcs -mno-thumb-interwork -mfpu=vfp -funwind-tables -marm -march=armv7-a -Uarm -DBITS_PER_LONG=32 -KBUILD_AFLAGS += -mabi=aapcs -mno-thumb-interwork -mfpu=vfp -funwind-tables -marm -march=armv7-a -Wa,-gdwarf-2 +KBUILD_CFLAGS += -mlittle-endian -mabi=aapcs -mno-thumb-interwork -mfpu=vfp -funwind-tables -marm -march=armv7-a -Uarm -DBITS_PER_LONG=32 +KBUILD_AFLAGS += -mlittle-endian -mabi=aapcs -mno-thumb-interwork -mfpu=vfp -funwind-tables -marm -march=armv7-a -Wa,-gdwarf-2 endif ifeq ($(CONFIG_ARCH_ARM64),y) -KBUILD_CFLAGS += -DBITS_PER_LONG=64 -fno-allow-store-data-races -KBUILD_AFLAGS += +KBUILD_CFLAGS += -mlittle-endian -DBITS_PER_LONG=64 -fno-allow-store-data-races +KBUILD_AFLAGS += -mlittle-endian +endif + +# The kernel lives in the top 2 GB (mcmodel=kernel), and never touches the +# FPU/SSE registers: they belong to user space and are switched by __switch_to. + +ifeq ($(CONFIG_ARCH_X86_64),y) +KBUILD_CFLAGS += -DBITS_PER_LONG=64 -m64 -mcmodel=kernel -mno-red-zone -mgeneral-regs-only \ + -mno-mmx -mno-sse -mno-sse2 -mno-3dnow -mno-avx -fno-pic -fcf-protection=none \ + -fno-asynchronous-unwind-tables -fno-allow-store-data-races -fno-omit-frame-pointer +KBUILD_AFLAGS += -m64 +LDFLAGS_ARCH := -z max-page-size=0x1000 -z noexecstack --no-warn-rwx-segments endif # Read KERNELRELEASE from include/config/kernel.release (if it exists) @@ -386,6 +399,9 @@ endif ifeq ($(CONFIG_VERDIN_IMX8MP),y) TARGET = verdin-imx8mp endif +ifeq ($(CONFIG_PC64),y) +TARGET = pc64 +endif # The all: target is the default when no target is given on the @@ -411,7 +427,14 @@ objs-$(CONFIG_SOO) += soo endif libs-y := lib -libs-y += lib/libfdt lib/libroxml +libs-y += lib/libfdt + +# libroxml parses floats, which the x86 kernel cannot use (the FPU belongs +# to user space); only SOO needs it. + +ifneq ($(CONFIG_ARCH_X86_64),y) +libs-y += lib/libroxml +endif so3-dirs := $(objs-y) $(libs-y) so3-objs := $(patsubst %,%/built-in.o, $(objs-y)) @@ -428,7 +451,7 @@ LIBGCC_PATH := $(shell dirname `$(CC) -print-libgcc-file-name`) quiet_cmd_so3 = LD $@ -cmd_so3 = $(LD) $(DEFSYM_FLAGS) -no-enum-size-warning -T $(srctree)/arch/$(SRCARCH)/so3.lds -o $@ $(so3-all) -L $(LIBGCC_PATH) -lgcc +cmd_so3 = $(LD) $(DEFSYM_FLAGS) $(LDFLAGS_ARCH) -T $(srctree)/arch/$(SRCARCH)/so3.lds -o $@ $(so3-all) -L $(LIBGCC_PATH) -lgcc KBUILD_CFLAGS_KERNEL += -I$(srctree)/arch/$(SRCARCH)/include/ -I$(srctree)/arch/$(SRCARCH)/$(TARGET)/include/ KBUILD_AFLAGS_KERNEL += -I$(srctree)/arch/$(SRCARCH)/include/ -I$(srctree)/arch/$(SRCARCH)/$(TARGET)/include/ diff --git a/so3/so3/arch/Kconfig b/so3/so3/arch/Kconfig index b0e3d9f5ae..fab45e51ba 100644 --- a/so3/so3/arch/Kconfig +++ b/so3/so3/arch/Kconfig @@ -7,24 +7,31 @@ choice config ARCH_ARM64 bool "ARM 64-bit" + + config ARCH_X86_64 + bool "x86 64-bit" endchoice config ARCH - string "ARM Architecture" + string "CPU Architecture" default "arm32" if ARCH_ARM32 default "arm64" if ARCH_ARM64 + default "x86" if ARCH_X86_64 config CROSS_COMPILE string "Cross-compiler" default "arm-none-linux-gnueabihf-" if ARCH_ARM32 default "aarch64-none-linux-gnu-" if ARCH_ARM64 + default "x86_64-linux-gnu-" if ARCH_X86_64 config ARM_TRUSTZONE bool "Using ARM TrustZone with OPTEE-OS" + depends on !ARCH_X86_64 source "arch/arm32/Kconfig" source "arch/arm64/Kconfig" +source "arch/x86/Kconfig" diff --git a/so3/so3/arch/Makefile b/so3/so3/arch/Makefile index fd0ba5df00..2447e3eb44 100644 --- a/so3/so3/arch/Makefile +++ b/so3/so3/arch/Makefile @@ -1,4 +1,5 @@ obj-$(CONFIG_ARCH_ARM32) += arm32/ obj-$(CONFIG_ARCH_ARM64) += arm64/ +obj-$(CONFIG_ARCH_X86_64) += x86/ diff --git a/so3/so3/arch/x86/Kconfig b/so3/so3/arch/x86/Kconfig new file mode 100644 index 0000000000..02925d0123 --- /dev/null +++ b/so3/so3/arch/x86/Kconfig @@ -0,0 +1,16 @@ + +if ARCH_X86_64 + +menu "Platform" + + choice + prompt "Target" + + config PC64 + bool "Generic QEMU x86_64 PC (i440FX, 8259 PIC, 8254 PIT, COM1)" + + endchoice + +endmenu + +endif diff --git a/so3/so3/arch/x86/Makefile b/so3/so3/arch/x86/Makefile new file mode 100644 index 0000000000..485f1cf452 --- /dev/null +++ b/so3/so3/arch/x86/Makefile @@ -0,0 +1,6 @@ + +obj-y += head.o entry.o context.o +obj-y += setup.o traps.o thread.o fault.o +obj-y += mmu.o syscalls.o + +obj-y += lib/ diff --git a/so3/so3/arch/x86/asm-offsets.c b/so3/so3/arch/x86/asm-offsets.c new file mode 100644 index 0000000000..7d3fa79288 --- /dev/null +++ b/so3/so3/arch/x86/asm-offsets.c @@ -0,0 +1,60 @@ +/* + * Copyright (C) 2026 Daniel Rossier + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#include +#include +#include + +#include +#include + +#define DEFINE(sym, val) asm volatile("\n->" #sym " %0 " #val : : "i"(val)) + +#define BLANK() asm volatile("\n->" : :) + +int main(void) +{ + DEFINE(OFFSET_KSP, offsetof(struct cpu_regs, ksp)); + DEFINE(OFFSET_FS_BASE, offsetof(struct cpu_regs, fs_base)); + DEFINE(OFFSET_RAX, offsetof(struct cpu_regs, rax)); + DEFINE(OFFSET_RDI, offsetof(struct cpu_regs, rdi)); + DEFINE(OFFSET_RSI, offsetof(struct cpu_regs, rsi)); + DEFINE(OFFSET_VECTOR, offsetof(struct cpu_regs, vector)); + DEFINE(OFFSET_RIP, offsetof(struct cpu_regs, rip)); + DEFINE(OFFSET_CS, offsetof(struct cpu_regs, cs)); + DEFINE(OFFSET_RFLAGS, offsetof(struct cpu_regs, rflags)); + DEFINE(OFFSET_RSP, offsetof(struct cpu_regs, rsp)); + DEFINE(OFFSET_SS, offsetof(struct cpu_regs, ss)); + DEFINE(S_FRAME_SIZE, sizeof(struct cpu_regs)); + + BLANK(); + + DEFINE(OFFSET_TCB_CPU_REGS, offsetof(tcb_t, cpu_regs)); + + BLANK(); + + DEFINE(OFFSET_SYS_SIGNUM, offsetof(__sigaction_t, signum)); + DEFINE(OFFSET_SYS_SA, offsetof(__sigaction_t, sa)); + + BLANK(); + + DEFINE(OFFSET_SA_HANDLER, offsetof(sigaction_t, sa_handler)); + DEFINE(OFFSET_SA_RESTORER, offsetof(sigaction_t, sa_restorer)); + + return 0; +} diff --git a/so3/so3/arch/x86/context.S b/so3/so3/arch/x86/context.S new file mode 100644 index 0000000000..34dd5b54d2 --- /dev/null +++ b/so3/so3/arch/x86/context.S @@ -0,0 +1,141 @@ +/* + * Copyright (C) 2026 Daniel Rossier + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#include +#include +#include + +#include + +#include + +.global __x86_switch_stack +.global __thread_prologue_kernel +.global __root_proc + +.text + +/* + * __x86_switch_stack(u64 *prev_ksp, u64 next_ksp) + * + * The callee-saved registers and the FXSAVE image of the outgoing thread stay + * on its kernel stack; the word right after the image holds the stack pointer + * to return to. arch_prepare_cpu_regs() lays out the same for a new thread. + */ + +ENTRY(__x86_switch_stack) + push %rbp + push %rbx + push %r12 + push %r13 + push %r14 + push %r15 + + mov %rsp, %rax + sub $(X86_FXSAVE_SIZE + 16), %rsp + and $-16, %rsp + fxsave64 (%rsp) + mov %rax, X86_FXSAVE_SIZE(%rsp) + mov %rsp, (%rdi) + + mov %rsi, %rsp + fxrstor64 (%rsp) + mov X86_FXSAVE_SIZE(%rsp), %rsp + + pop %r15 + pop %r14 + pop %r13 + pop %r12 + pop %rbx + pop %rbp + + ret + +/* First run of a kernel thread: rbx = th_fn, r12 = th_arg */ + +ENTRY(__thread_prologue_kernel) + mov %rbx, %rdi + mov %r12, %rsi + + sti + + call thread_prologue + + /* Never reached */ + +1: + hlt + jmp 1b + +ENTRY(cpu_do_idle) + sti + hlt + ret + +/* + * Data and code mapped in the user space as the initial process. The code + * runs at USER_SPACE_VADDR, hence only rip-relative references. + */ + +.section ".root_proc.text","ax" + + jmp __root_proc + +.LC_welcome: + .string "[SO3 USR] Starting the initial process\n" + .equ welcome_len, . - .LC_welcome + +.LC_exec: + .string CONFIG_USER_INIT_PROGRAM + +.LCnoshell: + .string "[SO3 USR] No init process found\n" + .equ noshell_len, . - .LCnoshell + +.align 16 + +ENTRY(__root_proc) + + /* write(stdout, buf, len) */ + + mov $STDOUT, %edi + lea .LC_welcome(%rip), %rsi + mov $welcome_len, %edx + mov $SYSCALL_write, %eax + syscall + + /* execve(init, NULL, NULL) */ + + lea .LC_exec(%rip), %rdi + xor %esi, %esi + xor %edx, %edx + mov $SYSCALL_execve, %eax + syscall + + /* If we are here, exec() has failed... */ + + mov $STDOUT, %edi + lea .LCnoshell(%rip), %rsi + mov $noshell_len, %edx + mov $SYSCALL_write, %eax + syscall + +1: + jmp 1b + +.section .note.GNU-stack, "", @progbits diff --git a/so3/so3/arch/x86/entry.S b/so3/so3/arch/x86/entry.S new file mode 100644 index 0000000000..4bbbc1dde6 --- /dev/null +++ b/so3/so3/arch/x86/entry.S @@ -0,0 +1,184 @@ +/* + * Copyright (C) 2026 Daniel Rossier + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#include +#include +#include + +#include + +.global ret_from_fork +.global x86_idt_stubs +.global x86_syscall_entry + +/* + * Every entry builds a cpu_regs_t on the kernel stack. The CPU pushes + * ss/rsp/rflags/cs/rip, the stub adds the error code and the vector, and + * save_regs the general registers plus the two TCB-only slots. + */ + +.macro save_regs + push %rdi + push %rsi + push %rdx + push %rcx + push %rax + push %r8 + push %r9 + push %r10 + push %r11 + push %rbx + push %rbp + push %r12 + push %r13 + push %r14 + push %r15 + sub $16, %rsp + cld +.endm + +.macro restore_regs + add $16, %rsp + pop %r15 + pop %r14 + pop %r13 + pop %r12 + pop %rbp + pop %rbx + pop %r11 + pop %r10 + pop %r9 + pop %r8 + pop %rax + pop %rcx + pop %rdx + pop %rsi + pop %rdi + + /* Vector and error code */ + + add $16, %rsp +.endm + +/* Exceptions 8, 10-14, 17, 21, 29 and 30 push an error code */ + +.macro idt_stub vec + .align 16 + .if (\vec == 8) || ((\vec >= 10) && (\vec <= 14)) || (\vec == 17) || (\vec == 21) || (\vec == 29) || (\vec == 30) + .else + push $0 + .endif + push $\vec + jmp x86_common_entry +.endm + +.text + +.align 16 +x86_idt_stubs: + .altmacro + .set vec, 0 + .rept 48 + idt_stub %vec + .set vec, vec + 1 + .endr + +x86_common_entry: + save_regs + + mov %rsp, %rdi + call trap_handle + + testb $3, OFFSET_CS(%rsp) + jnz ret_to_user + + restore_regs + iretq + +/* + * syscall: rcx = user rip, r11 = user rflags, IF cleared by SFMASK. + * The stack is still the user one; the frame is built as if the CPU had + * taken an interrupt, so the exit path is shared. + */ + +x86_syscall_entry: + mov %rsp, x86_user_rsp(%rip) + mov x86_kernel_rsp(%rip), %rsp + + push $USER_DS + push x86_user_rsp(%rip) + push %r11 + push $USER_CS + push %rcx + push $0 + push $X86_SYSCALL_VECTOR + + save_regs + + mov %rsp, %rdi + call syscall_entry_handle + +#ifdef CONFIG_IPC_SIGNAL + /* + * rt_sigreturn: drop the frame of the signal handler, so that the + * interrupted one below is restored. + */ + + test %rax, %rax + jz ret_to_user + + add $S_FRAME_SIZE, %rsp +#endif + +/* Entry point for new user threads as well, with rsp on their frame */ + +ret_from_fork: +ret_to_user: +#ifdef CONFIG_IPC_SIGNAL + call sig_check + test %rax, %rax + jz 1f + + /* Build the frame of the user handler below the current one */ + + mov %rsp, %rsi + sub $S_FRAME_SIZE, %rsp + mov %rsp, %rdi + mov %rax, %rdx + call x86_setup_sig_frame +1: +#endif + /* The next entry from user mode lands right above this frame */ + + lea S_FRAME_SIZE(%rsp), %rdi + call x86_set_kernel_stack + + restore_regs + iretq + +.data +.align 8 + +.global x86_kernel_rsp +x86_kernel_rsp: + .quad 0 + +x86_user_rsp: + .quad 0 + +.section .note.GNU-stack, "", @progbits diff --git a/so3/so3/arch/x86/fault.c b/so3/so3/arch/x86/fault.c new file mode 100644 index 0000000000..b4ba39e0aa --- /dev/null +++ b/so3/so3/arch/x86/fault.c @@ -0,0 +1,73 @@ +/* + * Copyright (C) 2026 Daniel Rossier + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#include + +#include +#include + +void show_registers(cpu_regs_t *regs); + +/* Walk the frame pointer chain, as far as it is present */ + +void __backtrace(void) +{ + u64 *rbp; + int depth; + + asm volatile("mov %%rbp, %0" : "=r"(rbp)); + + for (depth = 0; depth < 16 && rbp && ((addr_t) rbp >= CONFIG_KERNEL_VADDR); depth++) { + lprintk(" [<%016lx>]\n", rbp[1]); + rbp = (u64 *) rbp[0]; + } +} + +void dump_stack(void) +{ + lprintk("Call trace:\n"); + __backtrace(); +} + +void dump_execution_state(void) +{ + dump_stack(); +} + +void dump_all_execution_state(void) +{ + dump_stack(); +} + +void kernel_panic(void) +{ + lprintk("%s: entering infinite loop... CPU: %d\n", __func__, smp_processor_id()); + + /* Stop all activities. */ + + local_irq_disable(); + while (1) + wfi(); +} + +void _bug(char *file, int line) +{ + lprintk("BUG in %s at line: %d\n", file, line); + dump_stack(); + kernel_panic(); +} diff --git a/so3/so3/arch/x86/head.S b/so3/so3/arch/x86/head.S new file mode 100644 index 0000000000..c8ba400a9b --- /dev/null +++ b/so3/so3/arch/x86/head.S @@ -0,0 +1,187 @@ +/* + * Copyright (C) 2026 Daniel Rossier + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#include +#include + +#include + +#define MB2_MAGIC 0xe85250d6 +#define MB2_ARCH_I386 0 +#define MB2_BOOTLOADER_MAGIC 0x36d76289 + +#define PHYS(x) ((x) - CONFIG_KERNEL_VADDR) + +#define SYS_STACK_SIZE (CONFIG_SYS_STACK_SIZE_KB * 1024) + +.section ".multiboot", "a" +.align 8 + +mb2_header: + .long MB2_MAGIC + .long MB2_ARCH_I386 + .long mb2_header_end - mb2_header + .long -(MB2_MAGIC + MB2_ARCH_I386 + (mb2_header_end - mb2_header)) + + /* Entry address tag: GRUB jumps to the physical 32-bit entry */ + + .align 8 + .short 3 + .short 0 + .long 12 + .long PHYS(__start32) + + /* End tag */ + + .align 8 + .short 0 + .short 0 + .long 8 +mb2_header_end: + +/* + * GRUB enters here in 32-bit protected mode, paging off, with + * eax = multiboot2 magic and ebx = physical address of the boot info. + */ + +.section ".head.text", "ax" +.code32 + +ENTRY(__start32) + cli + cld + + mov %eax, %edi + mov %ebx, %esi + + mov $PHYS(__stack_bottom + SYS_STACK_SIZE), %esp + + cmp $MB2_BOOTLOADER_MAGIC, %edi + jne __boot_hang + + /* Clear the four boot page tables */ + + push %edi + mov $PHYS(__sys_root_pgtable), %edi + mov $(4 * 4096 / 4), %ecx + xor %eax, %eax + rep stosl + pop %edi + + /* + * PML4[0] -> idmap PDPT, PDPT[0] -> PD (identity for this code) + * PML4[511] -> kernel PDPT, PDPT[510] -> PD (0xffffffff80000000) + * The PD maps the first GB with 2 MB pages. + */ + + mov $PHYS(__sys_idmap_l1pgtable + 3), %eax + mov %eax, PHYS(__sys_root_pgtable) + + mov $PHYS(__sys_linearmap_l1pgtable + 3), %eax + mov %eax, PHYS(__sys_root_pgtable + 511 * 8) + + mov $PHYS(__sys_linearmap_l2pgtable + 3), %eax + mov %eax, PHYS(__sys_idmap_l1pgtable) + mov %eax, PHYS(__sys_linearmap_l1pgtable + 510 * 8) + + mov $PHYS(__sys_linearmap_l2pgtable), %ebx + mov $0x83, %eax + mov $512, %ecx +1: + mov %eax, (%ebx) + add $0x200000, %eax + add $8, %ebx + loop 1b + + /* PAE, then long mode, then paging */ + + mov %cr4, %eax + or $X86_CR4_PAE, %eax + mov %eax, %cr4 + + mov $PHYS(__sys_root_pgtable), %eax + mov %eax, %cr3 + + mov $MSR_EFER, %ecx + rdmsr + or $(EFER_LME | EFER_SCE), %eax + wrmsr + + mov %cr0, %eax + or $(X86_CR0_PG | X86_CR0_PE | X86_CR0_WP), %eax + mov %eax, %cr0 + + lgdt PHYS(boot_gdt_desc) + + ljmp $KERNEL_CS, $PHYS(__start64_low) + +__boot_hang: + hlt + jmp __boot_hang + +.code64 + +__start64_low: + movabs $__start64, %rax + jmp *%rax + +.text + +__start64: + xor %eax, %eax + mov %eax, %ds + mov %eax, %es + mov %eax, %ss + mov %eax, %fs + mov %eax, %gs + + movabs $(__stack_bottom + SYS_STACK_SIZE), %rsp + + /* Reload the GDT pointer through its high address */ + + movabs $boot_gdt_desc_high, %rax + lgdt (%rax) + + /* The boot info address is a 32-bit physical address */ + + mov %esi, %edi + call x86_boot + +1: + hlt + jmp 1b + +.section ".rodata" +.align 16 + +boot_gdt: + .quad 0 + .quad 0x00af9a000000ffff /* 0x08: 64-bit kernel code */ + .quad 0x00cf92000000ffff /* 0x10: kernel data */ +boot_gdt_end: + +boot_gdt_desc: + .short boot_gdt_end - boot_gdt - 1 + .long PHYS(boot_gdt) + +.align 8 +boot_gdt_desc_high: + .short boot_gdt_end - boot_gdt - 1 + .quad boot_gdt + +.section .note.GNU-stack, "", @progbits diff --git a/so3/so3/arch/x86/include/asm/atomic.h b/so3/so3/arch/x86/include/asm/atomic.h new file mode 100644 index 0000000000..5863e17f6b --- /dev/null +++ b/so3/so3/arch/x86/include/asm/atomic.h @@ -0,0 +1,96 @@ +/* + * Copyright (C) 2026 Daniel Rossier + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifndef ASM_ATOMIC_H +#define ASM_ATOMIC_H + +#include +#include + +#include + +typedef struct { + volatile int counter; +} atomic_t; + +#define ATOMIC_INIT(i) { (i) } + +#define atomic_read(v) READ_ONCE((v)->counter) +#define atomic_set(v, i) WRITE_ONCE(((v)->counter), (i)) + +static inline int atomic_add_return(int i, atomic_t *v) +{ + return __atomic_add_fetch(&v->counter, i, __ATOMIC_SEQ_CST); +} + +static inline int atomic_sub_return(int i, atomic_t *v) +{ + return __atomic_sub_fetch(&v->counter, i, __ATOMIC_SEQ_CST); +} + +static inline void atomic_and(int m, atomic_t *v) +{ + __atomic_and_fetch(&v->counter, m, __ATOMIC_SEQ_CST); +} + +static inline int atomic_cmpxchg(atomic_t *v, int old, int new) +{ + __atomic_compare_exchange_n(&v->counter, &old, new, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); + + return old; +} + +static inline int __atomic_add_unless(atomic_t *v, int a, int u) +{ + int c = atomic_read(v); + + while (c != u && !__atomic_compare_exchange_n(&v->counter, &c, c + a, false, __ATOMIC_SEQ_CST, + __ATOMIC_SEQ_CST)) + ; + + return c; +} + +#define atomic_add_unless(v, a, u) (__atomic_add_unless(v, a, u) != (u)) +#define atomic_inc_not_zero(v) atomic_add_unless((v), 1, 0) + +#define atomic_add(i, v) (void) atomic_add_return(i, v) +#define atomic_inc(v) (void) atomic_add_return(1, v) +#define atomic_sub(i, v) (void) atomic_sub_return(i, v) +#define atomic_dec(v) (void) atomic_sub_return(1, v) + +#define atomic_inc_and_test(v) (atomic_add_return(1, v) == 0) +#define atomic_dec_and_test(v) (atomic_sub_return(1, v) == 0) +#define atomic_inc_return(v) (atomic_add_return(1, v)) +#define atomic_dec_return(v) (atomic_sub_return(1, v)) +#define atomic_sub_and_test(i, v) (atomic_sub_return(i, v) == 0) + +#define atomic_add_negative(i, v) (atomic_add_return(i, v) < 0) + +#define xchg(ptr, x) __atomic_exchange_n((ptr), (x), __ATOMIC_SEQ_CST) + +#define cmpxchg(ptr, o, n) \ + ({ \ + __typeof__(*(ptr)) __old = (o); \ + __atomic_compare_exchange_n((ptr), &__old, (n), false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); \ + __old; \ + }) + +#define atomic_xchg(v, new) xchg(&((v)->counter), (new)) + +#endif /* ASM_ATOMIC_H */ diff --git a/so3/so3/arch/x86/include/asm/backtrace.h b/so3/so3/arch/x86/include/asm/backtrace.h new file mode 100644 index 0000000000..043505e764 --- /dev/null +++ b/so3/so3/arch/x86/include/asm/backtrace.h @@ -0,0 +1,34 @@ +/* + * Copyright (C) 2016-2020 Daniel Rossier + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifndef BACKTRACE_H +#define BACKTRACE_H + +void dump_stack(void); + +void show_registers(struct cpu_regs *regs); + +void dump_execution_state(void); +void dump_all_execution_state(void); + +static inline void show_execution_state(struct cpu_regs *regs) +{ + show_registers(regs); +} + +#endif /* BACKTRACE_H */ diff --git a/so3/so3/arch/x86/include/asm/bitops.h b/so3/so3/arch/x86/include/asm/bitops.h new file mode 100644 index 0000000000..30285ede60 --- /dev/null +++ b/so3/so3/arch/x86/include/asm/bitops.h @@ -0,0 +1,74 @@ +/* + * Copyright (C) 2026 Daniel Rossier + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifndef ASM_BITOPS_H +#define ASM_BITOPS_H + +#include +#include + +#ifndef __ASSEMBLY__ + +#define __L2(_x) (((_x) & 0x00000002) ? 1 : 0) +#define __L4(_x) (((_x) & 0x0000000c) ? (2 + __L2((_x) >> 2)) : __L2(_x)) +#define __L8(_x) (((_x) & 0x000000f0) ? (4 + __L4((_x) >> 4)) : __L4(_x)) +#define __L16(_x) (((_x) & 0x0000ff00) ? (8 + __L8((_x) >> 8)) : __L8(_x)) +#define LOG_2(_x) (((_x) & 0xffff0000) ? (16 + __L16((_x) >> 16)) : __L16(_x)) + +#define BIT_MASK(last, first) ((0xffffffffffffffffULL >> (64 - ((last) + 1 - (first)))) << (first)) +#define GET_FIELD(value, last, first) (((value) & BIT_MASK((last), (first))) >> (first)) + +#define smp_mb__before_clear_bit() mb() +#define smp_mb__after_clear_bit() mb() + +#define BITOP_MASK(nr) (1UL << ((nr) % BITS_PER_LONG)) +#define BITOP_WORD(nr) ((nr) / BITS_PER_LONG) + +static inline int test_bit(int nr, const volatile unsigned long *addr) +{ + return 1UL & (addr[BITOP_WORD(nr)] >> (nr & (BITS_PER_LONG - 1))); +} + +#define set_bit(nr, p) ((void) __atomic_fetch_or(&(p)[BITOP_WORD(nr)], BITOP_MASK(nr), __ATOMIC_SEQ_CST)) +#define clear_bit(nr, p) ((void) __atomic_fetch_and(&(p)[BITOP_WORD(nr)], ~BITOP_MASK(nr), __ATOMIC_SEQ_CST)) +#define change_bit(nr, p) ((void) __atomic_fetch_xor(&(p)[BITOP_WORD(nr)], BITOP_MASK(nr), __ATOMIC_SEQ_CST)) + +#define test_and_set_bit(nr, p) \ + (!!(__atomic_fetch_or(&(p)[BITOP_WORD(nr)], BITOP_MASK(nr), __ATOMIC_SEQ_CST) & BITOP_MASK(nr))) +#define test_and_clear_bit(nr, p) \ + (!!(__atomic_fetch_and(&(p)[BITOP_WORD(nr)], ~BITOP_MASK(nr), __ATOMIC_SEQ_CST) & BITOP_MASK(nr))) +#define test_and_change_bit(nr, p) \ + (!!(__atomic_fetch_xor(&(p)[BITOP_WORD(nr)], BITOP_MASK(nr), __ATOMIC_SEQ_CST) & BITOP_MASK(nr))) + +/* Count leading zeroes */ + +static inline unsigned long clz(unsigned long word) +{ + return word ? __builtin_clzl(word) : BITS_PER_LONG; +} + +/* Position of the least significant 1 (LSB = 0), 0 if none */ + +static inline unsigned long ffsl(unsigned long word) +{ + return word ? __builtin_ctzl(word) : 0; +} + +#endif /*__ASSEMBLY__ */ + +#endif /* ASM_BITOPS_H */ diff --git a/so3/so3/arch/x86/include/asm/byteorder.h b/so3/so3/arch/x86/include/asm/byteorder.h new file mode 100644 index 0000000000..63aa791c7a --- /dev/null +++ b/so3/so3/arch/x86/include/asm/byteorder.h @@ -0,0 +1,25 @@ +/* + * linux/include/asm-arm/byteorder.h + * + * ARM Endian-ness. In little endian mode, the data bus is connected such + * that byte accesses appear as: + * 0 = d0...d7, 1 = d8...d15, 2 = d16...d23, 3 = d24...d31 + * and word accesses (data or instruction) appear as: + * d0...d31 + * + * When in big endian mode, byte accesses appear as: + * 0 = d24...d31, 1 = d16...d23, 2 = d8...d15, 3 = d0...d7 + * and word accesses (data or instruction) appear as: + * d0...d31 + */ +#ifndef __ASM_ARM_BYTEORDER_H +#define __ASM_ARM_BYTEORDER_H + +#include + +#define __BYTEORDER_HAS_U64__ +#define __SWAB_64_THRU_32__ + +#include + +#endif diff --git a/so3/so3/arch/x86/include/asm/cacheflush.h b/so3/so3/arch/x86/include/asm/cacheflush.h new file mode 100644 index 0000000000..7ae37c323f --- /dev/null +++ b/so3/so3/arch/x86/include/asm/cacheflush.h @@ -0,0 +1,67 @@ +/* + * Copyright (C) 2026 Daniel Rossier + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifndef ASM_CACHEFLUSH_H +#define ASM_CACHEFLUSH_H + +#include + +#include + +/* + * x86 caches are coherent with page table walks and DMA, so the ARM cache + * maintenance calls used by the generic code reduce to TLB handling. + */ + +static inline void flush_dcache_all(void) +{ +} + +static inline void flush_dcache_range(addr_t start, addr_t end) +{ +} + +static inline void invalidate_dcache_range(addr_t start, addr_t end) +{ +} + +static inline void invalidate_dcache_all(void) +{ +} + +static inline void invalidate_icache_all(void) +{ +} + +static inline void mmu_page_table_flush(unsigned long start, unsigned long end) +{ +} + +static inline void flush_pte_entry(addr_t va, u64 *pte) +{ + invlpg(va); +} + +static inline void flush_tlb_all(void) +{ + write_cr3(read_cr3()); +} + +#define __asm_invalidate_tlb_all() flush_tlb_all() + +#endif /* ASM_CACHEFLUSH_H */ diff --git a/so3/so3/arch/x86/include/asm/div64.h b/so3/so3/arch/x86/include/asm/div64.h new file mode 100644 index 0000000000..70c0253642 --- /dev/null +++ b/so3/so3/arch/x86/include/asm/div64.h @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2022 Daniel Rossier + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifndef DIV64_H +#define DIV64_H + +#define do_div(n, base) \ + ({ \ + uint32_t __base = (base); \ + uint32_t __rem; \ + __rem = ((uint64_t) (n)) % __base; \ + (n) = ((uint64_t) (n)) / __base; \ + __rem; \ + }) + +/* Wrapper for do_div(). Doesn't modify dividend and returns + * the result, not reminder. + */ + +static inline uint64_t lldiv(uint64_t dividend, uint32_t divisor) +{ + uint64_t __res = dividend; + do_div(__res, divisor); + return (__res); +} + +#endif /* DIV64_H */ diff --git a/so3/so3/arch/x86/include/asm/hwcap.h b/so3/so3/arch/x86/include/asm/hwcap.h new file mode 100644 index 0000000000..0364a207fe --- /dev/null +++ b/so3/so3/arch/x86/include/asm/hwcap.h @@ -0,0 +1,25 @@ +/* + * Copyright (C) 2025 Clément Dieperink + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef ASM_ARM_HWCAP_H +#define ASM_ARM_HWCAP_H + +/* + * This isn't used by MUSL on AArch64, so simply let it to 0 for now. + */ +#define HWCAP_ELF 0 + +#endif /* ASM_ARM_HWCAP */ diff --git a/so3/so3/arch/x86/include/asm/io.h b/so3/so3/arch/x86/include/asm/io.h new file mode 100644 index 0000000000..c4b8606e2b --- /dev/null +++ b/so3/so3/arch/x86/include/asm/io.h @@ -0,0 +1,85 @@ +/* + * Copyright (C) 2026 Daniel Rossier + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifndef ASM_IO_H +#define ASM_IO_H + +#include + +#define ioread8(p) (*((volatile uint8_t *) (p))) +#define ioread16(p) (*((volatile uint16_t *) (p))) +#define ioread32(p) (*((volatile uint32_t *) (p))) +#define ioread64(p) (*((volatile uint64_t *) (p))) + +#define iowrite8(p, v) (*((volatile uint8_t *) (p)) = v) +#define iowrite16(p, v) (*((volatile uint16_t *) (p)) = v) +#define iowrite32(p, v) (*((volatile uint32_t *) (p)) = v) +#define iowrite64(p, v) (*((volatile uint64_t *) (p)) = v) + +/* Legacy PC devices (PIC, PIT, COM ports) sit in the I/O port space. */ + +static inline uint8_t inb(uint16_t port) +{ + uint8_t val; + + asm volatile("inb %1, %0" : "=a"(val) : "Nd"(port) : "memory"); + + return val; +} + +static inline void outb(uint16_t port, uint8_t val) +{ + asm volatile("outb %0, %1" : : "a"(val), "Nd"(port) : "memory"); +} + +static inline uint16_t inw(uint16_t port) +{ + uint16_t val; + + asm volatile("inw %1, %0" : "=a"(val) : "Nd"(port) : "memory"); + + return val; +} + +static inline void outw(uint16_t port, uint16_t val) +{ + asm volatile("outw %0, %1" : : "a"(val), "Nd"(port) : "memory"); +} + +static inline uint32_t inl(uint16_t port) +{ + uint32_t val; + + asm volatile("inl %1, %0" : "=a"(val) : "Nd"(port) : "memory"); + + return val; +} + +static inline void outl(uint16_t port, uint32_t val) +{ + asm volatile("outl %0, %1" : : "a"(val), "Nd"(port) : "memory"); +} + +/* A write to an unused port gives slow legacy chips time to settle. */ + +static inline void io_delay(void) +{ + outb(0x80, 0); +} + +#endif /* ASM_IO_H */ diff --git a/so3/so3/arch/x86/include/asm/mmu.h b/so3/so3/arch/x86/include/asm/mmu.h new file mode 100644 index 0000000000..9fdbacb433 --- /dev/null +++ b/so3/so3/arch/x86/include/asm/mmu.h @@ -0,0 +1,201 @@ +/* + * Copyright (C) 2026 Daniel Rossier + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifndef MMU_H +#define MMU_H + +#include + +#ifndef __ASSEMBLY__ +#include +#endif + +#include +#include + +#define USER_SPACE_VADDR UL(0x1000) + +#define RAMDEV_VADDR UL(0xffffa00000000000) + +/* Fixmap page used for temporary mapping */ + +#define FIXMAP_MAPPING UL(0xffffb00000000000) + +/* Anonymous start virtual address */ + +#define USER_ANONYMOUS_VADDR UL(0x0000000100000000) + +/* + * The user space is the lower canonical half, below 0x0000_8000_0000_0000. + * The stack top stays well inside it. + */ + +#define USER_STACK_TOP_VADDR UL(0x0000700000000000) + +#define SZ_256G (256UL * SZ_1G) + +/* PAGE_SHIFT determines the page size */ + +#define PAGE_SHIFT 12 +#define PAGE_SIZE (1 << PAGE_SHIFT) +#define PAGE_MASK (~(PAGE_SIZE - 1)) + +#define BLOCK_256G_OFFSET (SZ_256G - 1) +#define BLOCK_1G_OFFSET (SZ_1G - 1) +#define BLOCK_2M_OFFSET (SZ_2M - 1) + +#define BLOCK_256G_MASK (~BLOCK_256G_OFFSET) +#define BLOCK_1G_MASK (~BLOCK_1G_OFFSET) +#define BLOCK_2M_MASK (~BLOCK_2M_OFFSET) + +/* + * 4-level paging: L0 = PML4, L1 = PDPT, L2 = PD, L3 = PT. The geometry is + * the one of the AArch64 4 KB granule, so the names are kept. + */ + +#define TTB_I0_SHIFT 39 +#define TTB_I1_SHIFT 30 +#define TTB_I2_SHIFT 21 +#define TTB_I3_SHIFT 12 + +#define TTB_L0_ENTRIES 512 +#define TTB_L1_ENTRIES 512 +#define TTB_L2_ENTRIES 512 +#define TTB_L3_ENTRIES 512 + +#define TTB_L0_SIZE 4096 +#define TTB_L1_SIZE 4096 +#define TTB_L2_SIZE 4096 +#define TTB_L3_SIZE 4096 + +/* First L0 entry of the kernel (upper) half, shared by all page tables */ + +#define TTB_L0_KERNEL_FIRST 256 + +#define PTE_ADDR_MASK UL(0x000ffffffffff000) + +#define TTB_L0_TABLE_ADDR_MASK PTE_ADDR_MASK +#define TTB_L1_TABLE_ADDR_MASK PTE_ADDR_MASK +#define TTB_L2_TABLE_ADDR_MASK PTE_ADDR_MASK +#define TTB_L3_PAGE_ADDR_MASK PTE_ADDR_MASK + +#define TTB_L1_BLOCK_ADDR_MASK UL(0x000fffffc0000000) +#define TTB_L2_BLOCK_ADDR_MASK UL(0x000fffffffe00000) + +#define PTE_PRESENT (UL(1) << 0) +#define PTE_RW (UL(1) << 1) +#define PTE_USER (UL(1) << 2) +#define PTE_PWT (UL(1) << 3) +#define PTE_PCD (UL(1) << 4) +#define PTE_ACCESSED (UL(1) << 5) +#define PTE_DIRTY (UL(1) << 6) +#define PTE_PS (UL(1) << 7) +#define PTE_GLOBAL (UL(1) << 8) +#define PTE_NX (UL(1) << 63) + +#define PTE_TYPE_TABLE 1 +#define PTE_TYPE_BLOCK 2 +#define PTE_TYPE_PAGE 3 + +#define l0pte_index(a) ((((addr_t) a) >> TTB_I0_SHIFT) & (TTB_L0_ENTRIES - 1)) +#define l1pte_index(a) ((((addr_t) a) >> TTB_I1_SHIFT) & (TTB_L1_ENTRIES - 1)) +#define l2pte_index(a) ((((addr_t) a) >> TTB_I2_SHIFT) & (TTB_L2_ENTRIES - 1)) +#define l3pte_index(a) ((((addr_t) a) >> TTB_I3_SHIFT) & (TTB_L3_ENTRIES - 1)) + +#define l0pte_offset(pgtable, addr) ((u64 *) ((u64 *) pgtable + l0pte_index(addr))) +#define l1pte_offset(l0pte, addr) ((u64 *) (__va(*l0pte & TTB_L0_TABLE_ADDR_MASK)) + l1pte_index(addr)) +#define l2pte_offset(l1pte, addr) ((u64 *) (__va(*l1pte & TTB_L1_TABLE_ADDR_MASK)) + l2pte_index(addr)) +#define l3pte_offset(l2pte, addr) ((u64 *) (__va(*l2pte & TTB_L2_TABLE_ADDR_MASK)) + l3pte_index(addr)) + +#define l0_addr_end(addr, end) \ + ({ \ + unsigned long __boundary = ((addr) + SZ_256G) & BLOCK_256G_MASK; \ + (__boundary - 1 < (end) - 1) ? __boundary : (end); \ + }) + +#define l1_addr_end(addr, end) \ + ({ \ + unsigned long __boundary = ((addr) + SZ_1G) & BLOCK_1G_MASK; \ + (__boundary - 1 < (end) - 1) ? __boundary : (end); \ + }) + +#define l2_addr_end(addr, end) \ + ({ \ + unsigned long __boundary = ((addr) + SZ_2M) & BLOCK_2M_MASK; \ + (__boundary - 1 < (end) - 1) ? __boundary : (end); \ + }) + +#define clear_page(page) memset((void *) (page), 0, PAGE_SIZE) + +#define PFN_DOWN(x) ((x) >> PAGE_SHIFT) +#define PFN_UP(x) (((x) + PAGE_SIZE - 1) >> PAGE_SHIFT) + +#ifndef __ASSEMBLY__ + +static inline bool user_space_vaddr(addr_t addr) +{ + return addr < UL(0x0000800000000000); +} + +/* Type of a present entry at level 0 (PML4) to 3 (PT) */ + +static inline int pte_type(u64 *pte, int level) +{ + if (level == 3) + return PTE_TYPE_PAGE; + + if ((level == 1 || level == 2) && (*pte & PTE_PS)) + return PTE_TYPE_BLOCK; + + return PTE_TYPE_TABLE; +} + +extern addr_t __sys_root_pgtable[], __sys_idmap_l1pgtable[], __sys_linearmap_l1pgtable[], __sys_linearmap_l2pgtable[]; + +extern void *__current_pgtable; + +void *current_pgtable(void); + +static inline void set_pgtable(void *pgtable) +{ + __current_pgtable = pgtable; +} + +void *new_root_pgtable(void); +void copy_root_pgtable(void *dst, void *src); +void reset_root_pgtable(void *pgtable, bool remove); +void pgtable_copy_kernel_area(void *pgtable); + +void ramdev_create_mapping(void *root_pgtable, addr_t ramdev_start, addr_t ramdev_end); + +addr_t virt_to_phys_pt(addr_t vaddr); + +void create_mapping(void *pgtable, addr_t virt_base, addr_t phys_base, size_t size, bool nocache); +void release_mapping(void *pgtable, addr_t virt_base, size_t size); + +void mmu_switch(void *pgtable_paddr); +void mmu_switch_kernel(void *pgtable); + +void dump_pgtable(void *pgtable); + +struct pcb; +void duplicate_user_space(struct pcb *from, struct pcb *to); + +#endif /* __ASSEMBLY__ */ + +#endif /* MMU_H */ diff --git a/so3/so3/arch/x86/include/asm/posix_types.h b/so3/so3/arch/x86/include/asm/posix_types.h new file mode 100644 index 0000000000..f9f11f1499 --- /dev/null +++ b/so3/so3/arch/x86/include/asm/posix_types.h @@ -0,0 +1,50 @@ +/* + * linux/include/asm-arm/posix_types.h + * + * Copyright (C) 1996-1998 Russell King. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * Changelog: + * 27-06-1996 RMK Created + */ +#ifndef __ARCH_ARM_POSIX_TYPES_H +#define __ARCH_ARM_POSIX_TYPES_H + +/* + * This file is generally used by user-level software, so you need to + * be a little careful about namespace pollution etc. Also, we cannot + * assume GCC is being used. + */ + +#ifdef __GNUC__ +typedef long long __kernel_loff_t; +#endif + +typedef struct { +#if defined(__KERNEL__) || defined(__USE_ALL) + int val[2]; +#else /* !defined(__KERNEL__) && !defined(__USE_ALL) */ + int __val[2]; +#endif /* !defined(__KERNEL__) && !defined(__USE_ALL) */ +} __kernel_fsid_t; + +#if defined(__KERNEL__) || !defined(__GLIBC__) || (__GLIBC__ < 2) + +#undef __FD_SET +#define __FD_SET(fd, fdsetp) (((fd_set *) fdsetp)->fds_bits[fd >> 5] |= (1 << (fd & 31))) + +#undef __FD_CLR +#define __FD_CLR(fd, fdsetp) (((fd_set *) fdsetp)->fds_bits[fd >> 5] &= ~(1 << (fd & 31))) + +#undef __FD_ISSET +#define __FD_ISSET(fd, fdsetp) ((((fd_set *) fdsetp)->fds_bits[fd >> 5] & (1 << (fd & 31))) != 0) + +#undef __FD_ZERO +#define __FD_ZERO(fdsetp) (memset(fdsetp, 0, sizeof(*(fd_set *) fdsetp))) + +#endif + +#endif diff --git a/so3/so3/arch/x86/include/asm/process.h b/so3/so3/arch/x86/include/asm/process.h new file mode 100644 index 0000000000..ddd9a8219d --- /dev/null +++ b/so3/so3/arch/x86/include/asm/process.h @@ -0,0 +1,26 @@ +/* + * Copyright (C) 2022 Daniel Rossier + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifndef ASM_PROCESS_H +#define ASM_PROCESS_H + +extern int *__root_proc(void *); + +extern addr_t __root_proc_start[], __root_proc_end[]; + +#endif /* ASM_PROCESS_H */ diff --git a/so3/so3/arch/x86/include/asm/processor.h b/so3/so3/arch/x86/include/asm/processor.h new file mode 100644 index 0000000000..c38b996318 --- /dev/null +++ b/so3/so3/arch/x86/include/asm/processor.h @@ -0,0 +1,270 @@ +/* + * Copyright (C) 2026 Daniel Rossier + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifndef PROCESSOR_H +#define PROCESSOR_H + +#include +#include + +#include + +#define BIT(nr) (1UL << (nr)) + +/* Segment selectors, in the GDT order set up by setup.c */ +#define KERNEL_CS 0x08 +#define KERNEL_DS 0x10 +#define USER_DS (0x18 | 3) +#define USER_CS (0x20 | 3) +#define TSS_SEL 0x28 + +#define X86_EFLAGS_IF BIT(9) +#define X86_EFLAGS_DF BIT(10) +#define X86_EFLAGS_TF BIT(8) +#define X86_EFLAGS_FIXED BIT(1) + +#define X86_CR0_PE BIT(0) +#define X86_CR0_MP BIT(1) +#define X86_CR0_EM BIT(2) +#define X86_CR0_TS BIT(3) +#define X86_CR0_NE BIT(5) +#define X86_CR0_WP BIT(16) +#define X86_CR0_PG BIT(31) + +#define X86_CR4_PAE BIT(5) +#define X86_CR4_PGE BIT(7) +#define X86_CR4_OSFXSR BIT(9) +#define X86_CR4_OSXMMEXCPT BIT(10) + +#define MSR_EFER 0xc0000080 +#define MSR_STAR 0xc0000081 +#define MSR_LSTAR 0xc0000082 +#define MSR_SFMASK 0xc0000084 +#define MSR_FS_BASE 0xc0000100 +#define MSR_GS_BASE 0xc0000101 +#define MSR_KERNEL_GS_BASE 0xc0000102 + +#define EFER_SCE BIT(0) +#define EFER_LME BIT(8) +#define EFER_NXE BIT(11) + +/* Vector pushed in the frame by the syscall entry, outside the IDT range */ +#define X86_SYSCALL_VECTOR 0x100 + +/* Base vector of the 8259 PIC interrupts */ +#define X86_IRQ_BASE 32 + +/* Size of the FXSAVE image kept on the kernel stack across __switch_to */ +#define X86_FXSAVE_SIZE 512 + +#ifndef __ASSEMBLY__ + +#include + +#ifndef barrier +#define barrier() asm volatile("" : : : "memory") +#endif + +#define mb() asm volatile("mfence" : : : "memory") +#define rmb() asm volatile("lfence" : : : "memory") +#define wmb() asm volatile("sfence" : : : "memory") + +#define smp_mb() mb() +#define smp_rmb() barrier() +#define smp_wmb() barrier() + +/* ARM barrier names used by the generic code; x86 memory is coherent. */ +#define isb() barrier() +#define dsb(scope) mb() +#define dmb(scope) mb() + +#define sev() barrier() +#define wfe() asm volatile("pause" : : : "memory") +#define wfi() asm volatile("hlt" : : : "memory") + +/* + * Register frame built on the kernel stack by every entry (exception, IRQ, + * syscall). It ends with the frame pushed by the CPU, so that a frame taken + * from user mode ends exactly at TSS.rsp0. + * + * The same type holds the thread context in the TCB, where only ksp and + * fs_base are meaningful: callee-saved registers and the FPU image live on + * the kernel stack of a switched-out thread. + */ + +typedef struct cpu_regs { + u64 ksp; + u64 fs_base; + + u64 r15; + u64 r14; + u64 r13; + u64 r12; + u64 rbp; + u64 rbx; + u64 r11; + u64 r10; + u64 r9; + u64 r8; + u64 rax; + u64 rcx; + u64 rdx; + u64 rsi; + u64 rdi; + + u64 vector; + u64 error_code; + + u64 rip; + u64 cs; + u64 rflags; + u64 rsp; + u64 ss; +} cpu_regs_t; + +static inline int smp_processor_id(void) +{ + return 0; +} + +static inline int irqs_disabled_flags(cpu_regs_t *regs) +{ + return !(regs->rflags & X86_EFLAGS_IF); +} + +static inline void local_irq_enable(void) +{ + asm volatile("sti" : : : "memory"); +} + +static inline void local_irq_disable(void) +{ + asm volatile("cli" : : : "memory"); +} + +static inline unsigned long local_save_flags(void) +{ + unsigned long flags; + + asm volatile("pushfq; popq %0" : "=r"(flags) : : "memory"); + + return flags; +} + +static inline unsigned long local_irq_save(void) +{ + unsigned long flags; + + asm volatile("pushfq; popq %0; cli" : "=r"(flags) : : "memory"); + + return flags; +} + +static inline void local_irq_restore(unsigned long flags) +{ + asm volatile("pushq %0; popfq" : : "r"(flags) : "memory", "cc"); +} + +#define local_irq_is_enabled() (!!(local_save_flags() & X86_EFLAGS_IF)) +#define local_irq_is_disabled() (!local_irq_is_enabled()) + +/* The kernel always runs in ring 0. */ +#define user_mode() (0) + +static inline void cpu_relax(void) +{ + asm volatile("pause" : : : "memory"); +} + +/* Called with IRQs on from the idle thread: hlt wakes up on the next IRQ. */ + +static inline void cpu_standby(void) +{ + wfi(); +} + +static inline u64 rdmsr(u32 msr) +{ + u32 lo, hi; + + asm volatile("rdmsr" : "=a"(lo), "=d"(hi) : "c"(msr)); + + return ((u64) hi << 32) | lo; +} + +static inline void wrmsr(u32 msr, u64 val) +{ + asm volatile("wrmsr" : : "c"(msr), "a"((u32) val), "d"((u32) (val >> 32)) : "memory"); +} + +static inline u64 read_cr2(void) +{ + u64 val; + + asm volatile("mov %%cr2, %0" : "=r"(val)); + + return val; +} + +static inline u64 read_cr3(void) +{ + u64 val; + + asm volatile("mov %%cr3, %0" : "=r"(val)); + + return val; +} + +static inline void write_cr3(u64 val) +{ + asm volatile("mov %0, %%cr3" : : "r"(val) : "memory"); +} + +static inline void invlpg(addr_t va) +{ + asm volatile("invlpg (%0)" : : "r"(va) : "memory"); +} + +static inline u64 rdtsc(void) +{ + u32 lo, hi; + + asm volatile("rdtsc" : "=a"(lo), "=d"(hi)); + + return ((u64) hi << 32) | lo; +} + +struct tcb; +void __switch_to(struct tcb *prev, struct tcb *next); + +void cpu_do_idle(void); + +/* Kernel stack top that the next entry from user mode will use */ + +void x86_set_kernel_stack(addr_t sp); + +void x86_cpu_init(void); +void x86_fpu_init(void); +void x86_fpu_reset(void); + +void trap_handle(cpu_regs_t *regs); +long syscall_entry_handle(cpu_regs_t *regs); + +#endif /* __ASSEMBLY__ */ + +#endif /* PROCESSOR_H */ diff --git a/so3/so3/arch/x86/include/asm/semihosting.h b/so3/so3/arch/x86/include/asm/semihosting.h new file mode 100644 index 0000000000..ba54f3282c --- /dev/null +++ b/so3/so3/arch/x86/include/asm/semihosting.h @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2026 Daniel Rossier + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifndef ASM_SEMIHOSTING_H +#define ASM_SEMIHOSTING_H + +/* + * Leaves QEMU through the isa-debug-exit device when it is present, and + * halts otherwise. The generic code calls it when the root process exits. + */ + +void semi_exit(int code); + +#endif /* ASM_SEMIHOSTING_H */ diff --git a/so3/so3/arch/x86/include/asm/setup.h b/so3/so3/arch/x86/include/asm/setup.h new file mode 100644 index 0000000000..9b15003749 --- /dev/null +++ b/so3/so3/arch/x86/include/asm/setup.h @@ -0,0 +1,24 @@ +/* + * Copyright (C) 2026 Daniel Rossier + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifndef ASM_SETUP_H +#define ASM_SETUP_H + +void setup_arch(void); + +#endif /* ASM_SETUP_H */ diff --git a/so3/so3/arch/x86/include/asm/spinlock.h b/so3/so3/arch/x86/include/asm/spinlock.h new file mode 100644 index 0000000000..2e143cbee9 --- /dev/null +++ b/so3/so3/arch/x86/include/asm/spinlock.h @@ -0,0 +1,34 @@ +/* + * Copyright (C) 2026 Daniel Rossier + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifndef ASM_SPINLOCK_H +#define ASM_SPINLOCK_H + +#include + +static inline int spin_trylock(spinlock_t *lock) +{ + return !__atomic_exchange_n(&lock->lock, 1, __ATOMIC_ACQUIRE); +} + +static inline void spin_unlock(spinlock_t *lock) +{ + __atomic_store_n(&lock->lock, 0, __ATOMIC_RELEASE); +} + +#endif /* ASM_SPINLOCK_H */ diff --git a/so3/so3/arch/x86/include/asm/types.h b/so3/so3/arch/x86/include/asm/types.h new file mode 100644 index 0000000000..4c26cee57c --- /dev/null +++ b/so3/so3/arch/x86/include/asm/types.h @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2014-2019 Daniel Rossier + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#ifndef __ASM_ARM_TYPES_H +#define __ASM_ARM_TYPES_H + +typedef unsigned short umode_t; + +#define BITS_PER_INT 32 + +/* + * __xx is ok: it doesn't pollute the POSIX namespace. Use these in the + * header files exported to user space + */ + +typedef __signed__ char __s8; +typedef unsigned char __u8; + +typedef __signed__ short __s16; +typedef unsigned short __u16; + +typedef __signed__ int __s32; +typedef unsigned int __u32; + +typedef __signed__ long __s64; +typedef unsigned long __u64; + +#endif diff --git a/so3/so3/arch/x86/lib/Makefile b/so3/so3/arch/x86/lib/Makefile new file mode 100644 index 0000000000..774db5412e --- /dev/null +++ b/so3/so3/arch/x86/lib/Makefile @@ -0,0 +1,2 @@ + +obj-y += strchr.o findbit.o diff --git a/so3/so3/arch/x86/lib/findbit.c b/so3/so3/arch/x86/lib/findbit.c new file mode 100644 index 0000000000..20fe07fcb2 --- /dev/null +++ b/so3/so3/arch/x86/lib/findbit.c @@ -0,0 +1,178 @@ +/* find_next_bit.c: fallback find next bit implementation + * + * Copyright (C) 2004 Red Hat, Inc. All Rights Reserved. + * Written by David Howells (dhowells@redhat.com) + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version + * 2 of the License, or (at your option) any later version. + */ + +/* Based on linux/include/asm-generic/bitops/builtin-__ffs.h */ + +#include +#include + +/** + * __ffs - find first bit in word. + * @word: The word to search + * + * Undefined if no bit exists, so code should check against 0 first. + */ + +static inline unsigned long __ffs(unsigned long word) +{ + return __builtin_ctzl(word); +} + +/* Based on linux/include/asm-generic/bitops/ffz.h */ +/* + * ffz - find first zero in word. + * @word: The word to search + * + * Undefined if no zero exists, so code should check against ~0UL first. + */ +#define ffz(x) __ffs(~(x)) + +static inline int flsl(unsigned long x) +{ + return x ? BITS_PER_LONG - __builtin_clzl(x) : 0; +} + +/* + * Find the next set bit in a memory region. + */ + +unsigned long _find_next_bit(const unsigned long *addr, unsigned long size, unsigned long offset) +{ + const unsigned long *p = addr + BIT_WORD(offset); + unsigned long result = offset & ~(BITS_PER_LONG - 1); + unsigned long tmp; + + if (offset >= size) + return size; + size -= result; + offset %= BITS_PER_LONG; + if (offset) { + tmp = *(p++); + tmp &= (~0UL << offset); + if (size < BITS_PER_LONG) + goto found_first; + if (tmp) + goto found_middle; + size -= BITS_PER_LONG; + result += BITS_PER_LONG; + } + while (size & ~(BITS_PER_LONG - 1)) { + if ((tmp = *(p++))) + goto found_middle; + result += BITS_PER_LONG; + size -= BITS_PER_LONG; + } + if (!size) + return result; + tmp = *p; + +found_first: + tmp &= (~0UL >> (BITS_PER_LONG - size)); + if (tmp == 0UL) /* Are any bits set? */ + return result + size; /* Nope. */ +found_middle: + return result + __ffs(tmp); +} + +/* + * This implementation of find_{first,next}_zero_bit was stolen from + * Linus' asm-alpha/bitops.h. + */ + +unsigned long _find_next_zero_bit(const unsigned long *addr, unsigned long size, unsigned long offset) +{ + const unsigned long *p = addr + BIT_WORD(offset); + unsigned long result = offset & ~(BITS_PER_LONG - 1); + unsigned long tmp; + + if (offset >= size) + return size; + size -= result; + offset %= BITS_PER_LONG; + if (offset) { + tmp = *(p++); + tmp |= ~0UL >> (BITS_PER_LONG - offset); + if (size < BITS_PER_LONG) + goto found_first; + if (~tmp) + goto found_middle; + size -= BITS_PER_LONG; + result += BITS_PER_LONG; + } + while (size & ~(BITS_PER_LONG - 1)) { + if (~(tmp = *(p++))) + goto found_middle; + result += BITS_PER_LONG; + size -= BITS_PER_LONG; + } + if (!size) + return result; + tmp = *p; + +found_first: + tmp |= ~0UL << size; + if (tmp == ~0UL) /* Are any bits zero? */ + return result + size; /* Nope. */ +found_middle: + return result + ffz(tmp); +} + +/* + * Find the first set bit in a memory region. + */ + +unsigned long _find_first_bit(const unsigned long *addr, unsigned long size) +{ + const unsigned long *p = addr; + unsigned long result = 0; + unsigned long tmp; + + while (size & ~(BITS_PER_LONG - 1)) { + if ((tmp = *(p++))) + goto found; + result += BITS_PER_LONG; + size -= BITS_PER_LONG; + } + if (!size) + return result; + + tmp = (*p) & (~0UL >> (BITS_PER_LONG - size)); + if (tmp == 0UL) /* Are any bits set? */ + return result + size; /* Nope. */ +found: + return result + __ffs(tmp); +} + +/* + * Find the first cleared bit in a memory region. + */ + +unsigned long _find_first_zero_bit(const unsigned long *addr, unsigned long size) +{ + const unsigned long *p = addr; + unsigned long result = 0; + unsigned long tmp; + + while (size & ~(BITS_PER_LONG - 1)) { + if (~(tmp = *(p++))) + goto found; + result += BITS_PER_LONG; + size -= BITS_PER_LONG; + } + if (!size) + return result; + + tmp = (*p) | (~0UL << size); + if (tmp == ~0UL) /* Are any bits zero? */ + return result + size; /* Nope. */ +found: + return result + ffz(tmp); +} diff --git a/so3/so3/arch/x86/lib/strchr.c b/so3/so3/arch/x86/lib/strchr.c new file mode 100644 index 0000000000..7bde958b09 --- /dev/null +++ b/so3/so3/arch/x86/lib/strchr.c @@ -0,0 +1,24 @@ +/* + * Copyright (C) 2026 REDS Institute - HEIG-VD + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + +#include + +char *strchr(const char *s, int c) +{ + for (;; s++) { + if (*s == (char) c) + return (char *) s; + if (!*s) + return NULL; + } +} diff --git a/so3/so3/arch/x86/mmu.c b/so3/so3/arch/x86/mmu.c new file mode 100644 index 0000000000..c651b16ad0 --- /dev/null +++ b/so3/so3/arch/x86/mmu.c @@ -0,0 +1,397 @@ +/* + * Copyright (C) 2026 Daniel Rossier + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include + +void *__current_pgtable = NULL; + +void *current_pgtable(void) +{ + return __current_pgtable; +} + +static u64 *alloc_pgtable(void) +{ + u64 *pgtable; + + pgtable = (u64 *) memalign(PAGE_SIZE, PAGE_SIZE); + if (!pgtable) { + printk("%s: heap overflow...\n", __func__); + kernel_panic(); + } + + memset(pgtable, 0, PAGE_SIZE); + + return pgtable; +} + +/* + * Intermediate entries grant everything: the leaf decides. User-half tables + * carry the U/S bit so that user leaves below them are reachable. + */ + +static u64 table_flags(addr_t vaddr) +{ + return PTE_PRESENT | PTE_RW | (user_space_vaddr(vaddr) ? PTE_USER : 0); +} + +static u64 leaf_flags(addr_t vaddr, bool nocache) +{ + return table_flags(vaddr) | (nocache ? (PTE_PCD | PTE_PWT) : 0); +} + +/* Return the next-level table of @pte, allocating it if needed */ + +static u64 *get_next_table(u64 *pte, addr_t vaddr) +{ + if (!*pte) + *pte = __pa(alloc_pgtable()) | table_flags(vaddr); + + return (u64 *) __va(*pte & PTE_ADDR_MASK); +} + +/* + * New kernel L0 entries are created in the system page table; a process + * page table which is currently loaded must see them at once. + */ + +static void sync_current_kernel_area(void *pgtable) +{ + if ((pgtable == __sys_root_pgtable) && __current_pgtable && (__current_pgtable != (void *) __sys_root_pgtable)) + pgtable_copy_kernel_area(__current_pgtable); +} + +/* + * 2 MB pages are used for the kernel half when the alignment allows it. + * User space stays page-grained, as fork() duplicates it page by page. + */ + +void create_mapping(void *pgtable, addr_t virt_base, addr_t phys_base, size_t size, bool nocache) +{ + addr_t addr, end; + u64 *l1, *l2, *l3, *pte; + + if (pgtable == NULL) + pgtable = __sys_root_pgtable; + + BUG_ON(!size); + + addr = virt_base & PAGE_MASK; + phys_base &= PAGE_MASK; + end = addr + ALIGN_UP(size + (virt_base & ~PAGE_MASK), PAGE_SIZE); + + while (addr != end) { + l1 = get_next_table(l0pte_offset(pgtable, addr), addr); + l2 = get_next_table(l1 + l1pte_index(addr), addr); + pte = l2 + l2pte_index(addr); + + if (!user_space_vaddr(addr) && !((addr | phys_base) & BLOCK_2M_OFFSET) && (end - addr >= SZ_2M) && + (!*pte || (*pte & PTE_PS))) { + *pte = phys_base | leaf_flags(addr, nocache) | PTE_PS; + invlpg(addr); + + addr += SZ_2M; + phys_base += SZ_2M; + continue; + } + + /* A 2 MB page being remapped with a finer granularity */ + + if (*pte & PTE_PS) + *pte = 0; + + l3 = get_next_table(pte, addr); + l3[l3pte_index(addr)] = phys_base | leaf_flags(addr, nocache); + invlpg(addr); + + addr += PAGE_SIZE; + phys_base += PAGE_SIZE; + } + + sync_current_kernel_area(pgtable); +} + +static bool empty_table(u64 *table) +{ + int i; + + for (i = 0; i < TTB_L0_ENTRIES; i++) + if (table[i]) + return false; + + return true; +} + +/* + * Tables of the kernel half are shared by every root page table: they are + * never freed here, only the user ones are. + */ + +void release_mapping(void *pgtable, addr_t vaddr, size_t size) +{ + addr_t end; + u64 *l0e, *l1e, *l2e; + u64 *l1, *l2, *l3; + bool user; + + if (pgtable == NULL) + pgtable = __sys_root_pgtable; + + end = (vaddr & PAGE_MASK) + ALIGN_UP(size + (vaddr & ~PAGE_MASK), PAGE_SIZE); + vaddr &= PAGE_MASK; + + while (vaddr < end) { + user = user_space_vaddr(vaddr); + + l0e = l0pte_offset(pgtable, vaddr); + if (!*l0e) { + vaddr = l0_addr_end(vaddr, end); + continue; + } + + l1 = (u64 *) __va(*l0e & PTE_ADDR_MASK); + l1e = l1 + l1pte_index(vaddr); + if (!*l1e) { + vaddr = l1_addr_end(vaddr, end); + continue; + } + + l2 = (u64 *) __va(*l1e & PTE_ADDR_MASK); + l2e = l2 + l2pte_index(vaddr); + if (!*l2e) { + vaddr = l2_addr_end(vaddr, end); + continue; + } + + if (*l2e & PTE_PS) { + *l2e = 0; + invlpg(vaddr); + vaddr = l2_addr_end(vaddr, end); + } else { + l3 = (u64 *) __va(*l2e & PTE_ADDR_MASK); + l3[l3pte_index(vaddr)] = 0; + invlpg(vaddr); + vaddr += PAGE_SIZE; + + if (user && empty_table(l3)) { + *l2e = 0; + free(l3); + } + } + + if (user && empty_table(l2)) { + *l1e = 0; + free(l2); + } + + if (user && empty_table(l1)) { + *l0e = 0; + free(l1); + } + } +} + +void *new_root_pgtable(void) +{ + return alloc_pgtable(); +} + +void copy_root_pgtable(void *dst, void *src) +{ + memcpy(dst, src, TTB_L0_SIZE); + + if (__pa(dst) == (read_cr3() & PTE_ADDR_MASK)) + flush_tlb_all(); +} + +void pgtable_copy_kernel_area(void *pgtable) +{ + memcpy((u64 *) pgtable + TTB_L0_KERNEL_FIRST, (u64 *) __sys_root_pgtable + TTB_L0_KERNEL_FIRST, + (TTB_L0_ENTRIES - TTB_L0_KERNEL_FIRST) * sizeof(u64)); +} + +static void free_user_tables(u64 *table, int level) +{ + int i; + + for (i = 0; i < TTB_L0_ENTRIES; i++) { + if (!table[i]) + continue; + + if (level < 2 && !(table[i] & PTE_PS)) + free_user_tables((u64 *) __va(table[i] & PTE_ADDR_MASK), level + 1); + else if (level == 2 && !(table[i] & PTE_PS)) + free((void *) __va(table[i] & PTE_ADDR_MASK)); + } + + free(table); +} + +/* Drop the user half; the shared kernel half is kept */ + +void reset_root_pgtable(void *pgtable, bool remove) +{ + u64 *root = (u64 *) pgtable; + int i; + + for (i = 0; i < TTB_L0_KERNEL_FIRST; i++) { + if (root[i]) { + free_user_tables((u64 *) __va(root[i] & PTE_ADDR_MASK), 1); + root[i] = 0; + } + } + + if (__pa(pgtable) == (read_cr3() & PTE_ADDR_MASK)) + flush_tlb_all(); + + if (remove) + free(pgtable); +} + +void ramdev_create_mapping(void *root_pgtable, addr_t ramdev_start, addr_t ramdev_end) +{ + if (valid_ramdev()) + create_mapping(root_pgtable, RAMDEV_VADDR, ramdev_start, ramdev_end - ramdev_start, false); +} + +addr_t virt_to_phys_pt(addr_t vaddr) +{ + u64 *root, *l1e, *l2e, *l3e, *l0e; + addr_t offset = vaddr & ~PAGE_MASK; + + root = (user_space_vaddr(vaddr) && __current_pgtable) ? (u64 *) __current_pgtable : (u64 *) __sys_root_pgtable; + + l0e = l0pte_offset(root, vaddr); + BUG_ON(!*l0e); + + l1e = l1pte_offset(l0e, vaddr); + BUG_ON(!*l1e); + + if (*l1e & PTE_PS) + return (*l1e & TTB_L1_BLOCK_ADDR_MASK) | (vaddr & BLOCK_1G_OFFSET); + + l2e = l2pte_offset(l1e, vaddr); + BUG_ON(!*l2e); + + if (*l2e & PTE_PS) + return (*l2e & TTB_L2_BLOCK_ADDR_MASK) | (vaddr & BLOCK_2M_OFFSET); + + l3e = l3pte_offset(l2e, vaddr); + BUG_ON(!*l3e); + + return (*l3e & TTB_L3_PAGE_ADDR_MASK) | offset; +} + +/* Load a process page table, with the kernel half brought up to date */ + +void mmu_switch(void *pgtable_paddr) +{ + pgtable_copy_kernel_area((void *) __va(pgtable_paddr)); + write_cr3((u64) pgtable_paddr); +} + +void mmu_switch_kernel(void *pgtable) +{ + write_cr3(__pa(pgtable)); +} + +static void duplicate_level(u64 *from, u64 *to, int level, addr_t vaddr, pcb_t *pcb_to) +{ + u64 *child; + addr_t paddr, __vaddr; + int i, last; + + last = (level == 0) ? TTB_L0_KERNEL_FIRST : TTB_L0_ENTRIES; + + for (i = 0; i < last; i++) { + if (!from[i]) + continue; + + __vaddr = vaddr + ((addr_t) i << (TTB_I0_SHIFT - 9 * level)); + + if (level < 3) { + BUG_ON(from[i] & PTE_PS); + + child = alloc_pgtable(); + to[i] = (from[i] & ~PTE_ADDR_MASK) | __pa(child); + + duplicate_level((u64 *) __va(from[i] & PTE_ADDR_MASK), child, level + 1, __vaddr, pcb_to); + } else { + paddr = get_free_page(); + BUG_ON(!paddr); + + to[i] = (from[i] & ~PTE_ADDR_MASK) | paddr; + + add_page_to_proc(pcb_to, (page_t *) phys_to_page(paddr)); + + create_mapping(NULL, FIXMAP_MAPPING, paddr, PAGE_SIZE, false); + memcpy((void *) FIXMAP_MAPPING, (void *) __vaddr, PAGE_SIZE); + } + } +} + +/* Copy the whole user space of @from (the current process) into @to */ + +void duplicate_user_space(pcb_t *from, pcb_t *to) +{ + duplicate_level((u64 *) from->pgtable, (u64 *) to->pgtable, 0, 0, to); + + release_mapping(NULL, FIXMAP_MAPPING, PAGE_SIZE); +} + +void dump_pgtable(void *pgtable) +{ + u64 *root = pgtable ? (u64 *) pgtable : (u64 *) __sys_root_pgtable; + u64 *l1, *l2; + int i, j, k; + + lprintk(" ***** Page table dump *****\n"); + + for (i = 0; i < TTB_L0_ENTRIES; i++) { + if (!root[i]) + continue; + + lprintk(" - L0[%d] %lx\n", i, root[i]); + l1 = (u64 *) __va(root[i] & PTE_ADDR_MASK); + + for (j = 0; j < TTB_L1_ENTRIES; j++) { + if (!l1[j]) + continue; + + lprintk(" - L1[%d] %lx\n", j, l1[j]); + if (l1[j] & PTE_PS) + continue; + + l2 = (u64 *) __va(l1[j] & PTE_ADDR_MASK); + for (k = 0; k < TTB_L2_ENTRIES; k++) + if (l2[k]) + lprintk(" - L2[%d] %lx\n", k, l2[k]); + } + } +} diff --git a/so3/so3/arch/x86/setup.c b/so3/so3/arch/x86/setup.c new file mode 100644 index 0000000000..0474fba456 --- /dev/null +++ b/so3/so3/arch/x86/setup.c @@ -0,0 +1,383 @@ +/* + * Copyright (C) 2026 Daniel Rossier + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +/* + * x86_64 bootstrap: CPU tables, multiboot2 boot information and the + * device tree handed over to the generic code. + * + * GRUB loads the device tree and the root filesystem as multiboot2 modules + * named "dtb" and "rootfs". The memory size and the location of the root + * filesystem are written into the device tree, as U-Boot does on ARM. + */ + +#include +#include +#include + +#include + +#include + +#include +#include +#include +#include + +#define MB2_TAG_END 0 +#define MB2_TAG_CMDLINE 1 +#define MB2_TAG_MODULE 3 +#define MB2_TAG_MMAP 6 + +#define MB2_MEMORY_AVAILABLE 1 + +/* Room left in the device tree for the properties added at boot */ + +#define X86_FDT_SIZE SZ_64K + +/* The early 1 GB mapping from head.S bounds what can be reached at boot */ + +#define X86_BOOT_MAPPED SZ_1G + +struct mb2_tag { + u32 type; + u32 size; +}; + +struct mb2_tag_module { + u32 type; + u32 size; + u32 mod_start; + u32 mod_end; + char cmdline[]; +}; + +struct mb2_mmap_entry { + u64 addr; + u64 len; + u32 type; + u32 zero; +}; + +struct mb2_tag_mmap { + u32 type; + u32 size; + u32 entry_size; + u32 entry_version; + struct mb2_mmap_entry entries[]; +}; + +struct x86_tss { + u32 reserved0; + u64 rsp0; + u64 rsp1; + u64 rsp2; + u64 reserved1; + u64 ist[7]; + u64 reserved2; + u16 reserved3; + u16 iomap_base; +} __attribute__((packed)); + +struct x86_idt_entry { + u16 offset_lo; + u16 selector; + u8 ist; + u8 type_attr; + u16 offset_mid; + u32 offset_hi; + u32 zero; +} __attribute__((packed)); + +struct x86_desc_ptr { + u16 limit; + u64 base; +} __attribute__((packed)); + +extern char x86_idt_stubs[]; +extern void x86_syscall_entry(void); +extern u64 x86_kernel_rsp; + +/* Device tree used by the generic code, set by early_memory_init() */ + +void *__fdt_addr; + +static u64 gdt[7] __attribute__((aligned(16))); +static struct x86_tss tss __attribute__((aligned(16))); +static struct x86_idt_entry idt[256] __attribute__((aligned(16))); + +static u8 x86_fdt[X86_FDT_SIZE] __attribute__((aligned(8))); + +void kernel_start(void); +void x86_fpu_init(void); + +void x86_set_kernel_stack(addr_t sp) +{ + tss.rsp0 = sp; + x86_kernel_rsp = sp; +} + +/* + * Flat GDT: kernel code/data, then user data/code in the order SYSRET + * expects, then the 16-byte TSS descriptor. + */ + +static void gdt_init(void) +{ + struct x86_desc_ptr gdtr; + u64 base = (u64) &tss; + u64 limit = sizeof(tss) - 1; + + gdt[0] = 0; + gdt[1] = 0x00af9a000000ffffUL; /* KERNEL_CS */ + gdt[2] = 0x00cf92000000ffffUL; /* KERNEL_DS */ + gdt[3] = 0x00cff2000000ffffUL; /* USER_DS */ + gdt[4] = 0x00affa000000ffffUL; /* USER_CS */ + + gdt[5] = (limit & 0xffff) | ((base & 0xffffff) << 16) | (0x89UL << 40) | (((limit >> 16) & 0xf) << 48) | + (((base >> 24) & 0xff) << 56); + gdt[6] = base >> 32; + + tss.iomap_base = sizeof(tss); + + gdtr.limit = sizeof(gdt) - 1; + gdtr.base = (u64) gdt; + + asm volatile("lgdt %0\n" + "mov %1, %%ds\n" + "mov %1, %%es\n" + "mov %1, %%ss\n" + "pushq %2\n" + "leaq 1f(%%rip), %%rax\n" + "pushq %%rax\n" + "lretq\n" + "1:\n" + : + : "m"(gdtr), "r"((u64) KERNEL_DS), "i"(KERNEL_CS) + : "rax", "memory"); + + asm volatile("ltr %w0" : : "r"(TSS_SEL)); +} + +static void idt_set_gate(int vec, addr_t handler, u8 type_attr) +{ + idt[vec].offset_lo = handler & 0xffff; + idt[vec].selector = KERNEL_CS; + idt[vec].ist = 0; + idt[vec].type_attr = type_attr; + idt[vec].offset_mid = (handler >> 16) & 0xffff; + idt[vec].offset_hi = handler >> 32; + idt[vec].zero = 0; +} + +/* Interrupt gates only: IF is cleared on every entry, as on ARM. */ + +static void idt_init(void) +{ + struct x86_desc_ptr idtr; + int i; + + for (i = 0; i < 48; i++) + idt_set_gate(i, (addr_t) x86_idt_stubs + i * 16, 0x8e); + + idtr.limit = sizeof(idt) - 1; + idtr.base = (u64) idt; + + asm volatile("lidt %0" : : "m"(idtr)); +} + +static void cpu_features_init(void) +{ + u64 cr0, cr4; + + /* FPU and SSE for user space; the kernel itself is built without them */ + + asm volatile("mov %%cr0, %0" : "=r"(cr0)); + cr0 &= ~(X86_CR0_EM | X86_CR0_TS); + cr0 |= X86_CR0_MP | X86_CR0_NE; + asm volatile("mov %0, %%cr0" : : "r"(cr0)); + + asm volatile("mov %%cr4, %0" : "=r"(cr4)); + cr4 |= X86_CR4_OSFXSR | X86_CR4_OSXMMEXCPT; + asm volatile("mov %0, %%cr4" : : "r"(cr4)); + + x86_fpu_init(); + + /* syscall/sysret: kernel selectors in STAR[47:32], user base in STAR[63:48] */ + + wrmsr(MSR_EFER, rdmsr(MSR_EFER) | EFER_SCE); + wrmsr(MSR_STAR, ((u64) (KERNEL_DS | 3) << 48) | ((u64) KERNEL_CS << 32)); + wrmsr(MSR_LSTAR, (u64) x86_syscall_entry); + wrmsr(MSR_SFMASK, X86_EFLAGS_IF | X86_EFLAGS_DF | X86_EFLAGS_TF); + + wrmsr(MSR_FS_BASE, 0); + wrmsr(MSR_GS_BASE, 0); +} + +static void *mb2_va(u64 paddr) +{ + return (void *) (CONFIG_KERNEL_VADDR + paddr); +} + +/* End of the usable RAM region which holds the kernel */ + +static u64 mb2_ram_end(struct mb2_tag_mmap *mmap) +{ + struct mb2_mmap_entry *e; + u8 *p; + u64 kernel_paddr = __pa(__end); + + for (p = (u8 *) mmap->entries; p < (u8 *) mmap + mmap->size; p += mmap->entry_size) { + e = (struct mb2_mmap_entry *) p; + + if ((e->type == MB2_MEMORY_AVAILABLE) && (e->addr <= kernel_paddr) && (e->addr + e->len > kernel_paddr)) + return (e->addr + e->len) & PAGE_MASK; + } + + return 0; +} + +static void fdt_check(int err, const char *what) +{ + if (err < 0) { + lprintk("x86 boot: %s: %s\n", what, fdt_strerror(err)); + kernel_panic(); + } +} + +static void fdt_set_reg64(void *fdt, const char *path, const char *name, u64 val) +{ + int offset; + + offset = fdt_path_offset(fdt, path); + if (offset == -FDT_ERR_NOTFOUND) + offset = fdt_add_subnode(fdt, 0, path + 1); + fdt_check(offset, path); + + fdt_check(fdt_setprop_u64(fdt, offset, name, val), name); +} + +/* + * Parse the boot information and build the device tree passed to the + * generic code. The boot information and the modules may lie right after + * the kernel image, where the generic code puts the device tree and the frame + * table: everything needed is copied or moved away first. + */ + +static void mb2_setup(u32 mbi_paddr) +{ + struct mb2_tag *tag; + struct mb2_tag_module *mod; + struct mb2_tag_module *dtb_mod = NULL, *rootfs_mod = NULL; + struct mb2_tag_mmap *mmap = NULL; + u64 ram_end, rootfs_size = 0, rootfs_paddr = 0; + fdt64_t reg[2]; + int offset; + + tag = (struct mb2_tag *) mb2_va(mbi_paddr + 8); + + while (tag->type != MB2_TAG_END) { + switch (tag->type) { + case MB2_TAG_MODULE: + mod = (struct mb2_tag_module *) tag; + + if (!strcmp(mod->cmdline, "dtb")) + dtb_mod = mod; + else if (!strcmp(mod->cmdline, "rootfs")) + rootfs_mod = mod; + break; + + case MB2_TAG_MMAP: + mmap = (struct mb2_tag_mmap *) tag; + break; + } + + tag = (struct mb2_tag *) ALIGN_UP((addr_t) tag + tag->size, 8); + } + + if (!dtb_mod) { + lprintk("x86 boot: no \"dtb\" multiboot2 module, cannot go further.\n"); + kernel_panic(); + } + + if (!mmap) { + lprintk("x86 boot: no memory map from the bootloader.\n"); + kernel_panic(); + } + + fdt_check(fdt_open_into(mb2_va(dtb_mod->mod_start), x86_fdt, sizeof(x86_fdt)), "dtb"); + + ram_end = mb2_ram_end(mmap); + if (!ram_end) { + lprintk("x86 boot: the kernel is not in usable RAM.\n"); + kernel_panic(); + } + + if (ram_end > X86_BOOT_MAPPED) + ram_end = X86_BOOT_MAPPED; + + /* The root filesystem goes to the top of the RAM, out of the way. */ + + if (rootfs_mod) { + rootfs_size = rootfs_mod->mod_end - rootfs_mod->mod_start; + rootfs_paddr = (ram_end - rootfs_size) & PAGE_MASK; + + memmove(mb2_va(rootfs_paddr), mb2_va(rootfs_mod->mod_start), rootfs_size); + } + + /* RAM seen by SO3: from 0 to the end of the region holding the kernel */ + + offset = fdt_path_offset(x86_fdt, "/memory"); + fdt_check(offset, "/memory"); + + reg[0] = cpu_to_fdt64(0); + reg[1] = cpu_to_fdt64(ram_end); + fdt_check(fdt_setprop(x86_fdt, offset, "reg", reg, sizeof(reg)), "/memory reg"); + + if (rootfs_mod) { + fdt_set_reg64(x86_fdt, "/chosen", "linux,initrd-start", rootfs_paddr); + fdt_set_reg64(x86_fdt, "/chosen", "linux,initrd-end", rootfs_paddr + rootfs_size); + } + + fdt_pack(x86_fdt); +} + +void x86_boot(u32 mbi_paddr) +{ + gdt_init(); + idt_init(); + cpu_features_init(); + + mb2_setup(mbi_paddr); + + early_memory_init((void *) __pa(x86_fdt)); + + kernel_start(); +} + +/* QEMU isa-debug-exit device, when the machine has one (-device isa-debug-exit) */ + +#define X86_DEBUG_EXIT_PORT 0xf4 + +void semi_exit(int code) +{ + outb(X86_DEBUG_EXIT_PORT, code); + + local_irq_disable(); + while (1) + wfi(); +} diff --git a/so3/so3/arch/x86/so3.lds b/so3/so3/arch/x86/so3.lds new file mode 100644 index 0000000000..3871be2ba9 --- /dev/null +++ b/so3/so3/arch/x86/so3.lds @@ -0,0 +1,181 @@ +/* + * Linker script for the SO3 x86_64 kernel + * + * The kernel runs in the top 2 GB (KERNEL_VADDR = 0xffffffff80000000, + * required by -mcmodel=kernel) and is loaded by GRUB at the physical + * address LOAD_OFFSET, so every section has LMA = VMA - KERNEL_VADDR. + */ + +OUTPUT_FORMAT("elf64-x86-64") +OUTPUT_ARCH(i386:x86-64) +ENTRY(__start32) + +X86_LOAD_OFFSET = 0x200000; + +STACK_SIZE = (CONFIG_SYS_STACK_SIZE_KB + CONFIG_MAX_THREADS * CONFIG_THREAD_STACK_SIZE_KB) * 1024; +HEAP_SIZE = CONFIG_HEAP_SIZE_MB * 1024 * 1024; + +SECTIONS +{ + . = ENTRY_ADDR + X86_LOAD_OFFSET; + + __kernel_start = .; + + /* The multiboot2 header must lie in the first 32 KB of the file */ + + .head.text : AT(ADDR(.head.text) - ENTRY_ADDR) + { + KEEP(*(.multiboot)) + *(.head.text) + } :text + + .text : AT(ADDR(.text) - ENTRY_ADDR) + { + *(.text*) + } :text + + .rodata : AT(ADDR(.rodata) - ENTRY_ADDR) + { + *(.rodata*) + } :text + + . = ALIGN(4096); + + .root_proc_prologue : AT(ADDR(.root_proc_prologue) - ENTRY_ADDR) + { + __root_proc_start = .; + + *(.root_proc.text) + + __root_proc_end = .; + } :text + + . = ALIGN(4096); + + .data : AT(ADDR(.data) - ENTRY_ADDR) + { + *(.data*) + } :data + + /* Initcall sections, kept before .bss so that they are file-backed */ + + .initcall_driver_initcall_t_core : AT(ADDR(.initcall_driver_initcall_t_core) - ENTRY_ADDR) + { + __initcall_driver_initcall_t_core = .; + KEEP(*(.initcall_driver_initcall_t_core)); + __initcall_driver_initcall_t_core_end = .; + } :data + + .initcall_driver_initcall_t_postcore : AT(ADDR(.initcall_driver_initcall_t_postcore) - ENTRY_ADDR) + { + __initcall_driver_initcall_t_postcore = .; + KEEP(*(.initcall_driver_initcall_t_postcore)); + __initcall_driver_initcall_t_postcore_end = .; + } :data + + .initcall_pre_init_t_core : AT(ADDR(.initcall_pre_init_t_core) - ENTRY_ADDR) + { + __initcall_pre_irq_init_t_core = .; + KEEP(*(.initcall_pre_irq_init_t_core)); + __initcall_pre_irq_init_t_core_end = .; + } :data + + .initcall_postinit_t_core : AT(ADDR(.initcall_postinit_t_core) - ENTRY_ADDR) + { + __initcall_postinit_t_core = .; + KEEP(*(.initcall_postinit_t_core)); + __initcall_postinit_t_core_end = .; + } :data + + . = ALIGN(4096); + + __bss_start = .; + + .bss (NOLOAD) : AT(ADDR(.bss) - ENTRY_ADDR) + { + *(.sbss*) + *(.bss .bss.*) + *(COMMON) + + . = ALIGN(4096); + + __per_cpu_start = .; + + *(.percpu_data) + + . = ALIGN(128); + *(.percpu_data.read_mostly) + + . = ALIGN(128); + + __per_cpu_data_end = .; + + . = ALIGN(128); + + __per_cpu_end = .; + } :data + + __bss_end = .; + + /* + * Boot page tables: PML4, PDPT for the identity map, PDPT for the + * kernel map and one page directory shared by both (1 GB of 2 MB pages). + */ + + .pgtables (NOLOAD) : AT(ADDR(.pgtables) - ENTRY_ADDR) + { + . = ALIGN(4096); + + __sys_root_pgtable = .; + . += 4096; + + __sys_idmap_l1pgtable = .; + . += 4096; + + __sys_linearmap_l1pgtable = .; + . += 4096; + + __sys_linearmap_l2pgtable = .; + . += 4096; + } :data + + . = ALIGN(16384); + + .heap (NOLOAD) : AT(ADDR(.heap) - ENTRY_ADDR) + { + __heap_base_addr = .; + + . += HEAP_SIZE; + } :data + + . = ALIGN(8192); + + /* + * Each CPU has its own stack area of STACK_SIZE bytes, reserved in a + * contiguous way from __stack_bottom: CPU#0 - CPU#1 - etc. + */ + + .stack (NOLOAD) : AT(ADDR(.stack) - ENTRY_ADDR) + { + __stack_bottom = .; + + . += STACK_SIZE * CONFIG_NR_CPUS; + + __stack_top = .; + } :data + + __end = .; + + /DISCARD/ : + { + *(.note.gnu.property) + *(.comment) + *(.eh_frame) + } +} + +PHDRS +{ + text PT_LOAD FLAGS(5); /* R-X */ + data PT_LOAD FLAGS(6); /* RW- */ +} diff --git a/so3/so3/arch/x86/syscall.h.in b/so3/so3/arch/x86/syscall.h.in new file mode 100644 index 0000000000..aaa6d90f5e --- /dev/null +++ b/so3/so3/arch/x86/syscall.h.in @@ -0,0 +1,391 @@ +/* + * This files is copied from musl library and should not be included. + * Include generated/syscall_number.h instead. + * + * Original file from musl 1.2.6: arch/x86_64/bits/syscall.h.in + */ +#define __NR_read 0 +#define __NR_write 1 +#define __NR_open 2 +#define __NR_close 3 +#define __NR_stat 4 +#define __NR_fstat 5 +#define __NR_lstat 6 +#define __NR_poll 7 +#define __NR_lseek 8 +#define __NR_mmap 9 +#define __NR_mprotect 10 +#define __NR_munmap 11 +#define __NR_brk 12 +#define __NR_rt_sigaction 13 +#define __NR_rt_sigprocmask 14 +#define __NR_rt_sigreturn 15 +#define __NR_ioctl 16 +#define __NR_pread64 17 +#define __NR_pwrite64 18 +#define __NR_readv 19 +#define __NR_writev 20 +#define __NR_access 21 +#define __NR_pipe 22 +#define __NR_select 23 +#define __NR_sched_yield 24 +#define __NR_mremap 25 +#define __NR_msync 26 +#define __NR_mincore 27 +#define __NR_madvise 28 +#define __NR_shmget 29 +#define __NR_shmat 30 +#define __NR_shmctl 31 +#define __NR_dup 32 +#define __NR_dup2 33 +#define __NR_pause 34 +#define __NR_nanosleep 35 +#define __NR_getitimer 36 +#define __NR_alarm 37 +#define __NR_setitimer 38 +#define __NR_getpid 39 +#define __NR_sendfile 40 +#define __NR_socket 41 +#define __NR_connect 42 +#define __NR_accept 43 +#define __NR_sendto 44 +#define __NR_recvfrom 45 +#define __NR_sendmsg 46 +#define __NR_recvmsg 47 +#define __NR_shutdown 48 +#define __NR_bind 49 +#define __NR_listen 50 +#define __NR_getsockname 51 +#define __NR_getpeername 52 +#define __NR_socketpair 53 +#define __NR_setsockopt 54 +#define __NR_getsockopt 55 +#define __NR_clone 56 +#define __NR_fork 57 +#define __NR_vfork 58 +#define __NR_execve 59 +#define __NR_exit 60 +#define __NR_wait4 61 +#define __NR_kill 62 +#define __NR_uname 63 +#define __NR_semget 64 +#define __NR_semop 65 +#define __NR_semctl 66 +#define __NR_shmdt 67 +#define __NR_msgget 68 +#define __NR_msgsnd 69 +#define __NR_msgrcv 70 +#define __NR_msgctl 71 +#define __NR_fcntl 72 +#define __NR_flock 73 +#define __NR_fsync 74 +#define __NR_fdatasync 75 +#define __NR_truncate 76 +#define __NR_ftruncate 77 +#define __NR_getdents 78 +#define __NR_getcwd 79 +#define __NR_chdir 80 +#define __NR_fchdir 81 +#define __NR_rename 82 +#define __NR_mkdir 83 +#define __NR_rmdir 84 +#define __NR_creat 85 +#define __NR_link 86 +#define __NR_unlink 87 +#define __NR_symlink 88 +#define __NR_readlink 89 +#define __NR_chmod 90 +#define __NR_fchmod 91 +#define __NR_chown 92 +#define __NR_fchown 93 +#define __NR_lchown 94 +#define __NR_umask 95 +#define __NR_gettimeofday 96 +#define __NR_getrlimit 97 +#define __NR_getrusage 98 +#define __NR_sysinfo 99 +#define __NR_times 100 +#define __NR_ptrace 101 +#define __NR_getuid 102 +#define __NR_syslog 103 +#define __NR_getgid 104 +#define __NR_setuid 105 +#define __NR_setgid 106 +#define __NR_geteuid 107 +#define __NR_getegid 108 +#define __NR_setpgid 109 +#define __NR_getppid 110 +#define __NR_getpgrp 111 +#define __NR_setsid 112 +#define __NR_setreuid 113 +#define __NR_setregid 114 +#define __NR_getgroups 115 +#define __NR_setgroups 116 +#define __NR_setresuid 117 +#define __NR_getresuid 118 +#define __NR_setresgid 119 +#define __NR_getresgid 120 +#define __NR_getpgid 121 +#define __NR_setfsuid 122 +#define __NR_setfsgid 123 +#define __NR_getsid 124 +#define __NR_capget 125 +#define __NR_capset 126 +#define __NR_rt_sigpending 127 +#define __NR_rt_sigtimedwait 128 +#define __NR_rt_sigqueueinfo 129 +#define __NR_rt_sigsuspend 130 +#define __NR_sigaltstack 131 +#define __NR_utime 132 +#define __NR_mknod 133 +#define __NR_uselib 134 +#define __NR_personality 135 +#define __NR_ustat 136 +#define __NR_statfs 137 +#define __NR_fstatfs 138 +#define __NR_sysfs 139 +#define __NR_getpriority 140 +#define __NR_setpriority 141 +#define __NR_sched_setparam 142 +#define __NR_sched_getparam 143 +#define __NR_sched_setscheduler 144 +#define __NR_sched_getscheduler 145 +#define __NR_sched_get_priority_max 146 +#define __NR_sched_get_priority_min 147 +#define __NR_sched_rr_get_interval 148 +#define __NR_mlock 149 +#define __NR_munlock 150 +#define __NR_mlockall 151 +#define __NR_munlockall 152 +#define __NR_vhangup 153 +#define __NR_modify_ldt 154 +#define __NR_pivot_root 155 +#define __NR__sysctl 156 +#define __NR_prctl 157 +#define __NR_arch_prctl 158 +#define __NR_adjtimex 159 +#define __NR_setrlimit 160 +#define __NR_chroot 161 +#define __NR_sync 162 +#define __NR_acct 163 +#define __NR_settimeofday 164 +#define __NR_mount 165 +#define __NR_umount2 166 +#define __NR_swapon 167 +#define __NR_swapoff 168 +#define __NR_reboot 169 +#define __NR_sethostname 170 +#define __NR_setdomainname 171 +#define __NR_iopl 172 +#define __NR_ioperm 173 +#define __NR_create_module 174 +#define __NR_init_module 175 +#define __NR_delete_module 176 +#define __NR_get_kernel_syms 177 +#define __NR_query_module 178 +#define __NR_quotactl 179 +#define __NR_nfsservctl 180 +#define __NR_getpmsg 181 +#define __NR_putpmsg 182 +#define __NR_afs_syscall 183 +#define __NR_tuxcall 184 +#define __NR_security 185 +#define __NR_gettid 186 +#define __NR_readahead 187 +#define __NR_setxattr 188 +#define __NR_lsetxattr 189 +#define __NR_fsetxattr 190 +#define __NR_getxattr 191 +#define __NR_lgetxattr 192 +#define __NR_fgetxattr 193 +#define __NR_listxattr 194 +#define __NR_llistxattr 195 +#define __NR_flistxattr 196 +#define __NR_removexattr 197 +#define __NR_lremovexattr 198 +#define __NR_fremovexattr 199 +#define __NR_tkill 200 +#define __NR_time 201 +#define __NR_futex 202 +#define __NR_sched_setaffinity 203 +#define __NR_sched_getaffinity 204 +#define __NR_set_thread_area 205 +#define __NR_io_setup 206 +#define __NR_io_destroy 207 +#define __NR_io_getevents 208 +#define __NR_io_submit 209 +#define __NR_io_cancel 210 +#define __NR_get_thread_area 211 +#define __NR_lookup_dcookie 212 +#define __NR_epoll_create 213 +#define __NR_epoll_ctl_old 214 +#define __NR_epoll_wait_old 215 +#define __NR_remap_file_pages 216 +#define __NR_getdents64 217 +#define __NR_set_tid_address 218 +#define __NR_restart_syscall 219 +#define __NR_semtimedop 220 +#define __NR_fadvise64 221 +#define __NR_timer_create 222 +#define __NR_timer_settime 223 +#define __NR_timer_gettime 224 +#define __NR_timer_getoverrun 225 +#define __NR_timer_delete 226 +#define __NR_clock_settime 227 +#define __NR_clock_gettime 228 +#define __NR_clock_getres 229 +#define __NR_clock_nanosleep 230 +#define __NR_exit_group 231 +#define __NR_epoll_wait 232 +#define __NR_epoll_ctl 233 +#define __NR_tgkill 234 +#define __NR_utimes 235 +#define __NR_vserver 236 +#define __NR_mbind 237 +#define __NR_set_mempolicy 238 +#define __NR_get_mempolicy 239 +#define __NR_mq_open 240 +#define __NR_mq_unlink 241 +#define __NR_mq_timedsend 242 +#define __NR_mq_timedreceive 243 +#define __NR_mq_notify 244 +#define __NR_mq_getsetattr 245 +#define __NR_kexec_load 246 +#define __NR_waitid 247 +#define __NR_add_key 248 +#define __NR_request_key 249 +#define __NR_keyctl 250 +#define __NR_ioprio_set 251 +#define __NR_ioprio_get 252 +#define __NR_inotify_init 253 +#define __NR_inotify_add_watch 254 +#define __NR_inotify_rm_watch 255 +#define __NR_migrate_pages 256 +#define __NR_openat 257 +#define __NR_mkdirat 258 +#define __NR_mknodat 259 +#define __NR_fchownat 260 +#define __NR_futimesat 261 +#define __NR_newfstatat 262 +#define __NR_unlinkat 263 +#define __NR_renameat 264 +#define __NR_linkat 265 +#define __NR_symlinkat 266 +#define __NR_readlinkat 267 +#define __NR_fchmodat 268 +#define __NR_faccessat 269 +#define __NR_pselect6 270 +#define __NR_ppoll 271 +#define __NR_unshare 272 +#define __NR_set_robust_list 273 +#define __NR_get_robust_list 274 +#define __NR_splice 275 +#define __NR_tee 276 +#define __NR_sync_file_range 277 +#define __NR_vmsplice 278 +#define __NR_move_pages 279 +#define __NR_utimensat 280 +#define __NR_epoll_pwait 281 +#define __NR_signalfd 282 +#define __NR_timerfd_create 283 +#define __NR_eventfd 284 +#define __NR_fallocate 285 +#define __NR_timerfd_settime 286 +#define __NR_timerfd_gettime 287 +#define __NR_accept4 288 +#define __NR_signalfd4 289 +#define __NR_eventfd2 290 +#define __NR_epoll_create1 291 +#define __NR_dup3 292 +#define __NR_pipe2 293 +#define __NR_inotify_init1 294 +#define __NR_preadv 295 +#define __NR_pwritev 296 +#define __NR_rt_tgsigqueueinfo 297 +#define __NR_perf_event_open 298 +#define __NR_recvmmsg 299 +#define __NR_fanotify_init 300 +#define __NR_fanotify_mark 301 +#define __NR_prlimit64 302 +#define __NR_name_to_handle_at 303 +#define __NR_open_by_handle_at 304 +#define __NR_clock_adjtime 305 +#define __NR_syncfs 306 +#define __NR_sendmmsg 307 +#define __NR_setns 308 +#define __NR_getcpu 309 +#define __NR_process_vm_readv 310 +#define __NR_process_vm_writev 311 +#define __NR_kcmp 312 +#define __NR_finit_module 313 +#define __NR_sched_setattr 314 +#define __NR_sched_getattr 315 +#define __NR_renameat2 316 +#define __NR_seccomp 317 +#define __NR_getrandom 318 +#define __NR_memfd_create 319 +#define __NR_kexec_file_load 320 +#define __NR_bpf 321 +#define __NR_execveat 322 +#define __NR_userfaultfd 323 +#define __NR_membarrier 324 +#define __NR_mlock2 325 +#define __NR_copy_file_range 326 +#define __NR_preadv2 327 +#define __NR_pwritev2 328 +#define __NR_pkey_mprotect 329 +#define __NR_pkey_alloc 330 +#define __NR_pkey_free 331 +#define __NR_statx 332 +#define __NR_io_pgetevents 333 +#define __NR_rseq 334 +#define __NR_uretprobe 335 +#define __NR_uprobe 336 +#define __NR_pidfd_send_signal 424 +#define __NR_io_uring_setup 425 +#define __NR_io_uring_enter 426 +#define __NR_io_uring_register 427 +#define __NR_open_tree 428 +#define __NR_move_mount 429 +#define __NR_fsopen 430 +#define __NR_fsconfig 431 +#define __NR_fsmount 432 +#define __NR_fspick 433 +#define __NR_pidfd_open 434 +#define __NR_clone3 435 +#define __NR_close_range 436 +#define __NR_openat2 437 +#define __NR_pidfd_getfd 438 +#define __NR_faccessat2 439 +#define __NR_process_madvise 440 +#define __NR_epoll_pwait2 441 +#define __NR_mount_setattr 442 +#define __NR_quotactl_fd 443 +#define __NR_landlock_create_ruleset 444 +#define __NR_landlock_add_rule 445 +#define __NR_landlock_restrict_self 446 +#define __NR_memfd_secret 447 +#define __NR_process_mrelease 448 +#define __NR_futex_waitv 449 +#define __NR_set_mempolicy_home_node 450 +#define __NR_cachestat 451 +#define __NR_fchmodat2 452 +#define __NR_map_shadow_stack 453 +#define __NR_futex_wake 454 +#define __NR_futex_wait 455 +#define __NR_futex_requeue 456 +#define __NR_statmount 457 +#define __NR_listmount 458 +#define __NR_lsm_get_self_attr 459 +#define __NR_lsm_set_self_attr 460 +#define __NR_lsm_list_modules 461 +#define __NR_mseal 462 +#define __NR_setxattrat 463 +#define __NR_getxattrat 464 +#define __NR_listxattrat 465 +#define __NR_removexattrat 466 +#define __NR_open_tree_attr 467 +#define __NR_file_getattr 468 +#define __NR_file_setattr 469 +#define __NR_listns 470 + diff --git a/so3/so3/arch/x86/syscalls.c b/so3/so3/arch/x86/syscalls.c new file mode 100644 index 0000000000..d53f387983 --- /dev/null +++ b/so3/so3/arch/x86/syscalls.c @@ -0,0 +1,56 @@ +/* + * Copyright (C) 2026 Daniel Rossier + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +/* + * Path syscalls that x86_64 still has and musl prefers over their *at + * versions, which are the only ones SO3 implements. SO3 has no symbolic + * links, so lstat is stat. + */ + +#include +#include + +SYSCALL_DEFINE2(stat, const char *, path, struct stat *, st) +{ + return sys_do_newfstatat(AT_FDCWD, path, st, 0); +} + +SYSCALL_DEFINE2(lstat, const char *, path, struct stat *, st) +{ + return sys_do_newfstatat(AT_FDCWD, path, st, 0); +} + +SYSCALL_DEFINE2(mkdir, const char *, path, mode_t, mode) +{ + return sys_do_mkdirat(AT_FDCWD, path, mode); +} + +SYSCALL_DEFINE1(rmdir, const char *, path) +{ + return sys_do_unlinkat(AT_FDCWD, path, AT_REMOVEDIR); +} + +SYSCALL_DEFINE1(unlink, const char *, path) +{ + return sys_do_unlinkat(AT_FDCWD, path, 0); +} + +SYSCALL_DEFINE2(rename, const char *, oldpath, const char *, newpath) +{ + return sys_do_renameat(AT_FDCWD, oldpath, AT_FDCWD, newpath); +} diff --git a/so3/so3/arch/x86/thread.c b/so3/so3/arch/x86/thread.c new file mode 100644 index 0000000000..6424c2b8f4 --- /dev/null +++ b/so3/so3/arch/x86/thread.c @@ -0,0 +1,191 @@ +/* + * Copyright (C) 2026 Daniel Rossier + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#include +#include +#include + +#include + +void __x86_switch_stack(u64 *prev_ksp, u64 next_ksp); + +/* FPU/SSE state of a thread which starts from scratch (fninit + default MXCSR) */ + +static u8 fpu_init_image[X86_FXSAVE_SIZE] __attribute__((aligned(16))); + +/* Called once at boot, after the FPU/SSE units have been enabled */ + +void x86_fpu_init(void) +{ + u32 mxcsr = 0x1f80; + + asm volatile("fninit\n" + "ldmxcsr %1\n" + "fxsave64 (%0)\n" + : + : "r"(fpu_init_image), "m"(mxcsr) + : "memory"); +} + +void x86_fpu_reset(void) +{ + asm volatile("fxrstor64 (%0)" : : "r"(fpu_init_image) : "memory"); +} + +/* + * Lay out the initial kernel stack of a thread as __x86_switch_stack() + * leaves it: return address, six callee-saved registers, then the FXSAVE + * image followed by the stack pointer to restore. + */ + +static void prepare_switch_frame(tcb_t *tcb, addr_t base, addr_t entry, u64 rbx, u64 r12, bool inherit_fpu) +{ + u64 *sp = (u64 *) base; + u8 *fx; + + *--sp = entry; + *--sp = 0; /* rbp */ + *--sp = rbx; + *--sp = r12; + *--sp = 0; /* r13 */ + *--sp = 0; /* r14 */ + *--sp = 0; /* r15 */ + + fx = (u8 *) (((addr_t) sp - X86_FXSAVE_SIZE - 16) & ~15UL); + + if (inherit_fpu) + asm volatile("fxsave64 (%0)" : : "r"(fx) : "memory"); + else + memcpy(fx, fpu_init_image, X86_FXSAVE_SIZE); + + *(u64 *) (fx + X86_FXSAVE_SIZE) = (u64) sp; + + tcb->cpu_regs.ksp = (u64) fx; +} + +/** + * Set the CPU registers with thread related information + * + * @param tcb Thread to set CPU registers + * @param args Clone arguments with information about the thread + */ + +void arch_prepare_cpu_regs(tcb_t *tcb, clone_args_t *args) +{ + cpu_regs_t *user_regs; + + if (args->pcb == NULL) { + /* Kernel thread must have a function to call */ + + BUG_ON(args->fn == NULL); + + tcb->cpu_regs.fs_base = 0; + + prepare_switch_frame(tcb, get_kernel_stack_top(tcb->stack_slotID), (addr_t) __thread_prologue_kernel, + (u64) args->fn, (u64) args->fn_arg, false); + return; + } + + user_regs = (cpu_regs_t *) arch_get_kernel_stack_frame(tcb); + + if (args->fn) { + /* Special userspace case to start root process. */ + + BUG_ON(args->stack == 0); + arch_restart_user_thread(tcb, args->fn, args->stack); + + prepare_switch_frame(tcb, (addr_t) user_regs, (addr_t) ret_from_fork, 0, 0, false); + return; + } + + /* fork() or clone(): start from a copy of the caller's user registers */ + + *user_regs = *(cpu_regs_t *) arch_get_kernel_stack_frame(current()); + + if (args->stack) + user_regs->rsp = args->stack; + + tcb->cpu_regs.fs_base = (args->flags & CLONE_SETTLS) ? args->tls : rdmsr(MSR_FS_BASE); + + /* Return value 0 for the new thread */ + + user_regs->rax = 0; + + prepare_switch_frame(tcb, (addr_t) user_regs, (addr_t) ret_from_fork, 0, 0, true); +} + +/** + * Reset the user registers of a thread to start a new program, in + * particular after an exec() + * + * @param tcb Thread to restart + * @param fn_entry Entry point of the program + * @param stack_top Top of the user stack + */ + +void arch_restart_user_thread(tcb_t *tcb, th_fn_t fn_entry, addr_t stack_top) +{ + cpu_regs_t *user_regs = (cpu_regs_t *) arch_get_kernel_stack_frame(tcb); + + *user_regs = (cpu_regs_t) { + .rip = (u64) fn_entry, + .cs = USER_CS, + .rflags = X86_EFLAGS_IF | X86_EFLAGS_FIXED, + .rsp = stack_top, + .ss = USER_DS, + }; + + tcb->cpu_regs.fs_base = 0; + + if (tcb == current()) { + wrmsr(MSR_FS_BASE, 0); + x86_fpu_reset(); + } +} + +/** + * Get the base address of the arguments of a new process + */ + +addr_t arch_get_args_base(void) +{ + return (addr_t) (USER_STACK_TOP_VADDR - PAGE_SIZE); +} + +/** + * Get the user registers frame, at the top of the kernel stack + * + * @param tcb Thread to get the user registers frame + */ + +addr_t arch_get_kernel_stack_frame(tcb_t *tcb) +{ + return get_kernel_stack_top(tcb->stack_slotID) - sizeof(cpu_regs_t); +} + +void __switch_to(tcb_t *prev, tcb_t *next) +{ + static u64 boot_ksp; + + if (prev) + prev->cpu_regs.fs_base = rdmsr(MSR_FS_BASE); + + wrmsr(MSR_FS_BASE, next->cpu_regs.fs_base); + + __x86_switch_stack(prev ? &prev->cpu_regs.ksp : &boot_ksp, next->cpu_regs.ksp); +} diff --git a/so3/so3/arch/x86/traps.c b/so3/so3/arch/x86/traps.c new file mode 100644 index 0000000000..e80a13804b --- /dev/null +++ b/so3/so3/arch/x86/traps.c @@ -0,0 +1,206 @@ +/* + * Copyright (C) 2026 Daniel Rossier + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#include +#include +#include +#include +#include + +#include + +#include +#include + +#include + +void irq_handle(cpu_regs_t *regs); + +/* Red zone of the System V ABI, left untouched below the user stack pointer */ + +#define X86_RED_ZONE 128 + +static const char *exception_names[32] = { + "divide error", "debug", "NMI", "breakpoint", "overflow", "bound range", "invalid opcode", + "device not available", "double fault", "coprocessor overrun", "invalid TSS", "segment not present", + "stack fault", "general protection", "page fault", "reserved", "x87 FP error", "alignment check", + "machine check", "SIMD FP error", "virtualization", "control protection", +}; + +void show_registers(cpu_regs_t *regs) +{ + lprintk(" rip: %016lx cs: %lx rflags: %016lx\n", regs->rip, regs->cs, regs->rflags); + lprintk(" rsp: %016lx ss: %lx error: %lx\n", regs->rsp, regs->ss, regs->error_code); + lprintk(" rax: %016lx rbx: %016lx rcx: %016lx\n", regs->rax, regs->rbx, regs->rcx); + lprintk(" rdx: %016lx rsi: %016lx rdi: %016lx\n", regs->rdx, regs->rsi, regs->rdi); + lprintk(" rbp: %016lx r8: %016lx r9: %016lx\n", regs->rbp, regs->r8, regs->r9); + lprintk(" r10: %016lx r11: %016lx r12: %016lx\n", regs->r10, regs->r11, regs->r12); + lprintk(" r13: %016lx r14: %016lx r15: %016lx\n", regs->r13, regs->r14, regs->r15); + lprintk(" cr2: %016lx cr3: %016lx\n", read_cr2(), read_cr3()); +} + +/* + * A fault in user mode terminates the offending process only, so that the + * shell gets the control back. + */ + +static void user_fault(cpu_regs_t *regs) +{ + pcb_t *pcb = current()->pcb; + + printk("[SO3] process \"%s\" (pid %d) got a %s at rip=0x%lx (cr2=0x%lx, error=0x%lx) - terminating it.\n", + pcb ? pcb->name : "?", pcb ? pcb->pid : -1, exception_names[regs->vector & 31], regs->rip, read_cr2(), + regs->error_code); + + local_irq_enable(); + sys_do_exit_group(128 + SIGSEGV); +} + +/** + * Entry point of all IDT vectors: CPU exceptions and 8259 interrupts. + * + * @param regs Pointer to the stack frame + */ + +void trap_handle(cpu_regs_t *regs) +{ + if ((regs->vector >= X86_IRQ_BASE) && (regs->vector < X86_IRQ_BASE + 16)) { + irq_handle(regs); + return; + } + + if (regs->cs & 3) + user_fault(regs); + + lprintk("### Kernel exception %ld (%s) ###\n", regs->vector, + regs->vector < 32 && exception_names[regs->vector] ? exception_names[regs->vector] : "?"); + show_registers(regs); + + kernel_panic(); +} + +/* + * The syscall number is read back by syscall_handle() through + * __get_syscall_args_ext(). It is kept in the TCB, since the thread may be + * preempted as soon as IRQs are on. + */ + +void __get_syscall_args_ext(long *syscall_no) +{ + *syscall_no = current()->cpu_regs.rax; +} + +/** + * Syscall dispatcher, with the x86_64 ABI: number in rax, arguments in rdi, + * rsi, rdx, r10, r8 and r9, result in rax. + * + * @param regs Frame built by x86_syscall_entry + * @return 1 for rt_sigreturn, whose frame must be dropped, 0 otherwise + */ + +long syscall_entry_handle(cpu_regs_t *regs) +{ + syscall_args_t sys_args; + long nr = regs->rax; + long ret; + + sys_args.args[0] = regs->rdi; + sys_args.args[1] = regs->rsi; + sys_args.args[2] = regs->rdx; + sys_args.args[3] = regs->r10; + sys_args.args[4] = regs->r8; + sys_args.args[5] = regs->r9; + + /* x86_64 passes clone(flags, stack, ptid, ctid, tls), SO3 expects ARM's tls before ctid. */ + + if (nr == SYSCALL_clone) { + sys_args.args[3] = regs->r8; + sys_args.args[4] = regs->r10; + } + + current()->cpu_regs.rax = nr; + + local_irq_enable(); + ret = syscall_handle(&sys_args); + local_irq_disable(); + +#ifdef CONFIG_IPC_SIGNAL + if (nr == SYSCALL_rt_sigreturn) + return 1; +#endif + + regs->rax = ret; + + return 0; +} + +#ifdef CONFIG_IPC_SIGNAL + +/* + * Frame which makes the return to user space enter the signal handler: + * handler(signum) on the user stack, returning to sa_restorer, which + * issues rt_sigreturn and gets the interrupted frame back. + */ + +void x86_setup_sig_frame(cpu_regs_t *frame, cpu_regs_t *interrupted, __sigaction_t *sigaction) +{ + u64 sp; + + sp = ((interrupted->rsp - X86_RED_ZONE) & ~15UL) - 8; + *(u64 *) sp = (u64) sigaction->sa->sa_restorer; + + *frame = (cpu_regs_t) { + .rdi = sigaction->signum, + .rip = (u64) sigaction->sa->sa_handler, + .cs = USER_CS, + .rflags = X86_EFLAGS_IF | X86_EFLAGS_FIXED, + .rsp = sp, + .ss = USER_DS, + }; +} + +#endif /* CONFIG_IPC_SIGNAL */ + +/* + * arch_prctl(ARCH_SET_FS) is how musl sets up the thread pointer on x86_64. + */ + +#define ARCH_SET_GS 0x1001 +#define ARCH_SET_FS 0x1002 +#define ARCH_GET_FS 0x1003 +#define ARCH_GET_GS 0x1004 + +SYSCALL_DEFINE2(arch_prctl, int, code, unsigned long, addr) +{ + switch (code) { + case ARCH_SET_FS: + if (!user_space_vaddr(addr)) + return -EPERM; + + current()->cpu_regs.fs_base = addr; + wrmsr(MSR_FS_BASE, addr); + return 0; + + case ARCH_GET_FS: + *(unsigned long *) addr = rdmsr(MSR_FS_BASE); + return 0; + + default: + return -EINVAL; + } +} diff --git a/so3/so3/configs/pc64_defconfig b/so3/so3/configs/pc64_defconfig new file mode 100644 index 0000000000..f188be0b21 --- /dev/null +++ b/so3/so3/configs/pc64_defconfig @@ -0,0 +1,78 @@ +# +# Automatically generated make config: don't edit +# SO3 Polymorphic OS Configuration +# +# CONFIG_ARCH_ARM32 is not set +# CONFIG_ARCH_ARM64 is not set +CONFIG_ARCH_X86_64=y +# CONFIG_SO3VIRT is not set +CONFIG_ARCH="x86" +CONFIG_CROSS_COMPILE="x86_64-linux-gnu-" +CONFIG_KERNEL_VADDR=0xffffffff80000000 + +# +# Platform +# +CONFIG_PC64=y +# CONFIG_THREAD_ENV is not set +CONFIG_PROC_ENV=y + +# +# Kernel & CPU features +# +# CONFIG_SMP is not set +CONFIG_NR_CPUS=1 +CONFIG_HZ=100 +CONFIG_SCHED_FLIP_SCHEDFREQ=30 + +# +# SO3 Scheduling configuration +# +CONFIG_SCHED_RR=y +# CONFIG_SCHED_PRIO is not set +CONFIG_SCHED_FREQ_PREEMPTION=y + +# +# Drivers +# +CONFIG_UART=y +CONFIG_IO_MAPPING_BASE=0xffff900000000000 +# CONFIG_I2C is not set +# CONFIG_NET is not set +# CONFIG_FB is not set +# CONFIG_INPUT is not set +# CONFIG_NS16550 is not set +CONFIG_UART_PIO=y +CONFIG_UART_LL_PORT=0x3f8 +# CONFIG_MMC is not set +CONFIG_RAMDEV=y +CONFIG_I8254=y +CONFIG_I8259=y +# CONFIG_PL111_CLCD is not set +# CONFIG_QEMU_RAMFB is not set +# CONFIG_PL050_KMI is not set +# CONFIG_SMC911X is not set + +# +# SO3 Applications +# +CONFIG_APP_SAMPLE=y + +# +# Filesystems +# +CONFIG_FS_FAT=y +# CONFIG_ROOTFS_NONE is not set +# CONFIG_ROOTFS_MMC is not set +CONFIG_ROOTFS_RAMDEV=y + +# +# IPC +# +CONFIG_IPC_SIGNAL=y +CONFIG_IPC_PIPE=y +CONFIG_HEAP_SIZE=8 +# CONFIG_RTOS is not set +# CONFIG_AVZ is not set +# CONFIG_SOO is not set +CONFIG_MMU=y diff --git a/so3/so3/devices/fdt.c b/so3/so3/devices/fdt.c index beca433d69..5ce7a97ac4 100644 --- a/so3/so3/devices/fdt.c +++ b/so3/so3/devices/fdt.c @@ -68,11 +68,11 @@ int get_mem_info(const void *fdt, mem_info_t *info) const struct fdt_property *prop; int prop_len; -#ifdef CONFIG_ARCH_ARM64 +#ifndef CONFIG_ARCH_ARM32 volatile unsigned char *ptr; unsigned long val; int i; -#endif /* CONFIG_ARCH_ARM64 */ +#endif /* !CONFIG_ARCH_ARM32 */ offset = fdt_path_offset(fdt, "/memory"); diff --git a/so3/so3/devices/irq/Kconfig b/so3/so3/devices/irq/Kconfig index a9b08aa0df..cf61f1e111 100644 --- a/so3/so3/devices/irq/Kconfig +++ b/so3/so3/devices/irq/Kconfig @@ -14,3 +14,7 @@ config GIC_V2 config GIC_V3 bool "GICv3 (native — AVZ EL2 hypervisor path)" depends on GIC + +config I8259 + bool "Intel 8259A PIC pair (x86 PC)" + depends on ARCH_X86_64 diff --git a/so3/so3/devices/irq/Makefile b/so3/so3/devices/irq/Makefile index 62a0d35c84..40d13d4727 100644 --- a/so3/so3/devices/irq/Makefile +++ b/so3/so3/devices/irq/Makefile @@ -6,3 +6,5 @@ obj-$(CONFIG_AVZ) += vgic.o + +obj-$(CONFIG_I8259) += i8259.o diff --git a/so3/so3/devices/irq/i8259.c b/so3/so3/devices/irq/i8259.c new file mode 100644 index 0000000000..c6c7717ff6 --- /dev/null +++ b/so3/so3/devices/irq/i8259.c @@ -0,0 +1,160 @@ +/* + * Copyright (C) 2026 Daniel Rossier + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ +/* + * Legacy 8259A PIC pair, cascaded on IRQ 2: IRQ n is delivered on vector + * X86_IRQ_BASE + n. Interrupts follow the 2-cell binding . + */ + +#include +#include + +#include +#include +#include + +#include +#include + +#define PIC1_CMD 0x20 +#define PIC1_DATA 0x21 +#define PIC2_CMD 0xa0 +#define PIC2_DATA 0xa1 + +#define PIC_EOI 0x20 +#define PIC_READ_ISR 0x0b + +#define ICW1_INIT 0x11 +#define ICW4_8086 0x01 + +#define PIC_CASCADE_IRQ 2 + +static u16 pic_mask_cache = 0xffff; + +static void pic_write_mask(void) +{ + outb(PIC1_DATA, pic_mask_cache & 0xff); + outb(PIC2_DATA, pic_mask_cache >> 8); +} + +static void pic_mask(unsigned int irq) +{ + pic_mask_cache |= (1 << irq); + pic_write_mask(); +} + +static void pic_unmask(unsigned int irq) +{ + pic_mask_cache &= ~(1 << irq); + + /* The slave PIC needs the cascade line of the master */ + + if (irq >= 8) + pic_mask_cache &= ~(1 << PIC_CASCADE_IRQ); + + pic_write_mask(); +} + +static u16 pic_read_isr(void) +{ + outb(PIC1_CMD, PIC_READ_ISR); + outb(PIC2_CMD, PIC_READ_ISR); + + return (inb(PIC2_CMD) << 8) | inb(PIC1_CMD); +} + +static void pic_eoi(unsigned int irq) +{ + if (irq >= 8) + outb(PIC2_CMD, PIC_EOI); + + outb(PIC1_CMD, PIC_EOI); +} + +static void pic_handle(void *data) +{ + cpu_regs_t *regs = (cpu_regs_t *) data; + unsigned int irq = regs->vector - X86_IRQ_BASE; + + /* + * IRQ 7 and 15 may be spurious: the line dropped before the ack. The + * in-service bit tells. A spurious IRQ 15 still needs the master's EOI. + */ + + if ((irq == 7 || irq == 15) && !(pic_read_isr() & (1 << irq))) { + if (irq == 15) + outb(PIC1_CMD, PIC_EOI); + return; + } + + irq_to_desc(irq)->irq_ops->handle_high(irq); + + pic_eoi(irq); +} + +void fdt_interrupt_node(int fdt_offset, irq_def_t *irq_def) +{ + const struct fdt_property *prop; + const fdt32_t *p; + int prop_len; + + prop = fdt_get_property(__fdt_addr, fdt_offset, "interrupts", &prop_len); + BUG_ON(!prop); + + p = (const fdt32_t *) prop->data; + + BUG_ON(prop_len != 2 * sizeof(uint32_t)); + + irq_def->irq_class = 0; + irq_def->irqnr = fdt32_to_cpu(p[0]); + irq_def->irq_type = fdt32_to_cpu(p[1]); +} + +static int i8259_init(dev_t *dev, int fdt_offset) +{ + /* Remap both PICs above the CPU exceptions */ + + outb(PIC1_CMD, ICW1_INIT); + io_delay(); + outb(PIC2_CMD, ICW1_INIT); + io_delay(); + outb(PIC1_DATA, X86_IRQ_BASE); + io_delay(); + outb(PIC2_DATA, X86_IRQ_BASE + 8); + io_delay(); + outb(PIC1_DATA, 1 << PIC_CASCADE_IRQ); + io_delay(); + outb(PIC2_DATA, PIC_CASCADE_IRQ); + io_delay(); + outb(PIC1_DATA, ICW4_8086); + io_delay(); + outb(PIC2_DATA, ICW4_8086); + io_delay(); + + pic_mask_cache = 0xffff; + pic_write_mask(); + + irq_ops.enable = pic_unmask; + irq_ops.disable = pic_mask; + irq_ops.mask = pic_mask; + irq_ops.unmask = pic_unmask; + irq_ops.handle_low = pic_handle; + + return 0; +} + +REGISTER_DRIVER_CORE("intel,8259", i8259_init); diff --git a/so3/so3/devices/serial/Kconfig b/so3/so3/devices/serial/Kconfig index fc68063596..a38acd5d0b 100644 --- a/so3/so3/devices/serial/Kconfig +++ b/so3/so3/devices/serial/Kconfig @@ -17,8 +17,18 @@ config IMX_UART bool "Freescale i.MX UART (fsl,imx6q-uart)" depends on VERDIN_IMX8MP +config UART_PIO + bool "16550 UART in the x86 I/O port space" + depends on ARCH_X86_64 + config UART_LL_PADDR hex "Low-level UART base physical address" + depends on !ARCH_X86_64 + +config UART_LL_PORT + hex "Low-level UART I/O port" + depends on ARCH_X86_64 + default 0x3f8 config SOO_SERIAL bool "SOO Virtualized serial device (rely on vuart frontend)" diff --git a/so3/so3/devices/serial/Makefile b/so3/so3/devices/serial/Makefile index 50d805cf54..ac71831918 100644 --- a/so3/so3/devices/serial/Makefile +++ b/so3/so3/devices/serial/Makefile @@ -7,3 +7,4 @@ obj-$(CONFIG_IMX_UART) += imx_uart.o obj-$(CONFIG_SOO_SERIAL) += soo_serial.o +obj-$(CONFIG_UART_PIO) += uart_pio.o diff --git a/so3/so3/devices/serial/uart_pio.c b/so3/so3/devices/serial/uart_pio.c new file mode 100644 index 0000000000..9345ef2372 --- /dev/null +++ b/so3/so3/devices/serial/uart_pio.c @@ -0,0 +1,199 @@ +/* + * Copyright (C) 2026 Daniel Rossier + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ +/* + * 16550 UART in the x86 I/O port space (COM1 at 0x3f8 on a PC). The device + * tree gives the port base in "reg". Reception is interrupt-driven, as for + * the PL011. + */ + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include + +#define UART_RBR 0 /* Receive buffer (DLAB = 0) */ +#define UART_THR 0 /* Transmit holding (DLAB = 0) */ +#define UART_DLL 0 /* Divisor low (DLAB = 1) */ +#define UART_IER 1 /* Interrupt enable (DLAB = 0) */ +#define UART_DLH 1 /* Divisor high (DLAB = 1) */ +#define UART_FCR 2 /* FIFO control */ +#define UART_LCR 3 /* Line control */ +#define UART_MCR 4 /* Modem control */ +#define UART_LSR 5 /* Line status */ + +#define UART_IER_RDI 0x01 +#define UART_LCR_DLAB 0x80 +#define UART_LCR_8N1 0x03 +#define UART_MCR_DTR_RTS_OUT2 0x0b +#define UART_FCR_ENABLE_CLEAR 0x07 +#define UART_LSR_DR 0x01 +#define UART_LSR_THRE 0x20 + +/* 115200 bauds from the 1.8432 MHz clock */ + +#define UART_DIVISOR 1 + +#define SERIAL_BUFFER_SIZE 80 + +extern mutex_t read_lock; + +static u16 uart_port = CONFIG_UART_LL_PORT; +static irq_def_t uart_irq; + +static volatile char serial_buffer[SERIAL_BUFFER_SIZE]; +static volatile uint32_t prod = 0, cons = 0; + +static int uart_put_byte(char c) +{ + while (!(inb(uart_port + UART_LSR) & UART_LSR_THRE)) + ; + + outb(uart_port + UART_THR, c); + + return 1; +} + +static char uart_get_byte(bool polling) +{ + char tmp; + + if (polling) { + while (!(inb(uart_port + UART_LSR) & UART_LSR_DR)) + ; + + return inb(uart_port + UART_RBR); + } + + while (prod == cons) { + if (serial_intr) { + serial_intr = false; + return 3; /* ETX */ + } + + schedule(); + smp_mb(); + wfi(); + } + + tmp = serial_buffer[cons]; + cons = (cons + 1) % SERIAL_BUFFER_SIZE; + + return tmp; +} + +/* Ctrl-C is turned into SIGINT for the foreground process, as on the PL011 */ + +static void uart_rx_char(char c) +{ + if (c == 3) { + uart_put_byte('^'); + uart_put_byte('C'); + uart_put_byte('\n'); + +#ifdef CONFIG_IPC_SIGNAL + if (mutex_is_locked(&read_lock)) { + serial_intr = true; + } else { + pcb_t *target = fg_pcb ? fg_pcb : current()->pcb; + + if (target != NULL) + sys_do_kill(target->pid, SIGINT); + } +#endif + return; + } + + serial_buffer[prod] = c; + prod = (prod + 1) % SERIAL_BUFFER_SIZE; +} + +static irq_return_t uart_int(int irq, void *dummy) +{ + while (inb(uart_port + UART_LSR) & UART_LSR_DR) + uart_rx_char(inb(uart_port + UART_RBR)); + + return IRQ_COMPLETED; +} + +static void uart_enable_irq(void) +{ + irq_ops.enable(uart_irq.irqnr); +} + +static void uart_disable_irq(void) +{ + irq_ops.disable(uart_irq.irqnr); +} + +static int uart_pio_init(dev_t *dev, int fdt_offset) +{ + const struct fdt_property *prop; + int prop_len; + + prop = fdt_get_property(__fdt_addr, fdt_offset, "reg", &prop_len); + BUG_ON(!prop); + BUG_ON(prop_len != 2 * sizeof(u64)); + + uart_port = fdt64_to_cpu(((const fdt64_t *) prop->data)[0]); + + serial_ops.put_byte = uart_put_byte; + serial_ops.get_byte = uart_get_byte; + serial_ops.enable_irq = uart_enable_irq; + serial_ops.disable_irq = uart_disable_irq; + + outb(uart_port + UART_IER, 0); + + outb(uart_port + UART_LCR, UART_LCR_DLAB); + outb(uart_port + UART_DLL, UART_DIVISOR & 0xff); + outb(uart_port + UART_DLH, UART_DIVISOR >> 8); + outb(uart_port + UART_LCR, UART_LCR_8N1); + + outb(uart_port + UART_FCR, UART_FCR_ENABLE_CLEAR); + + /* OUT2 gates the UART interrupt line on a PC */ + + outb(uart_port + UART_MCR, UART_MCR_DTR_RTS_OUT2); + + fdt_interrupt_node(fdt_offset, &uart_irq); + irq_bind(uart_irq.irqnr, uart_int, NULL, NULL); + + outb(uart_port + UART_IER, UART_IER_RDI); + + return 0; +} + +void __ll_put_byte(char c) +{ + uart_put_byte(c); +} + +void printch(char c) +{ + __ll_put_byte(c); +} + +REGISTER_DRIVER_POSTCORE("x86,uart-pio", uart_pio_init); diff --git a/so3/so3/devices/timer/Kconfig b/so3/so3/devices/timer/Kconfig index 2a6d71d250..abc42d0f97 100644 --- a/so3/so3/devices/timer/Kconfig +++ b/so3/so3/devices/timer/Kconfig @@ -10,3 +10,7 @@ config ARM_TIMER config SOO_TIMER bool "SOO Virtualized timer device" depends on SOO && !AVZ + +config I8254 + bool "x86 PC timers: 8254 PIT tick and TSC clocksource" + depends on ARCH_X86_64 diff --git a/so3/so3/devices/timer/Makefile b/so3/so3/devices/timer/Makefile index d3e2858f1e..393adc0149 100644 --- a/so3/so3/devices/timer/Makefile +++ b/so3/so3/devices/timer/Makefile @@ -5,3 +5,4 @@ obj-$(CONFIG_ARM_TIMER) += arm_timer.o obj-$(CONFIG_SOO_TIMER) += soo_timer.o +obj-$(CONFIG_I8254) += i8254.o diff --git a/so3/so3/devices/timer/i8254.c b/so3/so3/devices/timer/i8254.c new file mode 100644 index 0000000000..d0a35b52e5 --- /dev/null +++ b/so3/so3/devices/timer/i8254.c @@ -0,0 +1,138 @@ +/* + * Copyright (C) 2026 Daniel Rossier + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ +/* + * PC timers: the 8254 PIT channel 0 gives the periodic tick on IRQ 0, and + * the TSC is the clocksource, calibrated against the PIT channel 2. + */ + +#include +#include +#include + +#include +#include +#include +#include + +#include +#include + +#define PIT_FREQ 1193182 + +#define PIT_CH0 0x40 +#define PIT_CH2 0x42 +#define PIT_CMD 0x43 +#define PIT_GATE 0x61 + +#define PIT_GATE_CH2 0x01 +#define PIT_SPEAKER 0x02 +#define PIT_OUT_CH2 0x20 + +/* Calibration window: 1/CALIBRATE_DIV second */ + +#define CALIBRATE_DIV 20 + +static irq_def_t pit_irq; + +/* The TSC is scaled down so that its rate fits the 32-bit clocksource rate */ + +static unsigned int tsc_shift; + +static irq_return_t pit_isr(int irq, void *dev) +{ + jiffies++; + raise_softirq(TIMER_SOFTIRQ); + + return IRQ_COMPLETED; +} + +static void pit_start(void) +{ + u16 divisor = PIT_FREQ / CONFIG_HZ; + + /* Channel 0, lobyte/hibyte, mode 2 (rate generator) */ + + outb(PIT_CMD, 0x34); + outb(PIT_CH0, divisor & 0xff); + outb(PIT_CH0, divisor >> 8); +} + +static int pit_init(dev_t *dev, int fdt_offset) +{ + periodic_timer.dev = dev; + + fdt_interrupt_node(fdt_offset, &pit_irq); + + periodic_timer.start = pit_start; + periodic_timer.period = NSECS / CONFIG_HZ; + + irq_bind(pit_irq.irqnr, pit_isr, NULL, dev); + + return 0; +} + +static u64 tsc_read(void) +{ + return rdtsc() >> tsc_shift; +} + +/* Count the TSC cycles while the PIT channel 2 counts down a known delay */ + +static u64 tsc_calibrate(void) +{ + u16 latch = PIT_FREQ / CALIBRATE_DIV; + u64 t0, t1; + + outb(PIT_GATE, (inb(PIT_GATE) & ~PIT_SPEAKER) | PIT_GATE_CH2); + + /* Channel 2, lobyte/hibyte, mode 0 (interrupt on terminal count) */ + + outb(PIT_CMD, 0xb0); + outb(PIT_CH2, latch & 0xff); + outb(PIT_CH2, latch >> 8); + + t0 = rdtsc(); + while (!(inb(PIT_GATE) & PIT_OUT_CH2)) + ; + t1 = rdtsc(); + + return (t1 - t0) * CALIBRATE_DIV; +} + +static int tsc_init(dev_t *dev, int fdt_offset) +{ + u64 tsc_hz = tsc_calibrate(); + + tsc_shift = 0; + while ((tsc_hz >> tsc_shift) > 0x7fffffffULL) + tsc_shift++; + + clocksource_timer.cycle_last = 0; + clocksource_timer.read = tsc_read; + clocksource_timer.rate = tsc_hz >> tsc_shift; + clocksource_timer.mask = CLOCKSOURCE_MASK((64 - tsc_shift)); + + clocks_calc_mult_shift(&clocksource_timer.mult, &clocksource_timer.shift, clocksource_timer.rate, NSECS, 3600); + + printk("TSC clocksource: %lu kHz\n", (unsigned long) (tsc_hz / 1000)); + + return 0; +} + +REGISTER_DRIVER_CORE("x86,tsc", tsc_init); +REGISTER_DRIVER_POSTCORE("intel,8254", pit_init); diff --git a/so3/so3/dts/Makefile b/so3/so3/dts/Makefile index 48ab169e94..e57d4345e3 100644 --- a/so3/so3/dts/Makefile +++ b/so3/so3/dts/Makefile @@ -4,6 +4,7 @@ dtb-$(CONFIG_RPI4_64) += rpi4_64.dtb rpi4_64_avz.dtb rpi4_64_capsule.dtb dtb-$(CONFIG_RPI5_64) += rpi5_64_avz.dtb dtb-$(CONFIG_VIRT64) += virt64.dtb virt64_avz.dtb virt64_capsule.dtb virt64_lvperf.dtb dtb-$(CONFIG_VIRT32) += virt32.dtb virt32_lvperf.dtb +dtb-$(CONFIG_PC64) += pc64.dtb dtb-$(CONFIG_VERDIN_IMX8MP) += verdin-imx8mp.dtb verdin-imx8mp_avz.dtb verdin-imx8mp_standalone.dtb ifeq ($(CONFIG_SOO),y) diff --git a/so3/so3/dts/pc64.dts b/so3/so3/dts/pc64.dts new file mode 100644 index 0000000000..fa32d00a4b --- /dev/null +++ b/so3/so3/dts/pc64.dts @@ -0,0 +1,86 @@ +/* + * Copyright (C) 2026 Daniel Rossier + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +/dts-v1/; + +/* + * QEMU x86_64 PC. The memory size and the root filesystem location are + * filled in at boot from the multiboot2 information. + */ + +/ { + model = "SO3 x86_64 PC"; + compatible = "x86,pc64"; + + #address-cells = <2>; + #size-cells = <2>; + + cpus { + device_type = "cpu"; + compatible = "x86,pc64"; + }; + + memory { + device_type = "memory"; + reg = <0x0 0x0 0x0 0x10000000>; + }; + + chosen { + }; + + mem { + compatible = "mem"; + status = "ok"; + }; + + pic: interrupt-controller@20 { + compatible = "intel,8259"; + interrupt-controller; + #interrupt-cells = <2>; + reg = <0x0 0x20 0x0 0x2 0x0 0xa0 0x0 0x2>; + status = "ok"; + }; + + /* COM1, in the I/O port space */ + + serial@3f8 { + compatible = "x86,uart-pio"; + reg = <0x0 0x3f8 0x0 0x8>; + interrupt-parent = <&pic>; + interrupts = <4 0>; + status = "ok"; + }; + + /* Periodic tick from the 8254 PIT channel 0 */ + + periodic-timer@40 { + compatible = "intel,8254"; + reg = <0x0 0x40 0x0 0x4>; + interrupt-parent = <&pic>; + interrupts = <0 0>; + status = "ok"; + }; + + /* Free-running TSC as clocksource */ + + clocksource-timer@0 { + compatible = "x86,tsc"; + reg = <0 0 0 0>; + status = "ok"; + }; +}; diff --git a/so3/so3/include/process.h b/so3/so3/include/process.h index 36428fb6c8..84bb5dbce5 100644 --- a/so3/so3/include/process.h +++ b/so3/so3/include/process.h @@ -172,6 +172,10 @@ SYSCALL_DECLARE(execve, const char *filename, char **argv, char **envp); SYSCALL_DECLARE(fork, void); SYSCALL_DECLARE(clone, unsigned long flags, unsigned long newsp, int *parent_tid, unsigned long tls, int *child_tid); SYSCALL_DECLARE(exit_group, int exit_status); + +#ifdef CONFIG_ARCH_X86_64 +SYSCALL_DECLARE(arch_prctl, int code, unsigned long addr); +#endif SYSCALL_DECLARE(wait4, int pid, uint32_t *wstatus, uint32_t options, void *rusage); pcb_t *find_proc_by_pid(uint32_t pid); diff --git a/so3/so3/include/spinlock.h b/so3/so3/include/spinlock.h index d4abe01552..e52ac65244 100644 --- a/so3/so3/include/spinlock.h +++ b/so3/so3/include/spinlock.h @@ -26,7 +26,7 @@ typedef struct { volatile uint32_t lock; } spinlock_t; -#elif CONFIG_ARCH_ARM64 +#elif defined(CONFIG_ARCH_ARM64) || defined(CONFIG_ARCH_X86_64) /* * On Aarch64, the field has to be 64-bit aligned apparently. diff --git a/so3/so3/include/stat.h b/so3/so3/include/stat.h index 16ce46dd43..a3fb55efd1 100644 --- a/so3/so3/include/stat.h +++ b/so3/so3/include/stat.h @@ -20,6 +20,7 @@ #ifndef STAT_H #define STAT_H +#include #include /* File type bits of st_mode (subset of the POSIX/Linux values). */ @@ -31,6 +32,33 @@ #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG) /* Stat structure copied from Linux include/uapi/asm-generic/stat.h */ +#ifdef CONFIG_ARCH_X86_64 + +/* Layout of the x86_64 kernel stat structure, as expected by musl */ + +struct stat { + unsigned long st_dev; + unsigned long st_ino; + unsigned long st_nlink; + unsigned int st_mode; + unsigned int st_uid; + unsigned int st_gid; + unsigned int __pad0; + unsigned long st_rdev; + long st_size; + long st_blksize; + long st_blocks; + long st_atime; + unsigned long st_atime_nsec; + long st_mtime; + unsigned long st_mtime_nsec; + long st_ctime; + unsigned long st_ctime_nsec; + long __unused[3]; +}; + +#else + struct stat { unsigned long st_dev; /* Device. */ unsigned long st_ino; /* File serial number. */ @@ -54,6 +82,8 @@ struct stat { unsigned int __unused5; }; +#endif /* !CONFIG_ARCH_X86_64 */ + /* This is for ARM32 compatibility as 64bits version of stat will be called. Adapted from arch/arm64/include/asm/stat.h on Linux */ struct stat64 { diff --git a/so3/so3/include/vfs.h b/so3/so3/include/vfs.h index 4ac2634357..d430d9c894 100644 --- a/so3/so3/include/vfs.h +++ b/so3/so3/include/vfs.h @@ -40,13 +40,25 @@ #define O_DSYNC 010000 #define O_SYNC 04010000 #define O_RSYNC 04010000 +/* These four differ between the ARM and the generic (x86_64) Linux ABI. */ + +#ifdef CONFIG_ARCH_X86_64 +#define O_DIRECTORY 0200000 +#define O_NOFOLLOW 0400000 +#else #define O_DIRECTORY 040000 #define O_NOFOLLOW 0100000 +#endif #define O_CLOEXEC 02000000 #define O_ASYNC 020000 +#ifdef CONFIG_ARCH_X86_64 +#define O_DIRECT 040000 +#define O_LARGEFILE 0100000 +#else #define O_DIRECT 0200000 #define O_LARGEFILE 0400000 +#endif #define O_NOATIME 01000000 #define O_PATH 010000000 #define O_TMPFILE 020040000 @@ -110,6 +122,7 @@ #ifndef __ASSEMBLY__ +#include #include #include #include @@ -201,6 +214,15 @@ SYSCALL_DECLARE(mkdirat, int dirfd, const char *path, mode_t mode); SYSCALL_DECLARE(unlinkat, int dirfd, const char *path, int flags); SYSCALL_DECLARE(renameat, int olddirfd, const char *oldpath, int newdirfd, const char *newpath); SYSCALL_DECLARE(renameat2, int olddirfd, const char *oldpath, int newdirfd, const char *newpath, unsigned int flags); + +#ifdef CONFIG_ARCH_X86_64 +SYSCALL_DECLARE(stat, const char *path, struct stat *st); +SYSCALL_DECLARE(lstat, const char *path, struct stat *st); +SYSCALL_DECLARE(mkdir, const char *path, mode_t mode); +SYSCALL_DECLARE(rmdir, const char *path); +SYSCALL_DECLARE(unlink, const char *path); +SYSCALL_DECLARE(rename, const char *oldpath, const char *newpath); +#endif SYSCALL_DECLARE(utimensat, int dirfd, const char *path, const struct timespec *times, int flags); /* Special tv_nsec values for utimensat() (matching Linux/musl). */ diff --git a/so3/so3/kernel/process.c b/so3/so3/kernel/process.c index 2fcdf54608..0f90f72359 100644 --- a/so3/so3/kernel/process.c +++ b/so3/so3/kernel/process.c @@ -233,9 +233,9 @@ pcb_t *new_process(void) kernel_panic(); } - /* With AArch32, we have one page table used by TTBR0/1 without - * distinction. */ -#ifdef CONFIG_ARCH_ARM32 + /* With AArch32 and x86, we have one page table used by TTBR0/1 + * (CR3) without distinction. */ +#if defined(CONFIG_ARCH_ARM32) || defined(CONFIG_ARCH_X86_64) /* Preserve the mapping of kernel regions according to the arch * configuration. */ pgtable_copy_kernel_area(pcb->pgtable); diff --git a/so3/so3/lib/Makefile b/so3/so3/lib/Makefile index 42ae8963d8..6c7b18b3bf 100644 --- a/so3/so3/lib/Makefile +++ b/so3/so3/lib/Makefile @@ -5,7 +5,9 @@ lib-y += string.o string_helpers.o lprintk.o lib-y += ctype.o lib-y += vsprintf.o printk.o +ifneq ($(CONFIG_ARCH_X86_64),y) lib-y += strtod.o +endif lib-y += list_sort.o lib-y += hashmap.o diff --git a/so3/so3/mm/Kconfig b/so3/so3/mm/Kconfig index da385d4121..7731b5f0a9 100644 --- a/so3/so3/mm/Kconfig +++ b/so3/so3/mm/Kconfig @@ -4,6 +4,7 @@ config KERNEL_VADDR default 0xff000000 if ARM32 default 0x100000000000 if AVZ default 0xffff700000000000 if ARM64 + default 0xffffffff80000000 if ARCH_X86_64 config HEAP_SIZE_MB int "Size of the heap (MB)" diff --git a/so3/so3/mm/memory.c b/so3/so3/mm/memory.c index 4e431eaaca..67fd15eedf 100644 --- a/so3/so3/mm/memory.c +++ b/so3/so3/mm/memory.c @@ -468,8 +468,10 @@ void memory_init(void) create_mapping(new_sys_root_pgtable, CONFIG_KERNEL_VADDR, mem_info.phys_base, get_kernel_size(), false); +#ifdef CONFIG_UART_LL_PADDR /* Mapping UART I/O for debugging purposes */ create_mapping(new_sys_root_pgtable, CONFIG_UART_LL_PADDR, CONFIG_UART_LL_PADDR, PAGE_SIZE, true); +#endif #ifdef CONFIG_AVZ diff --git a/so3/so3/syscall.tbl b/so3/so3/syscall.tbl index 92e44ca808..c559e6232a 100644 --- a/so3/so3/syscall.tbl +++ b/so3/so3/syscall.tbl @@ -58,6 +58,17 @@ getpid getpid MMU execve execve MMU fork fork MMU clone clone MMU +# x86_64 only: musl sets the thread pointer (FS base) with it. +arch_prctl arch_prctl ARCH_X86_64 + +# x86_64 only: legacy path syscalls musl calls instead of the *at ones. +stat stat ARCH_X86_64 +lstat lstat ARCH_X86_64 +mkdir mkdir ARCH_X86_64 +rmdir rmdir ARCH_X86_64 +unlink unlink ARCH_X86_64 +rename rename ARCH_X86_64 + set_tid_address set_tid_address MMU exit exit MMU exit_group exit_group MMU diff --git a/so3/usr/CMakeLists.txt b/so3/usr/CMakeLists.txt index f30cd284f9..16133b3adb 100644 --- a/so3/usr/CMakeLists.txt +++ b/so3/usr/CMakeLists.txt @@ -44,6 +44,11 @@ elseif (${CMAKE_SYSTEM_PROCESSOR} STREQUAL "aarch64") add_link_options(-N -Wl,--warn-common ) +elseif (${CMAKE_SYSTEM_PROCESSOR} STREQUAL "x86_64") + +add_link_options(-N -Wl,--warn-common +) + endif() if(CMAKE_BUILD_TYPE MATCHES "Debug") diff --git a/so3/usr/x86_64-linux-musl.cmake b/so3/usr/x86_64-linux-musl.cmake new file mode 100644 index 0000000000..7533fb00fa --- /dev/null +++ b/so3/usr/x86_64-linux-musl.cmake @@ -0,0 +1,30 @@ +# +# CMake toolchain information for SO3 build +# Inspired from buildroot generated toolchain.cmake +# +# Target musl libc + +set(CMAKE_SYSTEM_NAME SO3_usr) +set(CMAKE_SYSTEM_VERSION 1) +set(CMAKE_SYSTEM_PROCESSOR x86_64) + +set(CMAKE_C_FLAGS_DEBUG "" CACHE STRING "Debug CFLAGS") +set(CMAKE_C_FLAGS_RELEASE " -DNDEBUG" CACHE STRING "Release CFLAGS") + +set(CMAKE_BUILD_TYPE Release CACHE STRING "SO3 user applications build system") + +set(CMAKE_INSTALL_SO_NO_EXE 0) + +set(CMAKE_C_COMPILER "x86_64-linux-musl-gcc") +set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY) +set(CMAKE_CXX_COMPILER "x86_64-linux-musl-g++") +set(CMAKE_ASM_COMPILER "x86_64-linux-musl-gcc") + +set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -Wall -std=c99 -D_GNU_SOURCE -D__X86_64__ -fno-common") +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -D_GNU_SOURCE -D__X86_64__ -fno-common") + +set(CMAKE_ASM_FLAGS "-D__X86_64__ -D__ASSEMBLY__") + +set(CMAKE_LINKER "x86_64-linux-musl-ld") + +set(CMAKE_EXE_LINKER_FLAGS "-Os -static -fno-rtti" CACHE STRING "SO3 usr LDFLAGS for executables")