From 5b837e01122cff58474f585dc6f1f165b72d5a4e Mon Sep 17 00:00:00 2001 From: "neo.webmaster.2@gmail.com" Date: Wed, 3 Dec 2025 15:40:18 +0100 Subject: [PATCH] "Auto-commit via make git" --- CHANGELOG.md | 760 ++++++++--- src/_nfdos/init.c | 1116 +++++++++++++++++ .../src/neurotron/kernel_log_agent.py | 42 + .../src/neurotron/kernel_log_agent.py | 42 + src/tui/dashboard/panes/chat.py | 0 src/tui/dashboard/panes/kernel.py | 0 src/tui/dashboard/panes/memory.py | 0 src/tui/dashboard/panes/status.py | 0 src/tui/dashboard/panes/trm.py | 0 src/tui/dashboard/renderer.py | 0 src/tui/menu_kernel.py | 137 +- 11 files changed, 1903 insertions(+), 194 deletions(-) create mode 100644 src/_nfdos/init.c create mode 100644 src/_nfdos/kernel/neurotron/src/neurotron/kernel_log_agent.py create mode 100644 src/_nfdos/rootfs/opt/kernel/neurotron/src/neurotron/kernel_log_agent.py create mode 100644 src/tui/dashboard/panes/chat.py create mode 100644 src/tui/dashboard/panes/kernel.py create mode 100644 src/tui/dashboard/panes/memory.py create mode 100644 src/tui/dashboard/panes/status.py create mode 100644 src/tui/dashboard/panes/trm.py create mode 100644 src/tui/dashboard/renderer.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 28fbd0e..bd3a8c4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,174 +7,610 @@ cat -A Makefile.am | grep '\^I' cat -A src/Makefile.am | grep '\^I' cat -A configure.ac | grep '\^I' nl -ba Makefile | sed -n '770,790p' -grep -n "^[ ]" Makefile | head +grep -n "^[ ]" Makefile | head -ate que esta a ficar bonito 😍: +grep -E 'X86_PGE|X86_PSE|X86_PSE36|X86_VME|X86_PVI|SMAP|SMEP|RANDOMIZE_BASE|PAGE_TABLE_ISOLATION' src/_nfdos/kernel/linux/.config +grep -E '^CONFIG_CR4' src/_nfdos/kernel/linux/.config || true + + +┌────────────────────────────────────────────────────────────────────────────┐ +│ NEUROTRON STATUS CPU: 2% MEM: 11% TEMP: 1.2 ENERGY: 41.0 │ +│ CogState: STABLE Depth: 1 Valence: -5.00 Mode: ACTIVE │ +├────────────────────────────────────────────────────────────────────────────┤ +│ KERNEL MESSAGES (live): │ +│ [ 0.167890] ACPI: Core revision 20240415 │ +│ [ 0.260302] pci 0000:00:02.0: VESA 1024x768x32 framebuffer activated │ +│ [ 1.012399] EXT4-fs mounted filesystem with ordered data mode. │ +│ ... │ +├────────────────────────────────────────────────────────────────────────────┤ +│ NEUROTRON TRM: │ +│ mem estável — tendência favorável │ +│ sistema frio — margem para explorar │ +│ valência baixa — evitar exploração │ +├────────────────────────────────────────────────────────────────────────────┤ +│ NEUROTRON CHAT: │ +│ [ia@nfdos] Olá mundo! │ +│ [user@nfdos] ... │ +├────────────────────────────────────────────────────────────────────────────┤ +│ user@nfdos: │ +└────────────────────────────────────────────────────────────────────────────┘ + +Quando quiseres damos o próximo passo: Ritmos Internos — osciladores cognitivos leves (senoides, modulação lenta, ciclos internos). +São eles que vão permitir padrões emergentes mais profundos. + +grep ok: ``` -UP: 00:01:14 TICK: 0.50s MODO: PERSISTENT +grep -R "NFDOS_CR4_SAFE_MASK" -n src/_nfdos/kernel/linux/arch/x86/mm +src/_nfdos/kernel/linux/arch/x86/mm/init.c:39:#define NFDOS_CR4_SAFE_MASK \ +src/_nfdos/kernel/linux/arch/x86/mm/init.c:252: mask &= NFDOS_CR4_SAFE_MASK; +``` +sequencia da compil tambem ok: +``` +Compilando Kernel Linux... +make mrproper + CLEAN arch/x86/entry/vdso + CLEAN arch/x86/kernel/cpu + CLEAN arch/x86/kernel + CLEAN arch/x86/realmode/rm + CLEAN arch/x86/tools + CLEAN init + CLEAN usr + CLEAN . + CLEAN scripts/basic + CLEAN scripts/kconfig + CLEAN scripts/mod + CLEAN scripts + CLEAN include/config include/generated arch/x86/include/generated .config .config.old +make allnoconfig + HOSTCC scripts/basic/fixdep + HOSTCC scripts/kconfig/conf.o + HOSTCC scripts/kconfig/confdata.o + HOSTCC scripts/kconfig/expr.o + LEX scripts/kconfig/lexer.lex.c + YACC scripts/kconfig/parser.tab.[ch] + HOSTCC scripts/kconfig/lexer.lex.o + HOSTCC scripts/kconfig/menu.o + HOSTCC scripts/kconfig/parser.tab.o + HOSTCC scripts/kconfig/preprocess.o + HOSTCC scripts/kconfig/symbol.o + HOSTCC scripts/kconfig/util.o + HOSTLD scripts/kconfig/conf +# +# configuration written to .config +# +→ Patching kernel headers for C23 compatibility... +make prepare + SYSHDR arch/x86/include/generated/uapi/asm/unistd_32.h + SYSHDR arch/x86/include/generated/uapi/asm/unistd_64.h + SYSHDR arch/x86/include/generated/uapi/asm/unistd_x32.h + SYSTBL arch/x86/include/generated/asm/syscalls_32.h + SYSHDR arch/x86/include/generated/asm/unistd_32_ia32.h + SYSHDR arch/x86/include/generated/asm/unistd_64_x32.h + SYSTBL arch/x86/include/generated/asm/syscalls_64.h + HOSTCC arch/x86/tools/relocs_32.o + HOSTCC arch/x86/tools/relocs_64.o + HOSTCC arch/x86/tools/relocs_common.o + HOSTLD arch/x86/tools/relocs + HOSTCC scripts/kallsyms + HOSTCC scripts/sorttable + WRAP arch/x86/include/generated/uapi/asm/bpf_perf_event.h + WRAP arch/x86/include/generated/uapi/asm/errno.h + WRAP arch/x86/include/generated/uapi/asm/fcntl.h + WRAP arch/x86/include/generated/uapi/asm/ioctl.h + WRAP arch/x86/include/generated/uapi/asm/ioctls.h + WRAP arch/x86/include/generated/uapi/asm/ipcbuf.h + WRAP arch/x86/include/generated/uapi/asm/param.h + WRAP arch/x86/include/generated/uapi/asm/poll.h + WRAP arch/x86/include/generated/uapi/asm/resource.h + WRAP arch/x86/include/generated/uapi/asm/socket.h + WRAP arch/x86/include/generated/uapi/asm/sockios.h + WRAP arch/x86/include/generated/uapi/asm/termbits.h + WRAP arch/x86/include/generated/uapi/asm/termios.h + WRAP arch/x86/include/generated/uapi/asm/types.h + WRAP arch/x86/include/generated/asm/early_ioremap.h + WRAP arch/x86/include/generated/asm/mcs_spinlock.h + WRAP arch/x86/include/generated/asm/mmzone.h + WRAP arch/x86/include/generated/asm/irq_regs.h + WRAP arch/x86/include/generated/asm/kmap_size.h + WRAP arch/x86/include/generated/asm/local64.h + WRAP arch/x86/include/generated/asm/mmiowb.h + WRAP arch/x86/include/generated/asm/module.lds.h + WRAP arch/x86/include/generated/asm/rwonce.h + GEN arch/x86/include/generated/asm/orc_hash.h + UPD include/config/kernel.release + UPD include/generated/uapi/linux/version.h + UPD include/generated/utsrelease.h + UPD include/generated/compile.h + CC scripts/mod/empty.o + HOSTCC scripts/mod/mk_elfconfig + MKELF scripts/mod/elfconfig.h + HOSTCC scripts/mod/modpost.o + CC scripts/mod/devicetable-offsets.s + UPD scripts/mod/devicetable-offsets.h + HOSTCC scripts/mod/file2alias.o + HOSTCC scripts/mod/sumversion.o + HOSTCC scripts/mod/symsearch.o + HOSTLD scripts/mod/modpost + UPD include/generated/timeconst.h + CC kernel/bounds.s + UPD include/generated/bounds.h + CC arch/x86/kernel/asm-offsets.s + UPD include/generated/asm-offsets.h + CALL scripts/checksyscalls.sh + CHKSHA1 include/linux/atomic/atomic-arch-fallback.h + CHKSHA1 include/linux/atomic/atomic-instrumented.h + CHKSHA1 include/linux/atomic/atomic-long.h + DESCEND objtool + CC /home/neo/Público/nfdos/src/_nfdos/kernel/linux/tools/objtool/libsubcmd/exec-cmd.o + CC /home/neo/Público/nfdos/src/_nfdos/kernel/linux/tools/objtool/libsubcmd/help.o + CC /home/neo/Público/nfdos/src/_nfdos/kernel/linux/tools/objtool/libsubcmd/pager.o + CC /home/neo/Público/nfdos/src/_nfdos/kernel/linux/tools/objtool/libsubcmd/parse-options.o + CC /home/neo/Público/nfdos/src/_nfdos/kernel/linux/tools/objtool/libsubcmd/run-command.o + CC /home/neo/Público/nfdos/src/_nfdos/kernel/linux/tools/objtool/libsubcmd/sigchain.o + CC /home/neo/Público/nfdos/src/_nfdos/kernel/linux/tools/objtool/libsubcmd/subcmd-config.o + LD /home/neo/Público/nfdos/src/_nfdos/kernel/linux/tools/objtool/libsubcmd/libsubcmd-in.o + AR /home/neo/Público/nfdos/src/_nfdos/kernel/linux/tools/objtool/libsubcmd/libsubcmd.a + INSTALL libsubcmd_headers + CC /home/neo/Público/nfdos/src/_nfdos/kernel/linux/tools/objtool/arch/x86/special.o + CC /home/neo/Público/nfdos/src/_nfdos/kernel/linux/tools/objtool/arch/x86/decode.o + CC /home/neo/Público/nfdos/src/_nfdos/kernel/linux/tools/objtool/arch/x86/orc.o + LD /home/neo/Público/nfdos/src/_nfdos/kernel/linux/tools/objtool/arch/x86/objtool-in.o + CC /home/neo/Público/nfdos/src/_nfdos/kernel/linux/tools/objtool/weak.o + CC /home/neo/Público/nfdos/src/_nfdos/kernel/linux/tools/objtool/check.o + CC /home/neo/Público/nfdos/src/_nfdos/kernel/linux/tools/objtool/special.o + CC /home/neo/Público/nfdos/src/_nfdos/kernel/linux/tools/objtool/builtin-check.o + CC /home/neo/Público/nfdos/src/_nfdos/kernel/linux/tools/objtool/elf.o + CC /home/neo/Público/nfdos/src/_nfdos/kernel/linux/tools/objtool/objtool.o + CC /home/neo/Público/nfdos/src/_nfdos/kernel/linux/tools/objtool/orc_gen.o + CC /home/neo/Público/nfdos/src/_nfdos/kernel/linux/tools/objtool/orc_dump.o + CC /home/neo/Público/nfdos/src/_nfdos/kernel/linux/tools/objtool/libstring.o + CC /home/neo/Público/nfdos/src/_nfdos/kernel/linux/tools/objtool/libctype.o + CC /home/neo/Público/nfdos/src/_nfdos/kernel/linux/tools/objtool/str_error_r.o + CC /home/neo/Público/nfdos/src/_nfdos/kernel/linux/tools/objtool/librbtree.o + LD /home/neo/Público/nfdos/src/_nfdos/kernel/linux/tools/objtool/objtool-in.o + LINK /home/neo/Público/nfdos/src/_nfdos/kernel/linux/tools/objtool/objtool +make scripts +✔ Patched: include/linux/stddef.h +✔ Patched: include/linux/types.h +→ Boot directory forced to GNU11: arch/x86/boot +→ Boot directory forced to GNU11: arch/x86/boot/compressed +→ Boot directory forced to GNU11: drivers/firmware/efi/libstub +→ Global C23 overrides neutralized in main Makefile +✔ Kernel headers & boot toolchain fully sanitized. +git checkout -- arch/x86/mm/init.c +cp /home/neo/Público/nfdos/src/_nfdos/init.c /home/neo/Público/nfdos/src/_nfdos/kernel/linux/arch/x86/mm/init.c +→ Aplicando overrides de configuração... +scripts/config --enable CONFIG_PRINTK +[...] +scripts/config --enable CONFIG_BINFMT_SCRIPT +make olddefconfig + HOSTCC scripts/basic/fixdep + HOSTCC scripts/kconfig/conf.o + HOSTCC scripts/kconfig/confdata.o + HOSTCC scripts/kconfig/expr.o + HOSTCC scripts/kconfig/lexer.lex.o + HOSTCC scripts/kconfig/menu.o + HOSTCC scripts/kconfig/parser.tab.o + HOSTCC scripts/kconfig/preprocess.o + HOSTCC scripts/kconfig/symbol.o + HOSTCC scripts/kconfig/util.o + HOSTLD scripts/kconfig/conf +# +# configuration written to .config +# +✔ Overrides aplicados com sucesso. +make olddefconfig + HOSTCC scripts/basic/fixdep + HOSTCC scripts/kconfig/conf.o + HOSTCC scripts/kconfig/confdata.o + HOSTCC scripts/kconfig/expr.o + HOSTCC scripts/kconfig/lexer.lex.o + HOSTCC scripts/kconfig/menu.o + HOSTCC scripts/kconfig/parser.tab.o + HOSTCC scripts/kconfig/preprocess.o + HOSTCC scripts/kconfig/symbol.o + HOSTCC scripts/kconfig/util.o + HOSTLD scripts/kconfig/conf +# +# No change to .config +# +make -j 4 + SYNC include/config/auto.conf.cmd +[...] +Kernel: arch/x86/boot/bzImage is ready (#1) +✔ Kernel compilado com sucesso! +``` +qemu standard ok: +``` + # 🧠 Monta a linha base do QEMU + kernel_params = ( + "console=ttyS0 earlyprintk=serial,ttyS0,115200 " + "keep_bootcon loglevel=8" + ) + + qemu_cmd = ( + f"qemu-system-x86_64 " + f"-machine q35,accel=kvm " # q35,accel=kvm + f"-cpu qemu64 " # qemu64 + f"-kernel {bz_image} " + f"-initrd {nfdos_dir}/initramfs.cpio.gz " + f"-append '{kernel_params}' " + f"-drive file={data_disk},if=virtio,format=raw " + f"-m 1024 " + # f"-vga std " + # f"-display default " + # f"-serial mon:stdio " + f"-nographic " + f"-no-reboot" + ) +``` +e temos o neurotron a falar conosco: +``` +Linux version 6.12.0-nfdos (neo@notebook) (x86_64-nfdos-linux-musl-gcc (crosstool-NG 1.28.0.1_403899e) 15.2.0, GNU ld (crosstool-NG 1.28.0.1_403899e) 2.45) #1 Wed Dec 3 15:21:12 CET 2025 +Command line: console=ttyS0 earlyprintk=serial,ttyS0,115200 keep_bootcon loglevel=8 +BIOS-provided physical RAM map: +BIOS-e820: [mem 0x0000000000000000-0x000000000009fbff] usable +BIOS-e820: [mem 0x000000000009fc00-0x000000000009ffff] reserved +BIOS-e820: [mem 0x00000000000f0000-0x00000000000fffff] reserved +BIOS-e820: [mem 0x0000000000100000-0x000000003ffdbfff] usable +BIOS-e820: [mem 0x000000003ffdc000-0x000000003fffffff] reserved +BIOS-e820: [mem 0x00000000b0000000-0x00000000bfffffff] reserved +BIOS-e820: [mem 0x00000000fed1c000-0x00000000fed1ffff] reserved +BIOS-e820: [mem 0x00000000feffc000-0x00000000feffffff] reserved +BIOS-e820: [mem 0x00000000fffc0000-0x00000000ffffffff] reserved +printk: legacy bootconsole [earlyser0] enabled +printk: debug: skip boot console de-registration. +NX (Execute Disable) protection: active +APIC: Static calls initialized +SMBIOS 3.0.0 present. +DMI: QEMU Standard PC (Q35 + ICH9, 2009), BIOS 1.16.3-debian-1.16.3-2 04/01/2014 +DMI: Memory slots populated: 1/1 +tsc: Fast TSC calibration failed +e820: update [mem 0x00000000-0x00000fff] usable ==> reserved +e820: remove [mem 0x000a0000-0x000fffff] usable +last_pfn = 0x3ffdc max_arch_pfn = 0x400000000 +MTRR map: 4 entries (3 fixed + 1 variable; max 19), built from 8 variable MTRRs +x86/PAT: Configuration [0-7]: WB WC UC- UC WB WP UC- WT +found SMP MP-table at [mem 0x000f5470-0x000f547f] +RAMDISK: [mem 0x3e831000-0x3ffcffff] +Intel MultiProcessor Specification v1.4 +MPTABLE: OEM ID: BOCHSCPU +MPTABLE: Product ID: 0.1 +MPTABLE: APIC at: 0xFEE00000 +Zone ranges: + DMA [mem 0x0000000000001000-0x0000000000ffffff] + DMA32 [mem 0x0000000001000000-0x000000003ffdbfff] + Normal empty +Movable zone start for each node +Early memory node ranges + node 0: [mem 0x0000000000001000-0x000000000009efff] + node 0: [mem 0x0000000000100000-0x000000003ffdbfff] +Initmem setup node 0 [mem 0x0000000000001000-0x000000003ffdbfff] +On node 0, zone DMA: 1 pages in unavailable ranges +On node 0, zone DMA: 97 pages in unavailable ranges +On node 0, zone DMA32: 36 pages in unavailable ranges +Intel MultiProcessor Specification v1.4 +MPTABLE: OEM ID: BOCHSCPU +MPTABLE: Product ID: 0.1 +MPTABLE: APIC at: 0xFEE00000 +Processor #0 (Bootup-CPU) +IOAPIC[0]: apic_id 0, version 17, address 0xfec00000, GSI 0-23 +Processors: 1 +CPU topo: Max. logical packages: 1 +CPU topo: Max. logical dies: 1 +CPU topo: Max. dies per package: 1 +CPU topo: Max. threads per core: 1 +CPU topo: Num. cores per package: 1 +CPU topo: Num. threads per package: 1 +CPU topo: Allowing 1 present CPUs plus 0 hotplug CPUs +[mem 0x40000000-0xafffffff] available for PCI devices +clocksource: refined-jiffies: mask: 0xffffffff max_cycles: 0xffffffff, max_idle_ns: 7645519600211568 ns +pcpu-alloc: s0 r0 d32768 u32768 alloc=1*32768 +pcpu-alloc: [0] 0 +Kernel command line: console=ttyS0 earlyprintk=serial,ttyS0,115200 keep_bootcon loglevel=8 +Dentry cache hash table entries: 131072 (order: 8, 1048576 bytes, linear) +Inode-cache hash table entries: 65536 (order: 7, 524288 bytes, linear) +Built 1 zonelists, mobility grouping on. Total pages: 262010 +mem auto-init: stack:all(zero), heap alloc:off, heap free:off +SLUB: HWalign=64, Order=0-3, MinObjects=0, CPUs=1, Nodes=1 +NR_IRQS: 4352, nr_irqs: 48, preallocated irqs: 16 +Console: colour VGA+ 80x25 +printk: legacy console [ttyS0] enabled +printk: legacy console [ttyS0] enabled +APIC: Switch to symmetric I/O mode setup +APIC: Switch to symmetric I/O mode setup +..TIMER: vector=0x30 apic1=0 pin1=2 apic2=-1 pin2=-1 +..TIMER: vector=0x30 apic1=0 pin1=2 apic2=-1 pin2=-1 +tsc: Unable to calibrate against PIT +tsc: Unable to calibrate against PIT +tsc: No reference (HPET/PMTIMER) available +tsc: No reference (HPET/PMTIMER) available +tsc: Marking TSC unstable due to could not calculate TSC khz +tsc: Marking TSC unstable due to could not calculate TSC khz +Calibrating delay loop... 6239.23 BogoMIPS (lpj=12478464) +Calibrating delay loop... 6239.23 BogoMIPS (lpj=12478464) +Last level iTLB entries: 4KB 0, 2MB 0, 4MB 0 +Last level iTLB entries: 4KB 0, 2MB 0, 4MB 0 +Last level dTLB entries: 4KB 0, 2MB 0, 4MB 0, 1GB 0 +Last level dTLB entries: 4KB 0, 2MB 0, 4MB 0, 1GB 0 +CPU: Intel QEMU Virtual CPU version 2.5+ (family: 0xf, model: 0x6b, stepping: 0x1) +CPU: Intel QEMU Virtual CPU version 2.5+ (family: 0xf, model: 0x6b, stepping: 0x1) +Speculative Store Bypass: Vulnerable +Speculative Store Bypass: Vulnerable +x86/fpu: x87 FPU will use FXSAVE +x86/fpu: x87 FPU will use FXSAVE +pid_max: default: 32768 minimum: 301 +pid_max: default: 32768 minimum: 301 +Mount-cache hash table entries: 2048 (order: 2, 16384 bytes, linear) +Mount-cache hash table entries: 2048 (order: 2, 16384 bytes, linear) +Mountpoint-cache hash table entries: 2048 (order: 2, 16384 bytes, linear) +Mountpoint-cache hash table entries: 2048 (order: 2, 16384 bytes, linear) +Performance Events: unsupported Netburst CPU model 107 no PMU driver, software events only. +Performance Events: unsupported Netburst CPU model 107 no PMU driver, software events only. +signal: max sigframe size: 1040 +signal: max sigframe size: 1040 +Memory: 990500K/1048040K available (6144K kernel code, 877K rwdata, 872K rodata, 624K init, 1324K bss, 55160K reserved, 0K cma-reserved) +Memory: 990500K/1048040K available (6144K kernel code, 877K rwdata, 872K rodata, 624K init, 1324K bss, 55160K reserved, 0K cma-reserved) +devtmpfs: initialized +devtmpfs: initialized +clocksource: jiffies: mask: 0xffffffff max_cycles: 0xffffffff, max_idle_ns: 7645041785100000 ns +clocksource: jiffies: mask: 0xffffffff max_cycles: 0xffffffff, max_idle_ns: 7645041785100000 ns +futex hash table entries: 256 (order: 0, 6144 bytes, linear) +futex hash table entries: 256 (order: 0, 6144 bytes, linear) +PCI: Using configuration type 1 for base access +PCI: Using configuration type 1 for base access +PCI: Probing PCI hardware +PCI: Probing PCI hardware +PCI: root bus 00: using default resources +PCI: root bus 00: using default resources +PCI: Probing PCI hardware (bus 00) +PCI: Probing PCI hardware (bus 00) +PCI host bridge to bus 0000:00 +PCI host bridge to bus 0000:00 +pci_bus 0000:00: root bus resource [io 0x0000-0xffff] +pci_bus 0000:00: root bus resource [io 0x0000-0xffff] +pci_bus 0000:00: root bus resource [mem 0x00000000-0xffffffffff] +pci_bus 0000:00: root bus resource [mem 0x00000000-0xffffffffff] +pci_bus 0000:00: No busn resource found for root bus, will use [bus 00-ff] +pci_bus 0000:00: No busn resource found for root bus, will use [bus 00-ff] +pci 0000:00:00.0: [8086:29c0] type 00 class 0x060000 conventional PCI endpoint +pci 0000:00:00.0: [8086:29c0] type 00 class 0x060000 conventional PCI endpoint +pci 0000:00:01.0: [1234:1111] type 00 class 0x030000 conventional PCI endpoint +pci 0000:00:01.0: [1234:1111] type 00 class 0x030000 conventional PCI endpoint +pci 0000:00:01.0: BAR 0 [mem 0xfd000000-0xfdffffff pref] +pci 0000:00:01.0: BAR 0 [mem 0xfd000000-0xfdffffff pref] +pci 0000:00:01.0: BAR 2 [mem 0xfebd4000-0xfebd4fff] +pci 0000:00:01.0: BAR 2 [mem 0xfebd4000-0xfebd4fff] +pci 0000:00:01.0: ROM [mem 0xfebc0000-0xfebcffff pref] +pci 0000:00:01.0: ROM [mem 0xfebc0000-0xfebcffff pref] +pci 0000:00:01.0: Video device with shadowed ROM at [mem 0x000c0000-0x000dffff] +pci 0000:00:01.0: Video device with shadowed ROM at [mem 0x000c0000-0x000dffff] +pci 0000:00:02.0: [8086:10d3] type 00 class 0x020000 PCIe Root Complex Integrated Endpoint +pci 0000:00:02.0: [8086:10d3] type 00 class 0x020000 PCIe Root Complex Integrated Endpoint +pci 0000:00:02.0: BAR 0 [mem 0xfeb80000-0xfeb9ffff] +pci 0000:00:02.0: BAR 0 [mem 0xfeb80000-0xfeb9ffff] +pci 0000:00:02.0: BAR 1 [mem 0xfeba0000-0xfebbffff] +pci 0000:00:02.0: BAR 1 [mem 0xfeba0000-0xfebbffff] +pci 0000:00:02.0: BAR 2 [io 0xc0c0-0xc0df] +pci 0000:00:02.0: BAR 2 [io 0xc0c0-0xc0df] +pci 0000:00:02.0: BAR 3 [mem 0xfebd0000-0xfebd3fff] +pci 0000:00:02.0: BAR 3 [mem 0xfebd0000-0xfebd3fff] +pci 0000:00:02.0: ROM [mem 0xfeb00000-0xfeb7ffff pref] +pci 0000:00:02.0: ROM [mem 0xfeb00000-0xfeb7ffff pref] +pci 0000:00:03.0: [1af4:1001] type 00 class 0x010000 conventional PCI endpoint +pci 0000:00:03.0: [1af4:1001] type 00 class 0x010000 conventional PCI endpoint +pci 0000:00:03.0: BAR 0 [io 0xc000-0xc07f] +pci 0000:00:03.0: BAR 0 [io 0xc000-0xc07f] +pci 0000:00:03.0: BAR 1 [mem 0xfebd5000-0xfebd5fff] +pci 0000:00:03.0: BAR 1 [mem 0xfebd5000-0xfebd5fff] +pci 0000:00:03.0: BAR 4 [mem 0xfe000000-0xfe003fff 64bit pref] +pci 0000:00:03.0: BAR 4 [mem 0xfe000000-0xfe003fff 64bit pref] +pci 0000:00:1f.0: [8086:2918] type 00 class 0x060100 conventional PCI endpoint +pci 0000:00:1f.0: [8086:2918] type 00 class 0x060100 conventional PCI endpoint +pci 0000:00:1f.0: quirk: [io 0x0600-0x067f] claimed by ICH6 ACPI/GPIO/TCO +pci 0000:00:1f.0: quirk: [io 0x0600-0x067f] claimed by ICH6 ACPI/GPIO/TCO +pci 0000:00:1f.2: [8086:2922] type 00 class 0x010601 conventional PCI endpoint +pci 0000:00:1f.2: [8086:2922] type 00 class 0x010601 conventional PCI endpoint +pci 0000:00:1f.2: BAR 4 [io 0xc0e0-0xc0ff] +pci 0000:00:1f.2: BAR 4 [io 0xc0e0-0xc0ff] +pci 0000:00:1f.2: BAR 5 [mem 0xfebd6000-0xfebd6fff] +pci 0000:00:1f.2: BAR 5 [mem 0xfebd6000-0xfebd6fff] +pci 0000:00:1f.3: [8086:2930] type 00 class 0x0c0500 conventional PCI endpoint +pci 0000:00:1f.3: [8086:2930] type 00 class 0x0c0500 conventional PCI endpoint +pci 0000:00:1f.3: BAR 4 [io 0x0700-0x073f] +pci 0000:00:1f.3: BAR 4 [io 0x0700-0x073f] +pci_bus 0000:00: busn_res: [bus 00-ff] end is updated to 00 +pci_bus 0000:00: busn_res: [bus 00-ff] end is updated to 00 +pci 0000:00:01.0: PIIX/ICH IRQ router [1234:1111] +pci 0000:00:01.0: PIIX/ICH IRQ router [1234:1111] +PCI: pci_cache_line_size set to 64 bytes +PCI: pci_cache_line_size set to 64 bytes +e820: reserve RAM buffer [mem 0x0009fc00-0x0009ffff] +e820: reserve RAM buffer [mem 0x0009fc00-0x0009ffff] +e820: reserve RAM buffer [mem 0x3ffdc000-0x3fffffff] +e820: reserve RAM buffer [mem 0x3ffdc000-0x3fffffff] +pci 0000:00:01.0: vgaarb: setting as boot VGA device +pci 0000:00:01.0: vgaarb: setting as boot VGA device +pci 0000:00:01.0: vgaarb: bridge control possible +pci 0000:00:01.0: vgaarb: bridge control possible +pci 0000:00:01.0: vgaarb: VGA device added: decodes=io+mem,owns=io+mem,locks=none +pci 0000:00:01.0: vgaarb: VGA device added: decodes=io+mem,owns=io+mem,locks=none +vgaarb: loaded +vgaarb: loaded +clocksource: Switched to clocksource refined-jiffies +clocksource: Switched to clocksource refined-jiffies +pci_bus 0000:00: resource 4 [io 0x0000-0xffff] +pci_bus 0000:00: resource 4 [io 0x0000-0xffff] +pci_bus 0000:00: resource 5 [mem 0x00000000-0xffffffffff] +pci_bus 0000:00: resource 5 [mem 0x00000000-0xffffffffff] +PCI: CLS 0 bytes, default 64 +PCI: CLS 0 bytes, default 64 +platform rtc_cmos: registered platform RTC device (no PNP device found) +platform rtc_cmos: registered platform RTC device (no PNP device found) +Unpacking initramfs... +Unpacking initramfs... +workingset: timestamp_bits=62 max_order=18 bucket_order=0 +workingset: timestamp_bits=62 max_order=18 bucket_order=0 +virtio-pci 0000:00:03.0: PCI->APIC IRQ transform: INT A -> IRQ 11 +virtio-pci 0000:00:03.0: PCI->APIC IRQ transform: INT A -> IRQ 11 +Serial: 8250/16550 driver, 4 ports, IRQ sharing disabled +Serial: 8250/16550 driver, 4 ports, IRQ sharing disabled +serial8250: ttyS0 at I/O 0x3f8 (irq = 4, base_baud = 115200) is a 16550A +serial8250: ttyS0 at I/O 0x3f8 (irq = 4, base_baud = 115200) is a 16550A +virtio_blk virtio0: 1/0/0 default/read/poll queues +virtio_blk virtio0: 1/0/0 default/read/poll queues +virtio_blk virtio0: [vda] 1048576 512-byte logical blocks (537 MB/512 MiB) +virtio_blk virtio0: [vda] 1048576 512-byte logical blocks (537 MB/512 MiB) +Freeing initrd memory: 24188K +Freeing initrd memory: 24188K +Freeing unused kernel image (initmem) memory: 624K +Freeing unused kernel image (initmem) memory: 624K +Write protecting the kernel read-only data: 8192k +Write protecting the kernel read-only data: 8192k +Freeing unused kernel image (rodata/data gap) memory: 1176K +Freeing unused kernel image (rodata/data gap) memory: 1176K +Run /init as init process +Run /init as init process + with arguments: + with arguments: + /init + /init + with environment: + with environment: + HOME=/ + HOME=/ + TERM=linux + TERM=linux +random: crng init done +UP: 00:00:18 TICK: 0.62s MODO: DIAGNOSTIC ──────────────────────────────────────────────────────────────────────────────── -[06:23:38] [debug] [diag] estado=STABLE cpu=0.0 mem=10.6 load1=0.44 -[06:23:38] [diag] estado=STABLE cpu=0.0 mem=10.6 load1=0.44 -[06:23:38] [debug] telemetry state=stable temp=1.2 cpu=0.0% mem=10.6% load=0.44 jitter=0.904s -[06:23:38] [debug] [trm.thought] mem estável — tendência favorável -[06:23:38] [debug] [trm.thought] sistema frio — margem para explorar -[06:23:38] [debug] [trm.thought] valência baixa — evitar exploração -[06:23:38] [debug] [trm.engine] step ok: mode=active cog=stable energy=43.1 depth=1 valence=-5.00 -[06:23:38] [heart] cpu=0.0% mem=10.6% tick=0.50s -[06:23:39] [debug] telemetry state=stable temp=1.2 cpu=0.0% mem=10.6% load=0.44 jitter=0.748s -[06:23:39] [debug] [trm.thought] mem estável — tendência favorável -[06:23:39] [debug] [trm.thought] sistema frio — margem para explorar -[06:23:39] [debug] [trm.thought] valência baixa — evitar exploração -[06:23:39] [debug] [trm.engine] step ok: mode=active cog=stable energy=42.4 depth=1 valence=-5.00 -[06:23:39] [heart] cpu=0.0% mem=10.6% tick=0.50s -[06:23:39] [debug] telemetry state=stable temp=1.2 cpu=0.0% mem=10.6% load=0.44 jitter=0.784s -[06:23:40] [debug] [trm.thought] mem estável — tendência favorável -[06:23:40] [debug] [trm.thought] sistema frio — margem para explorar -[06:23:40] [debug] [trm.thought] valência baixa — evitar exploração -[06:23:40] [debug] [trm.engine] step ok: mode=active cog=stable energy=41.7 depth=1 valence=-5.00 -[06:23:40] [heart] cpu=0.0% mem=10.6% tick=0.50s -[06:23:40] [debug] Vitals CPU=0.0% MEM=10.6% load1=0.4 -[06:23:40] [debug] telemetry state=stable temp=1.2 cpu=0.0% mem=10.6% load=0.40 jitter=0.820s -[06:23:40] [debug] [trm.thought] mem estável — tendência favorável -[06:23:40] [debug] [trm.thought] sistema frio — margem para explorar -[06:23:40] [debug] [trm.thought] valência baixa — evitar exploração -[06:23:40] [debug] [trm.engine] step ok: mode=active cog=stable energy=41.0 depth=1 valence=-5.00 -[06:23:40] [heart] cpu=0.0% mem=10.6% tick=0.50s -[06:23:41] [debug] telemetry state=stable temp=1.2 cpu=0.0% mem=10.6% load=0.40 jitter=0.736s -[06:23:41] [debug] [trm.thought] mem estável — tendência favorável -[06:23:41] [debug] [trm.thought] sistema frio — margem para explorar -[06:23:41] [debug] [trm.thought] valência baixa — evitar exploração -[06:23:41] [debug] [trm.engine] step ok: mode=active cog=stable energy=40.3 depth=1 valence=-5.00 -[06:23:41] [heart] cpu=0.0% mem=10.6% tick=0.50s -[06:23:42] [debug] [diag] estado=STABLE cpu=0.0 mem=10.6 load1=0.4 -[06:23:42] [diag] estado=STABLE cpu=0.0 mem=10.6 load1=0.4 -[06:23:42] [debug] telemetry state=stable temp=1.2 cpu=0.0% mem=10.6% load=0.40 +[14:23:22] [info] tick ajustado 0.88s → 0.75s +[14:23:22] [debug] telemetry state=stable temp=0.7 cpu=0.0% mem=10.4% load=0.00 jitter=1.324s +[14:23:22] [debug] [trm.archaeologist] encontrou 3 eventos perigosos recentes → valence -0.30 +[14:23:22] [debug] [trm.thought] mem estável — tendência favorável +[14:23:22] [debug] [trm.thought] sistema frio — margem para explorar +[14:23:22] [debug] [trm.engine] step ok: mode=active cog=stable energy=92.1 depth=1 valence=-2.70 +[14:23:22] [heart] cpu=0.0% mem=10.4% tick=0.75s +[14:23:23] [disk] Filesystem existente detectado +[14:23:23] [debug] Vitals CPU=0.0% MEM=10.5% load1=0.0 +[14:23:23] [info] [echo] CPU=0.0% MEM=10.5% ``` -podemos adicionar "o pensador" ao roadmap: +agora a parte do "como fiz?": fui no gitea buscar o ".config" que funcionava: ``` -### ✔ TRM — Tiny Recursive Model — Base simbólica definida + # Essenciais do sistema base + essentials = [ + "CONFIG_PRINTK", + "CONFIG_TTY", + "CONFIG_SERIAL_8250", + "CONFIG_SERIAL_8250_CONSOLE", + "CONFIG_SERIAL_EARLYCON", + "CONFIG_DEVTMPFS", + "CONFIG_DEVTMPFS_MOUNT", + "CONFIG_BLK_DEV_INITRD", + "CONFIG_TMPFS", + "CONFIG_PROC_FS", + "CONFIG_SYSFS", + # EXT4 base + alias para ext2 + "CONFIG_PARTITION_ADVANCED", + "CONFIG_EFI_PARTITION", + "CONFIG_MSDOS_PARTITION", + "CONFIG_EXT4_FS", + "CONFIG_EXT4_USE_FOR_EXT2", + "CONFIG_CMDLINE_PARTITION", + "CONFIG_MCORE2", + #"CONFIG_EXT4_FS_POSIX_ACL", + #"CONFIG_EXT4_FS_SECURITY", + # Console VGA (comentado para modo serial-only) + # "CONFIG_VT", + # "CONFIG_VT_CONSOLE", + # "CONFIG_VGA_CONSOLE", + # "CONFIG_FB", + # "CONFIG_FB_VESA", + # "CONFIG_FRAMEBUFFER_CONSOLE", + # "CONFIG_FONT_8x16", + # "CONFIG_FONT_8x8", + # # "CONFIG_X86_MCE", + # # "CONFIG_X86_MCE_INTEL", + # "CONFIG_X86_LOCAL_APIC", + # "CONFIG_X86_IO_APIC", + # "CONFIG_X86_MSR", + # "CONFIG_X86_FEATURE_NAMES", + # "CONFIG_X86_TSC", + # "CONFIG_X86_CMOV", + # "CONFIG_RD_GZIP", + # "CONFIG_RD_BZIP2", + # "CONFIG_RD_LZMA", + # "CONFIG_RD_XZ", + # "CONFIG_RD_LZO", + # "CONFIG_RD_LZ4", + ] -O TRM é o primeiro módulo de **raciocínio interno** do Neurotron. -Ele não é uma rede neural, não aprende por SGD e não precisa de GPU. + # VirtIO (para bloco, rede, PCI) + virtio = [ + "CONFIG_PCI", + "CONFIG_VIRTIO", + "CONFIG_VIRTIO_MENU", + "CONFIG_VIRTIO_PCI", + "CONFIG_VIRTIO_PCI_LEGACY", + "CONFIG_VIRTIO_BLK", + "CONFIG_VIRTIO_NET", + "CONFIG_VIRTIO_CONSOLE", + "CONFIG_VIRTIO_INPUT", + "CONFIG_VIRTIO_MMIO", + "CONFIG_VIRTIO_MMIO_CMDLINE_DEVICES", + "CONFIG_BLK_MQ_VIRTIO", + "CONFIG_BLOCK", + "CONFIG_BLK_DEV", + "CONFIG_BLOCK_LEGACY_AUTOLOAD", + "CONFIG_EXPORTFS_BLOCK_OPS", + "CONFIG_MSDOS_PARTITION", # assegura parsing de tabela de partições + ] -O TRM é: + # Debug e early printk + debug = [ + "CONFIG_DEBUG_KERNEL", + "CONFIG_EARLY_PRINTK", + "CONFIG_SERIAL_8250_PNP", + "CONFIG_DEBUG_INFO_NONE", # evita symbols extras + ] -> um **micro-modelo simbólico**, iterativo, recorrente, energeticamente limitado, -> capaz de gerar *pensamentos internos*, previsões, julgamentos e estados mentais. + # Garante compatibilidade máxima de CPU (para manter o kernel leve, limpo e evitar CR4 panics) + disable_extras = [ + # modo serial-only + "CONFIG_VT", + "CONFIG_VT_CONSOLE", + "CONFIG_VGA_CONSOLE", + "CONFIG_FRAMEBUFFER_CONSOLE", + "CONFIG_DUMMY_CONSOLE", + "CONFIG_FB", + "CONFIG_DRM", + "CONFIG_DRM_I915", + "CONFIG_LOGO", + "CONFIG_X86_PAE", + "CONFIG_X86_5LEVEL", + "CONFIG_RANDOMIZE_BASE", + "CONFIG_RETPOLINE", + "CONFIG_SMAP", + "CONFIG_SMEP", + "CONFIG_PAGE_TABLE_ISOLATION", + # modo VGA + # Deixar estes quatro comentados. Eles são core para x86_64 + QEMU. + # "CONFIG_X86_PAE", + # "CONFIG_X86_PGE", + # "CONFIG_X86_PAT", + # "CONFIG_X86_PSE", + # + # "CONFIG_X86_PSE36", + # "CONFIG_X86_VME", + # "CONFIG_X86_PVI", + # "CONFIG_X86_PCID", + # "CONFIG_PAGE_TABLE_ISOLATION", + # "CONFIG_PARAVIRT", + # "CONFIG_PARAVIRT_CLOCK", + # "CONFIG_ARCH_RANDOM", + ] +``` -Ele usa: - -* [x] telemetria v5 -* [x] memória de eventos (Hippocampus) -* [x] sinais fisiológicos -* [-] micro-regras -* [x] micro-agentes internos - -para criar uma **mente mínima**, mas viva. - -#### 🟦 **TRM v1 — (implementação imediata)** - -> Objetivo: gerar *vida interna mínima* e um estado cognitivo coerente. - -##### 🔹 1. Micro-agentes internos - -Três agentes simples, independentes, mas acoplados: - -##### **🛡️ Guardião** - -Responsável por proteção e homeostase. - -* [-] monitora delta, aceleração, temperatura e FS -* [-] ajustes preventivos -* [x] ativa markers (`enter_stress_zone`, `fs_warning`) -* [-] reduz carga quando há risco - -##### **🧭 Explorador** - -Responsável por “pensamento” TRM. - -* [-] gera micro previsões de tendência -* [-] avalia estabilidade -* [-] modifica tick cognitivo -* [ ] inicia refinamento simbólico - -##### **📜 Arqueólogo** - -Responsável por memória e histórico. - -* [x] lê eventos telemétricos recentes -* [-] correlaciona com estados antigos -* [x] ativa markers (`loop_suspect`, `recovering`) -* [x] influencia valência interna - -#### 🔹 2. Energia / Custo Cognitivo - -Cada passo TRM consome energia. - -* [x] cada passo TRM consome energia -* [-] mais telemetria = mais custo -* [ ] previsões mais profundas = custo quadrático -* [-] estado “quente” aumenta custo -* [-] estado “frio” diminui custo - -* [x] Quando a energia baixa demais → TRM reduz profundidade, entra em modo “mínimo”. - -#### 🔹 3. Valência Interna - -Uma métrica de “bem-estar”. - -* [x] estabilidade aumenta valência -* [-] picos rápidos diminuem -* [x] recovery aumenta -* [x] FS warning diminui -* [-] jitter alto diminui - -Valência influencia: - -* [x] intensidade TRM -* [-] prioridades -* [-] ritmo cognitivo - -#### 🔹 4. Ritmos Internos (Osciladores) - -Quatro ritmos independentes: - -* [-] `think_rate` -* [-] `memory_sync_rate` -* [-] `telemetry_rate` -* [-] `selfcheck_rate` - -Alguns podem oscilar lentamente ao longo do tempo (sinusóide leve), criando: - -* [-] ciclos -* [-] fases -* [-] padrões internos - -Estes ritmos ajudam a criar **estabilidade dinâmica**, essencial para emergência. - -#### 🔹 5. Espaço de Estados & Atratores - -##### Estados principais: - -* [x] `stable` -* [x] `warm` -* [x] `hot` -* [x] `critical` -* [x] `recovery` - -##### Atratores cognitivos (dinâmica de V1): - -* [-] estável -* [-] quasi-estável -* [-] recuperativo -* [-] oscilatório -* [ ] pré-caótico (quando delta+aceleração divergem) - -O estado atual do TRM influencia: - -* [x] profundidade TRM -* [x] valência -* [-] custo cognitivo -* [-] ajustes no tick -* [x] markers enviados ao Hippocampus -``` \ No newline at end of file +E no GRUB: +GRUB_GFXMODE=1024x768x32 +GRUB_GFXPAYLOAD_LINUX=keep \ No newline at end of file diff --git a/src/_nfdos/init.c b/src/_nfdos/init.c new file mode 100644 index 0000000..4c840b6 --- /dev/null +++ b/src/_nfdos/init.c @@ -0,0 +1,1116 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include /* for MAX_DMA_PFN */ +#include +#include +#include +#include +#include +#include +#include +#include /* garante X86_CR4_* */ + +/* + * NFDOS: CR4 SAFE MASK + * + * Só permitimos bits conservadores no CR4 durante o boot, + * para evitar #GP em CPUs/QEMU mais “sensíveis”. + */ +#define NFDOS_CR4_SAFE_MASK \ + ( X86_CR4_DE | /* Debug Extensions */ \ + X86_CR4_PSE | /* Page Size Extension */ \ + X86_CR4_PAE | /* Physical Addr Extension */ \ + X86_CR4_MCE | /* Machine Check Exception */ \ + X86_CR4_PGE | /* Global Pages */ \ + X86_CR4_PCE | /* Perf Counter Enable */ \ + X86_CR4_OSFXSR | /* SSE */ \ + X86_CR4_OSXMMEXCPT ) /* SSE exceptions */ + +/* + * We need to define the tracepoints somewhere, and tlb.c + * is only compiled when SMP=y. + */ +#include + +#include "mm_internal.h" + +/* + * Tables translating between page_cache_type_t and pte encoding. + * + * The default values are defined statically as minimal supported mode; + * WC and WT fall back to UC-. pat_init() updates these values to support + * more cache modes, WC and WT, when it is safe to do so. See pat_init() + * for the details. Note, __early_ioremap() used during early boot-time + * takes pgprot_t (pte encoding) and does not use these tables. + * + * Index into __cachemode2pte_tbl[] is the cachemode. + * + * Index into __pte2cachemode_tbl[] are the caching attribute bits of the pte + * (_PAGE_PWT, _PAGE_PCD, _PAGE_PAT) at index bit positions 0, 1, 2. + */ +static uint16_t __cachemode2pte_tbl[_PAGE_CACHE_MODE_NUM] = { + [_PAGE_CACHE_MODE_WB ] = 0 | 0 , + [_PAGE_CACHE_MODE_WC ] = 0 | _PAGE_PCD, + [_PAGE_CACHE_MODE_UC_MINUS] = 0 | _PAGE_PCD, + [_PAGE_CACHE_MODE_UC ] = _PAGE_PWT | _PAGE_PCD, + [_PAGE_CACHE_MODE_WT ] = 0 | _PAGE_PCD, + [_PAGE_CACHE_MODE_WP ] = 0 | _PAGE_PCD, +}; + +unsigned long cachemode2protval(enum page_cache_mode pcm) +{ + if (likely(pcm == 0)) + return 0; + return __cachemode2pte_tbl[pcm]; +} +EXPORT_SYMBOL(cachemode2protval); + +static uint8_t __pte2cachemode_tbl[8] = { + [__pte2cm_idx( 0 | 0 | 0 )] = _PAGE_CACHE_MODE_WB, + [__pte2cm_idx(_PAGE_PWT | 0 | 0 )] = _PAGE_CACHE_MODE_UC_MINUS, + [__pte2cm_idx( 0 | _PAGE_PCD | 0 )] = _PAGE_CACHE_MODE_UC_MINUS, + [__pte2cm_idx(_PAGE_PWT | _PAGE_PCD | 0 )] = _PAGE_CACHE_MODE_UC, + [__pte2cm_idx( 0 | 0 | _PAGE_PAT)] = _PAGE_CACHE_MODE_WB, + [__pte2cm_idx(_PAGE_PWT | 0 | _PAGE_PAT)] = _PAGE_CACHE_MODE_UC_MINUS, + [__pte2cm_idx(0 | _PAGE_PCD | _PAGE_PAT)] = _PAGE_CACHE_MODE_UC_MINUS, + [__pte2cm_idx(_PAGE_PWT | _PAGE_PCD | _PAGE_PAT)] = _PAGE_CACHE_MODE_UC, +}; + +/* + * Check that the write-protect PAT entry is set for write-protect. + * To do this without making assumptions how PAT has been set up (Xen has + * another layout than the kernel), translate the _PAGE_CACHE_MODE_WP cache + * mode via the __cachemode2pte_tbl[] into protection bits (those protection + * bits will select a cache mode of WP or better), and then translate the + * protection bits back into the cache mode using __pte2cm_idx() and the + * __pte2cachemode_tbl[] array. This will return the really used cache mode. + */ +bool x86_has_pat_wp(void) +{ + uint16_t prot = __cachemode2pte_tbl[_PAGE_CACHE_MODE_WP]; + + return __pte2cachemode_tbl[__pte2cm_idx(prot)] == _PAGE_CACHE_MODE_WP; +} + +enum page_cache_mode pgprot2cachemode(pgprot_t pgprot) +{ + unsigned long masked; + + masked = pgprot_val(pgprot) & _PAGE_CACHE_MASK; + if (likely(masked == 0)) + return 0; + return __pte2cachemode_tbl[__pte2cm_idx(masked)]; +} + +static unsigned long __initdata pgt_buf_start; +static unsigned long __initdata pgt_buf_end; +static unsigned long __initdata pgt_buf_top; + +static unsigned long min_pfn_mapped; + +static bool __initdata can_use_brk_pgt = true; + +/* + * Pages returned are already directly mapped. + * + * Changing that is likely to break Xen, see commit: + * + * 279b706 x86,xen: introduce x86_init.mapping.pagetable_reserve + * + * for detailed information. + */ +__ref void *alloc_low_pages(unsigned int num) +{ + unsigned long pfn; + int i; + + if (after_bootmem) { + unsigned int order; + + order = get_order((unsigned long)num << PAGE_SHIFT); + return (void *)__get_free_pages(GFP_ATOMIC | __GFP_ZERO, order); + } + + if ((pgt_buf_end + num) > pgt_buf_top || !can_use_brk_pgt) { + unsigned long ret = 0; + + if (min_pfn_mapped < max_pfn_mapped) { + ret = memblock_phys_alloc_range( + PAGE_SIZE * num, PAGE_SIZE, + min_pfn_mapped << PAGE_SHIFT, + max_pfn_mapped << PAGE_SHIFT); + } + if (!ret && can_use_brk_pgt) + ret = __pa(extend_brk(PAGE_SIZE * num, PAGE_SIZE)); + + if (!ret) + panic("alloc_low_pages: can not alloc memory"); + + pfn = ret >> PAGE_SHIFT; + } else { + pfn = pgt_buf_end; + pgt_buf_end += num; + } + + for (i = 0; i < num; i++) { + void *adr; + + adr = __va((pfn + i) << PAGE_SHIFT); + clear_page(adr); + } + + return __va(pfn << PAGE_SHIFT); +} + +/* + * By default need to be able to allocate page tables below PGD firstly for + * the 0-ISA_END_ADDRESS range and secondly for the initial PMD_SIZE mapping. + * With KASLR memory randomization, depending on the machine e820 memory and the + * PUD alignment, twice that many pages may be needed when KASLR memory + * randomization is enabled. + */ + +#ifndef CONFIG_X86_5LEVEL +#define INIT_PGD_PAGE_TABLES 3 +#else +#define INIT_PGD_PAGE_TABLES 4 +#endif + +#ifndef CONFIG_RANDOMIZE_MEMORY +#define INIT_PGD_PAGE_COUNT (2 * INIT_PGD_PAGE_TABLES) +#else +#define INIT_PGD_PAGE_COUNT (4 * INIT_PGD_PAGE_TABLES) +#endif + +#define INIT_PGT_BUF_SIZE (INIT_PGD_PAGE_COUNT * PAGE_SIZE) +RESERVE_BRK(early_pgt_alloc, INIT_PGT_BUF_SIZE); +void __init early_alloc_pgt_buf(void) +{ + unsigned long tables = INIT_PGT_BUF_SIZE; + phys_addr_t base; + + base = __pa(extend_brk(tables, PAGE_SIZE)); + + pgt_buf_start = base >> PAGE_SHIFT; + pgt_buf_end = pgt_buf_start; + pgt_buf_top = pgt_buf_start + (tables >> PAGE_SHIFT); +} + +int after_bootmem; + +early_param_on_off("gbpages", "nogbpages", direct_gbpages, CONFIG_X86_DIRECT_GBPAGES); + +struct map_range { + unsigned long start; + unsigned long end; + unsigned page_size_mask; +}; + +static int page_size_mask; + +static inline void cr4_set_bits_and_update_boot(unsigned long mask) +{ + /* + * NFDOS: filtramos o mask para só conter bits seguros. + * Isto evita que a gente tente ligar SMEP/SMAP/LA57/PKE/etc + * se por algum motivo o caminho de deteção de features se enganar + * ou ficar inconsistente com o CPU emulado. + * + * Para referencia futura segue o "backup" do kernel original: + * + * Save some of cr4 feature set we're using (e.g. Pentium 4MB + * enable and PPro Global page enable), so that any CPU's that boot + * up after us can get the correct flags. Invoked on the boot CPU. + * static inline void cr4_set_bits_and_update_boot(unsigned long mask) + * { + * mmu_cr4_features |= mask; + * if (trampoline_cr4_features) + * *trampoline_cr4_features = mmu_cr4_features; + * cr4_set_bits(mask); + * } + */ + mask &= NFDOS_CR4_SAFE_MASK; + if (!mask) + return; + + mmu_cr4_features |= mask; + + if (trampoline_cr4_features) + *trampoline_cr4_features = mmu_cr4_features; + + cr4_set_bits(mask); +} + +static void __init probe_page_size_mask(void) +{ + /* + * For pagealloc debugging, identity mapping will use small pages. + * This will simplify cpa(), which otherwise needs to support splitting + * large pages into small in interrupt context, etc. + */ + if (boot_cpu_has(X86_FEATURE_PSE) && !debug_pagealloc_enabled()) + page_size_mask |= 1 << PG_LEVEL_2M; + else + direct_gbpages = 0; + + /* Enable PSE if available */ + if (boot_cpu_has(X86_FEATURE_PSE)) + cr4_set_bits_and_update_boot(X86_CR4_PSE); + + /* Enable PGE if available */ + __supported_pte_mask &= ~_PAGE_GLOBAL; + if (boot_cpu_has(X86_FEATURE_PGE)) { + cr4_set_bits_and_update_boot(X86_CR4_PGE); + __supported_pte_mask |= _PAGE_GLOBAL; + } + + /* By the default is everything supported: */ + __default_kernel_pte_mask = __supported_pte_mask; + /* Except when with PTI where the kernel is mostly non-Global: */ + if (cpu_feature_enabled(X86_FEATURE_PTI)) + __default_kernel_pte_mask &= ~_PAGE_GLOBAL; + + /* Enable 1 GB linear kernel mappings if available: */ + if (direct_gbpages && boot_cpu_has(X86_FEATURE_GBPAGES)) { + printk(KERN_INFO "Using GB pages for direct mapping\n"); + page_size_mask |= 1 << PG_LEVEL_1G; + } else { + direct_gbpages = 0; + } +} + +/* + * INVLPG may not properly flush Global entries + * on these CPUs when PCIDs are enabled. + */ +static const struct x86_cpu_id invlpg_miss_ids[] = { + X86_MATCH_VFM(INTEL_ALDERLAKE, 0), + X86_MATCH_VFM(INTEL_ALDERLAKE_L, 0), + X86_MATCH_VFM(INTEL_ATOM_GRACEMONT, 0), + X86_MATCH_VFM(INTEL_RAPTORLAKE, 0), + X86_MATCH_VFM(INTEL_RAPTORLAKE_P, 0), + X86_MATCH_VFM(INTEL_RAPTORLAKE_S, 0), + {} +}; + +static void setup_pcid(void) +{ + if (!IS_ENABLED(CONFIG_X86_64)) + return; + + if (!boot_cpu_has(X86_FEATURE_PCID)) + return; + + if (x86_match_cpu(invlpg_miss_ids)) { + pr_info("Incomplete global flushes, disabling PCID"); + setup_clear_cpu_cap(X86_FEATURE_PCID); + return; + } + + if (boot_cpu_has(X86_FEATURE_PGE)) { + /* + * This can't be cr4_set_bits_and_update_boot() -- the + * trampoline code can't handle CR4.PCIDE and it wouldn't + * do any good anyway. Despite the name, + * cr4_set_bits_and_update_boot() doesn't actually cause + * the bits in question to remain set all the way through + * the secondary boot asm. + * + * Instead, we brute-force it and set CR4.PCIDE manually in + * start_secondary(). + */ + cr4_set_bits(X86_CR4_PCIDE); + } else { + /* + * flush_tlb_all(), as currently implemented, won't work if + * PCID is on but PGE is not. Since that combination + * doesn't exist on real hardware, there's no reason to try + * to fully support it, but it's polite to avoid corrupting + * data if we're on an improperly configured VM. + */ + setup_clear_cpu_cap(X86_FEATURE_PCID); + } +} + +#ifdef CONFIG_X86_32 +#define NR_RANGE_MR 3 +#else /* CONFIG_X86_64 */ +#define NR_RANGE_MR 5 +#endif + +static int __meminit save_mr(struct map_range *mr, int nr_range, + unsigned long start_pfn, unsigned long end_pfn, + unsigned long page_size_mask) +{ + if (start_pfn < end_pfn) { + if (nr_range >= NR_RANGE_MR) + panic("run out of range for init_memory_mapping\n"); + mr[nr_range].start = start_pfn<> PAGE_SHIFT) > max_low_pfn) + continue; +#endif + + if (memblock_is_region_memory(start, end - start)) + mr[i].page_size_mask |= 1<page_size_mask & (1<page_size_mask & (1<page_size_mask & (1< limit_pfn) + end_pfn = limit_pfn; + if (start_pfn < end_pfn) { + nr_range = save_mr(mr, nr_range, start_pfn, end_pfn, 0); + pfn = end_pfn; + } + + /* big page (2M) range */ + start_pfn = round_up(pfn, PFN_DOWN(PMD_SIZE)); +#ifdef CONFIG_X86_32 + end_pfn = round_down(limit_pfn, PFN_DOWN(PMD_SIZE)); +#else /* CONFIG_X86_64 */ + end_pfn = round_up(pfn, PFN_DOWN(PUD_SIZE)); + if (end_pfn > round_down(limit_pfn, PFN_DOWN(PMD_SIZE))) + end_pfn = round_down(limit_pfn, PFN_DOWN(PMD_SIZE)); +#endif + + if (start_pfn < end_pfn) { + nr_range = save_mr(mr, nr_range, start_pfn, end_pfn, + page_size_mask & (1< 1 && i < nr_range - 1; i++) { + unsigned long old_start; + if (mr[i].end != mr[i+1].start || + mr[i].page_size_mask != mr[i+1].page_size_mask) + continue; + /* move it */ + old_start = mr[i].start; + memmove(&mr[i], &mr[i+1], + (nr_range - 1 - i) * sizeof(struct map_range)); + mr[i--].start = old_start; + nr_range--; + } + + for (i = 0; i < nr_range; i++) + pr_debug(" [mem %#010lx-%#010lx] page %s\n", + mr[i].start, mr[i].end - 1, + page_size_string(&mr[i])); + + return nr_range; +} + +struct range pfn_mapped[E820_MAX_ENTRIES]; +int nr_pfn_mapped; + +static void add_pfn_range_mapped(unsigned long start_pfn, unsigned long end_pfn) +{ + nr_pfn_mapped = add_range_with_merge(pfn_mapped, E820_MAX_ENTRIES, + nr_pfn_mapped, start_pfn, end_pfn); + nr_pfn_mapped = clean_sort_range(pfn_mapped, E820_MAX_ENTRIES); + + max_pfn_mapped = max(max_pfn_mapped, end_pfn); + + if (start_pfn < (1UL<<(32-PAGE_SHIFT))) + max_low_pfn_mapped = max(max_low_pfn_mapped, + min(end_pfn, 1UL<<(32-PAGE_SHIFT))); +} + +bool pfn_range_is_mapped(unsigned long start_pfn, unsigned long end_pfn) +{ + int i; + + for (i = 0; i < nr_pfn_mapped; i++) + if ((start_pfn >= pfn_mapped[i].start) && + (end_pfn <= pfn_mapped[i].end)) + return true; + + return false; +} + +/* + * Setup the direct mapping of the physical memory at PAGE_OFFSET. + * This runs before bootmem is initialized and gets pages directly from + * the physical memory. To access them they are temporarily mapped. + */ +unsigned long __ref init_memory_mapping(unsigned long start, + unsigned long end, pgprot_t prot) +{ + struct map_range mr[NR_RANGE_MR]; + unsigned long ret = 0; + int nr_range, i; + + pr_debug("init_memory_mapping: [mem %#010lx-%#010lx]\n", + start, end - 1); + + memset(mr, 0, sizeof(mr)); + nr_range = split_mem_range(mr, 0, start, end); + + for (i = 0; i < nr_range; i++) + ret = kernel_physical_mapping_init(mr[i].start, mr[i].end, + mr[i].page_size_mask, + prot); + + add_pfn_range_mapped(start >> PAGE_SHIFT, ret >> PAGE_SHIFT); + + return ret >> PAGE_SHIFT; +} + +/* + * We need to iterate through the E820 memory map and create direct mappings + * for only E820_TYPE_RAM and E820_KERN_RESERVED regions. We cannot simply + * create direct mappings for all pfns from [0 to max_low_pfn) and + * [4GB to max_pfn) because of possible memory holes in high addresses + * that cannot be marked as UC by fixed/variable range MTRRs. + * Depending on the alignment of E820 ranges, this may possibly result + * in using smaller size (i.e. 4K instead of 2M or 1G) page tables. + * + * init_mem_mapping() calls init_range_memory_mapping() with big range. + * That range would have hole in the middle or ends, and only ram parts + * will be mapped in init_range_memory_mapping(). + */ +static unsigned long __init init_range_memory_mapping( + unsigned long r_start, + unsigned long r_end) +{ + unsigned long start_pfn, end_pfn; + unsigned long mapped_ram_size = 0; + int i; + + for_each_mem_pfn_range(i, MAX_NUMNODES, &start_pfn, &end_pfn, NULL) { + u64 start = clamp_val(PFN_PHYS(start_pfn), r_start, r_end); + u64 end = clamp_val(PFN_PHYS(end_pfn), r_start, r_end); + if (start >= end) + continue; + + /* + * if it is overlapping with brk pgt, we need to + * alloc pgt buf from memblock instead. + */ + can_use_brk_pgt = max(start, (u64)pgt_buf_end<= + min(end, (u64)pgt_buf_top<> PAGE_SHIFT; + last_start = real_end; + + /* + * We start from the top (end of memory) and go to the bottom. + * The memblock_find_in_range() gets us a block of RAM from the + * end of RAM in [min_pfn_mapped, max_pfn_mapped) used as new pages + * for page table. + */ + while (last_start > map_start) { + unsigned long start; + + if (last_start > step_size) { + start = round_down(last_start - 1, step_size); + if (start < map_start) + start = map_start; + } else + start = map_start; + mapped_ram_size += init_range_memory_mapping(start, + last_start); + last_start = start; + min_pfn_mapped = last_start >> PAGE_SHIFT; + if (mapped_ram_size >= step_size) + step_size = get_new_step_size(step_size); + } + + if (real_end < map_end) + init_range_memory_mapping(real_end, map_end); +} + +/** + * memory_map_bottom_up - Map [map_start, map_end) bottom up + * @map_start: start address of the target memory range + * @map_end: end address of the target memory range + * + * This function will setup direct mapping for memory range + * [map_start, map_end) in bottom-up. Since we have limited the + * bottom-up allocation above the kernel, the page tables will + * be allocated just above the kernel and we map the memory + * in [map_start, map_end) in bottom-up. + */ +static void __init memory_map_bottom_up(unsigned long map_start, + unsigned long map_end) +{ + unsigned long next, start; + unsigned long mapped_ram_size = 0; + /* step_size need to be small so pgt_buf from BRK could cover it */ + unsigned long step_size = PMD_SIZE; + + start = map_start; + min_pfn_mapped = start >> PAGE_SHIFT; + + /* + * We start from the bottom (@map_start) and go to the top (@map_end). + * The memblock_find_in_range() gets us a block of RAM from the + * end of RAM in [min_pfn_mapped, max_pfn_mapped) used as new pages + * for page table. + */ + while (start < map_end) { + if (step_size && map_end - start > step_size) { + next = round_up(start + 1, step_size); + if (next > map_end) + next = map_end; + } else { + next = map_end; + } + + mapped_ram_size += init_range_memory_mapping(start, next); + start = next; + + if (mapped_ram_size >= step_size) + step_size = get_new_step_size(step_size); + } +} + +/* + * The real mode trampoline, which is required for bootstrapping CPUs + * occupies only a small area under the low 1MB. See reserve_real_mode() + * for details. + * + * If KASLR is disabled the first PGD entry of the direct mapping is copied + * to map the real mode trampoline. + * + * If KASLR is enabled, copy only the PUD which covers the low 1MB + * area. This limits the randomization granularity to 1GB for both 4-level + * and 5-level paging. + */ +static void __init init_trampoline(void) +{ +#ifdef CONFIG_X86_64 + /* + * The code below will alias kernel page-tables in the user-range of the + * address space, including the Global bit. So global TLB entries will + * be created when using the trampoline page-table. + */ + if (!kaslr_memory_enabled()) + trampoline_pgd_entry = init_top_pgt[pgd_index(__PAGE_OFFSET)]; + else + init_trampoline_kaslr(); +#endif +} + +void __init init_mem_mapping(void) +{ + unsigned long end; + + pti_check_boottime_disable(); + probe_page_size_mask(); + setup_pcid(); + +#ifdef CONFIG_X86_64 + end = max_pfn << PAGE_SHIFT; +#else + end = max_low_pfn << PAGE_SHIFT; +#endif + + /* the ISA range is always mapped regardless of memory holes */ + init_memory_mapping(0, ISA_END_ADDRESS, PAGE_KERNEL); + + /* Init the trampoline, possibly with KASLR memory offset */ + init_trampoline(); + + /* + * If the allocation is in bottom-up direction, we setup direct mapping + * in bottom-up, otherwise we setup direct mapping in top-down. + */ + if (memblock_bottom_up()) { + unsigned long kernel_end = __pa_symbol(_end); + + /* + * we need two separate calls here. This is because we want to + * allocate page tables above the kernel. So we first map + * [kernel_end, end) to make memory above the kernel be mapped + * as soon as possible. And then use page tables allocated above + * the kernel to map [ISA_END_ADDRESS, kernel_end). + */ + memory_map_bottom_up(kernel_end, end); + memory_map_bottom_up(ISA_END_ADDRESS, kernel_end); + } else { + memory_map_top_down(ISA_END_ADDRESS, end); + } + +#ifdef CONFIG_X86_64 + if (max_pfn > max_low_pfn) { + /* can we preserve max_low_pfn ?*/ + max_low_pfn = max_pfn; + } +#else + early_ioremap_page_table_range_init(); +#endif + + load_cr3(swapper_pg_dir); + __flush_tlb_all(); + + x86_init.hyper.init_mem_mapping(); + + early_memtest(0, max_pfn_mapped << PAGE_SHIFT); +} + +/* + * Initialize an mm_struct to be used during poking and a pointer to be used + * during patching. + */ +void __init poking_init(void) +{ + spinlock_t *ptl; + pte_t *ptep; + + poking_mm = mm_alloc(); + BUG_ON(!poking_mm); + + /* Xen PV guests need the PGD to be pinned. */ + paravirt_enter_mmap(poking_mm); + + /* + * Randomize the poking address, but make sure that the following page + * will be mapped at the same PMD. We need 2 pages, so find space for 3, + * and adjust the address if the PMD ends after the first one. + */ + poking_addr = TASK_UNMAPPED_BASE; + if (IS_ENABLED(CONFIG_RANDOMIZE_BASE)) + poking_addr += (kaslr_get_random_long("Poking") & PAGE_MASK) % + (TASK_SIZE - TASK_UNMAPPED_BASE - 3 * PAGE_SIZE); + + if (((poking_addr + PAGE_SIZE) & ~PMD_MASK) == 0) + poking_addr += PAGE_SIZE; + + /* + * We need to trigger the allocation of the page-tables that will be + * needed for poking now. Later, poking may be performed in an atomic + * section, which might cause allocation to fail. + */ + ptep = get_locked_pte(poking_mm, poking_addr, &ptl); + BUG_ON(!ptep); + pte_unmap_unlock(ptep, ptl); +} + +/* + * devmem_is_allowed() checks to see if /dev/mem access to a certain address + * is valid. The argument is a physical page number. + * + * On x86, access has to be given to the first megabyte of RAM because that + * area traditionally contains BIOS code and data regions used by X, dosemu, + * and similar apps. Since they map the entire memory range, the whole range + * must be allowed (for mapping), but any areas that would otherwise be + * disallowed are flagged as being "zero filled" instead of rejected. + * Access has to be given to non-kernel-ram areas as well, these contain the + * PCI mmio resources as well as potential bios/acpi data regions. + */ +int devmem_is_allowed(unsigned long pagenr) +{ + if (region_intersects(PFN_PHYS(pagenr), PAGE_SIZE, + IORESOURCE_SYSTEM_RAM, IORES_DESC_NONE) + != REGION_DISJOINT) { + /* + * For disallowed memory regions in the low 1MB range, + * request that the page be shown as all zeros. + */ + if (pagenr < 256) + return 2; + + return 0; + } + + /* + * This must follow RAM test, since System RAM is considered a + * restricted resource under CONFIG_STRICT_DEVMEM. + */ + if (iomem_is_exclusive(pagenr << PAGE_SHIFT)) { + /* Low 1MB bypasses iomem restrictions. */ + if (pagenr < 256) + return 1; + + return 0; + } + + return 1; +} + +void free_init_pages(const char *what, unsigned long begin, unsigned long end) +{ + unsigned long begin_aligned, end_aligned; + + /* Make sure boundaries are page aligned */ + begin_aligned = PAGE_ALIGN(begin); + end_aligned = end & PAGE_MASK; + + if (WARN_ON(begin_aligned != begin || end_aligned != end)) { + begin = begin_aligned; + end = end_aligned; + } + + if (begin >= end) + return; + + /* + * If debugging page accesses then do not free this memory but + * mark them not present - any buggy init-section access will + * create a kernel page fault: + */ + if (debug_pagealloc_enabled()) { + pr_info("debug: unmapping init [mem %#010lx-%#010lx]\n", + begin, end - 1); + /* + * Inform kmemleak about the hole in the memory since the + * corresponding pages will be unmapped. + */ + kmemleak_free_part((void *)begin, end - begin); + set_memory_np(begin, (end - begin) >> PAGE_SHIFT); + } else { + /* + * We just marked the kernel text read only above, now that + * we are going to free part of that, we need to make that + * writeable and non-executable first. + */ + set_memory_nx(begin, (end - begin) >> PAGE_SHIFT); + set_memory_rw(begin, (end - begin) >> PAGE_SHIFT); + + free_reserved_area((void *)begin, (void *)end, + POISON_FREE_INITMEM, what); + } +} + +/* + * begin/end can be in the direct map or the "high kernel mapping" + * used for the kernel image only. free_init_pages() will do the + * right thing for either kind of address. + */ +void free_kernel_image_pages(const char *what, void *begin, void *end) +{ + unsigned long begin_ul = (unsigned long)begin; + unsigned long end_ul = (unsigned long)end; + unsigned long len_pages = (end_ul - begin_ul) >> PAGE_SHIFT; + + free_init_pages(what, begin_ul, end_ul); + + /* + * PTI maps some of the kernel into userspace. For performance, + * this includes some kernel areas that do not contain secrets. + * Those areas might be adjacent to the parts of the kernel image + * being freed, which may contain secrets. Remove the "high kernel + * image mapping" for these freed areas, ensuring they are not even + * potentially vulnerable to Meltdown regardless of the specific + * optimizations PTI is currently using. + * + * The "noalias" prevents unmapping the direct map alias which is + * needed to access the freed pages. + * + * This is only valid for 64bit kernels. 32bit has only one mapping + * which can't be treated in this way for obvious reasons. + */ + if (IS_ENABLED(CONFIG_X86_64) && cpu_feature_enabled(X86_FEATURE_PTI)) + set_memory_np_noalias(begin_ul, len_pages); +} + +void __ref free_initmem(void) +{ + e820__reallocate_tables(); + + mem_encrypt_free_decrypted_mem(); + + free_kernel_image_pages("unused kernel image (initmem)", + &__init_begin, &__init_end); +} + +#ifdef CONFIG_BLK_DEV_INITRD +void __init free_initrd_mem(unsigned long start, unsigned long end) +{ + /* + * end could be not aligned, and We can not align that, + * decompressor could be confused by aligned initrd_end + * We already reserve the end partial page before in + * - i386_start_kernel() + * - x86_64_start_kernel() + * - relocate_initrd() + * So here We can do PAGE_ALIGN() safely to get partial page to be freed + */ + free_init_pages("initrd", start, PAGE_ALIGN(end)); +} +#endif + +void __init zone_sizes_init(void) +{ + unsigned long max_zone_pfns[MAX_NR_ZONES]; + + memset(max_zone_pfns, 0, sizeof(max_zone_pfns)); + +#ifdef CONFIG_ZONE_DMA + max_zone_pfns[ZONE_DMA] = min(MAX_DMA_PFN, max_low_pfn); +#endif +#ifdef CONFIG_ZONE_DMA32 + max_zone_pfns[ZONE_DMA32] = min(MAX_DMA32_PFN, max_low_pfn); +#endif + max_zone_pfns[ZONE_NORMAL] = max_low_pfn; +#ifdef CONFIG_HIGHMEM + max_zone_pfns[ZONE_HIGHMEM] = max_pfn; +#endif + + free_area_init(max_zone_pfns); +} + +__visible DEFINE_PER_CPU_ALIGNED(struct tlb_state, cpu_tlbstate) = { + .loaded_mm = &init_mm, + .next_asid = 1, + .cr4 = ~0UL, /* fail hard if we screw up cr4 shadow initialization */ +}; + +#ifdef CONFIG_ADDRESS_MASKING +DEFINE_PER_CPU(u64, tlbstate_untag_mask); +EXPORT_PER_CPU_SYMBOL(tlbstate_untag_mask); +#endif + +void update_cache_mode_entry(unsigned entry, enum page_cache_mode cache) +{ + /* entry 0 MUST be WB (hardwired to speed up translations) */ + BUG_ON(!entry && cache != _PAGE_CACHE_MODE_WB); + + __cachemode2pte_tbl[cache] = __cm_idx2pte(entry); + __pte2cachemode_tbl[entry] = cache; +} + +#ifdef CONFIG_SWAP +unsigned long arch_max_swapfile_size(void) +{ + unsigned long pages; + + pages = generic_max_swapfile_size(); + + if (boot_cpu_has_bug(X86_BUG_L1TF) && l1tf_mitigation != L1TF_MITIGATION_OFF) { + /* Limit the swap file size to MAX_PA/2 for L1TF workaround */ + unsigned long long l1tf_limit = l1tf_pfn_limit(); + /* + * We encode swap offsets also with 3 bits below those for pfn + * which makes the usable limit higher. + */ +#if CONFIG_PGTABLE_LEVELS > 2 + l1tf_limit <<= PAGE_SHIFT - SWP_OFFSET_FIRST_BIT; +#endif + pages = min_t(unsigned long long, l1tf_limit, pages); + } + return pages; +} +#endif + +#ifdef CONFIG_EXECMEM +static struct execmem_info execmem_info __ro_after_init; + +struct execmem_info __init *execmem_arch_setup(void) +{ + unsigned long start, offset = 0; + + if (kaslr_enabled()) + offset = get_random_u32_inclusive(1, 1024) * PAGE_SIZE; + + start = MODULES_VADDR + offset; + + execmem_info = (struct execmem_info){ + .ranges = { + [EXECMEM_DEFAULT] = { + .flags = EXECMEM_KASAN_SHADOW, + .start = start, + .end = MODULES_END, + .pgprot = PAGE_KERNEL, + .alignment = MODULE_ALIGN, + }, + }, + }; + + return &execmem_info; +} +#endif /* CONFIG_EXECMEM */ diff --git a/src/_nfdos/kernel/neurotron/src/neurotron/kernel_log_agent.py b/src/_nfdos/kernel/neurotron/src/neurotron/kernel_log_agent.py new file mode 100644 index 0000000..bd4d842 --- /dev/null +++ b/src/_nfdos/kernel/neurotron/src/neurotron/kernel_log_agent.py @@ -0,0 +1,42 @@ +# neurotron/kernel_log_agent.py + +from pathlib import Path +from neurotron.logbus import logbus + +class KernelLogAgent: + name = "kernel.log" + + def __init__(self, cortex, max_lines=256): + self.ctx = cortex + self.max_lines = max_lines + self.buffer = [] # futuramente vai para dashboard pane + + def observe(self): + # leitura "bulk" por enquanto + try: + with open("/dev/kmsg", "r", encoding="utf-8", errors="ignore") as f: + for _ in range(self.max_lines): + line = f.readline() + if not line: + break + line = line.strip() + if not line: + continue + + # guarda em memória (para TUI) + self.buffer.append(line) + if len(self.buffer) > self.max_lines: + self.buffer = self.buffer[-self.max_lines:] + + # opcional: envia alguns para o Hippocampus + # self.ctx.memory.remember("kernel.msg", {"line": line}) + except Exception as e: + logbus.debug(f"[kernel.log] erro a ler /dev/kmsg: {e}") + + def think(self): + # futuro: detectar padrões, warnings, crashes… + pass + + def act(self): + # futuro: alertar o utilizador, reiniciar serviços… + pass \ No newline at end of file diff --git a/src/_nfdos/rootfs/opt/kernel/neurotron/src/neurotron/kernel_log_agent.py b/src/_nfdos/rootfs/opt/kernel/neurotron/src/neurotron/kernel_log_agent.py new file mode 100644 index 0000000..bd4d842 --- /dev/null +++ b/src/_nfdos/rootfs/opt/kernel/neurotron/src/neurotron/kernel_log_agent.py @@ -0,0 +1,42 @@ +# neurotron/kernel_log_agent.py + +from pathlib import Path +from neurotron.logbus import logbus + +class KernelLogAgent: + name = "kernel.log" + + def __init__(self, cortex, max_lines=256): + self.ctx = cortex + self.max_lines = max_lines + self.buffer = [] # futuramente vai para dashboard pane + + def observe(self): + # leitura "bulk" por enquanto + try: + with open("/dev/kmsg", "r", encoding="utf-8", errors="ignore") as f: + for _ in range(self.max_lines): + line = f.readline() + if not line: + break + line = line.strip() + if not line: + continue + + # guarda em memória (para TUI) + self.buffer.append(line) + if len(self.buffer) > self.max_lines: + self.buffer = self.buffer[-self.max_lines:] + + # opcional: envia alguns para o Hippocampus + # self.ctx.memory.remember("kernel.msg", {"line": line}) + except Exception as e: + logbus.debug(f"[kernel.log] erro a ler /dev/kmsg: {e}") + + def think(self): + # futuro: detectar padrões, warnings, crashes… + pass + + def act(self): + # futuro: alertar o utilizador, reiniciar serviços… + pass \ No newline at end of file diff --git a/src/tui/dashboard/panes/chat.py b/src/tui/dashboard/panes/chat.py new file mode 100644 index 0000000..e69de29 diff --git a/src/tui/dashboard/panes/kernel.py b/src/tui/dashboard/panes/kernel.py new file mode 100644 index 0000000..e69de29 diff --git a/src/tui/dashboard/panes/memory.py b/src/tui/dashboard/panes/memory.py new file mode 100644 index 0000000..e69de29 diff --git a/src/tui/dashboard/panes/status.py b/src/tui/dashboard/panes/status.py new file mode 100644 index 0000000..e69de29 diff --git a/src/tui/dashboard/panes/trm.py b/src/tui/dashboard/panes/trm.py new file mode 100644 index 0000000..e69de29 diff --git a/src/tui/dashboard/renderer.py b/src/tui/dashboard/renderer.py new file mode 100644 index 0000000..e69de29 diff --git a/src/tui/menu_kernel.py b/src/tui/menu_kernel.py index 540b4c4..70009b4 100644 --- a/src/tui/menu_kernel.py +++ b/src/tui/menu_kernel.py @@ -14,9 +14,10 @@ console = Console() def corrigir_kernel_headers(linux_dir, env): """ - Corrige headers incompatíveis com C23 em vários caminhos. - Adiciona guards para typedef bool / enum { false, true }. + Ajusta headers para compatibilidade com C23, mas + FORÇA que o boot code inteiro seja compilado em GNU11. """ + console.print("[yellow]→ Patching kernel headers for C23 compatibility...[/]") header_candidates = [ @@ -28,7 +29,7 @@ def corrigir_kernel_headers(linux_dir, env): "arch/x86/include/asm/types.h", ] - # Antes de aplicar os patches: + # Preparar scripts e headers safe_run(["make", "prepare"], env=env) safe_run(["make", "scripts"], env=env) @@ -40,18 +41,19 @@ def corrigir_kernel_headers(linux_dir, env): content = path.read_text() patched = False - # Corrige enum false/true - if "false" in content and "__bool_true_false_are_defined" not in content: + # Guard enum false/true + if "enum {" in content and "false" in content and "__bool_true_false_are_defined" not in content: content = content.replace( "enum {\n false = 0,\n true = 1\n};", "#ifndef __bool_true_false_are_defined\n" "enum {\n false = 0,\n true = 1\n};\n" - "#define __bool_true_false_are_defined 1\n#endif" + "#define __bool_true_false_are_defined 1\n" + "#endif" ) patched = True - # Corrige typedef _Bool - if "typedef _Bool" in content and "__STDC_VERSION__" not in content: + # typedef _Bool bool; + if "typedef _Bool" in content and "STDC_VERSION" not in content: content = content.replace( "typedef _Bool bool;", "#ifndef __cplusplus\n" @@ -66,26 +68,52 @@ def corrigir_kernel_headers(linux_dir, env): path.write_text(content) console.print(f"[green]✔ Patched:[/] {relpath}") - # Corrige Makefile do boot - boot_makefile = linux_dir / "arch/x86/boot/Makefile" - if boot_makefile.exists(): - with open(boot_makefile, "a") as f: - f.write("\n# C23 fix\nccflags-y += -std=gnu11 -Wno-error\n") - console.print("[cyan]→ Applied local Makefile override for boot code (C23 fix)[/]") + # =========================================================== + # 🔥 Parte crítica: Remover C23 do boot COMPLETO + # =========================================================== - # Corrige Makefile do boot/compressed - boot_compr_makefile = linux_dir / "arch/x86/boot/compressed/Makefile" - if boot_compr_makefile.exists(): - with open(boot_compr_makefile, "a") as f: - f.write("\n# C23 fix\nccflags-y += -std=gnu11 -Wno-error\n") - console.print("[cyan]→ Applied local Makefile override for boot/compressed code (C23 fix)[/]") + # Diretórios que NUNCA podem ser compilados com C23 + BOOT_CRITICAL_DIRS = [ + "arch/x86/boot", + "arch/x86/boot/compressed", + "drivers/firmware/efi/libstub", + ] + + for d in BOOT_CRITICAL_DIRS: + mk = linux_dir / d / "Makefile" + if mk.exists(): + # Remove flags C23 pré-existentes + text = mk.read_text() + text = text.replace("-std=c23", "") + text = text.replace("-std=gnu2x", "") + + with open(mk, "w") as f: + f.write(text) + + # Agora força GNU11 explícito + with open(mk, "a") as f: + f.write("\n# --- NFDOS C23 BOOT SANITY OVERRIDE ---\n") + f.write("ccflags-y += -std=gnu11\n") + f.write("KBUILD_CFLAGS := $(filter-out -std=c23 -std=gnu2x,$(KBUILD_CFLAGS))\n") + f.write("KBUILD_CFLAGS += -std=gnu11\n") + + console.print(f"[cyan]→ Boot directory forced to GNU11:[/] {d}") + + # =========================================================== + # 🔥 Garantia absoluta: remover C23 de flags globais herdadas + # =========================================================== + + top_makefile = linux_dir / "Makefile" + if top_makefile.exists(): + txt = top_makefile.read_text() + txt = txt.replace("-std=c23", "") + txt = txt.replace("-std=gnu2x", "") + with open(top_makefile, "w") as f: + f.write(txt) + console.print("[cyan]→ Global C23 overrides neutralized in main Makefile[/]") + + console.print("[green]✔ Kernel headers & boot toolchain fully sanitized.[/]") - # Corrige Makefile do EFI stub - efi_makefile = linux_dir / "drivers/firmware/efi/libstub/Makefile" - if efi_makefile.exists(): - with open(efi_makefile, "a") as f: - f.write("\n# C23 fix\nccflags-y += -std=gnu11 -Wno-error\n") - console.print("[cyan]→ Applied local Makefile override for EFI stub (C23 fix)[/]") def corrigir_kernel_overrides(cross_compile): env = { @@ -120,6 +148,29 @@ def corrigir_kernel_overrides(cross_compile): "CONFIG_MCORE2", #"CONFIG_EXT4_FS_POSIX_ACL", #"CONFIG_EXT4_FS_SECURITY", + # Console VGA (comentado para modo serial-only) + # "CONFIG_VT", + # "CONFIG_VT_CONSOLE", + # "CONFIG_VGA_CONSOLE", + # "CONFIG_FB", + # "CONFIG_FB_VESA", + # "CONFIG_FRAMEBUFFER_CONSOLE", + # "CONFIG_FONT_8x16", + # "CONFIG_FONT_8x8", + # # "CONFIG_X86_MCE", + # # "CONFIG_X86_MCE_INTEL", + # "CONFIG_X86_LOCAL_APIC", + # "CONFIG_X86_IO_APIC", + # "CONFIG_X86_MSR", + # "CONFIG_X86_FEATURE_NAMES", + # "CONFIG_X86_TSC", + # "CONFIG_X86_CMOV", + # "CONFIG_RD_GZIP", + # "CONFIG_RD_BZIP2", + # "CONFIG_RD_LZMA", + # "CONFIG_RD_XZ", + # "CONFIG_RD_LZO", + # "CONFIG_RD_LZ4", ] # VirtIO (para bloco, rede, PCI) @@ -151,8 +202,14 @@ def corrigir_kernel_overrides(cross_compile): "CONFIG_DEBUG_INFO_NONE", # evita symbols extras ] - # Desativa gráficos e Garante compatibilidade máxima de CPU (para manter o kernel leve, limpo e evitar CR4 panics) - disable_graphics = [ + # Garante compatibilidade máxima de CPU (para manter o kernel leve, limpo e evitar CR4 panics) + disable_extras = [ + # Deixar estes quatro comentados. Eles são core para x86_64 + QEMU. + # "CONFIG_X86_PAE", + # "CONFIG_X86_PGE", + # "CONFIG_X86_PAT", + # "CONFIG_X86_PSE", + # modo serial-only "CONFIG_VT", "CONFIG_VT_CONSOLE", "CONFIG_VGA_CONSOLE", @@ -169,6 +226,15 @@ def corrigir_kernel_overrides(cross_compile): "CONFIG_SMAP", "CONFIG_SMEP", "CONFIG_PAGE_TABLE_ISOLATION", + # estes estao sendo testados + # "CONFIG_X86_PSE36", + # "CONFIG_X86_VME", + # "CONFIG_X86_PVI", + # "CONFIG_X86_PCID", + # "CONFIG_PAGE_TABLE_ISOLATION", + # "CONFIG_PARAVIRT", + # "CONFIG_PARAVIRT_CLOCK", + # "CONFIG_ARCH_RANDOM", ] # Habilita todos os conjuntos @@ -184,7 +250,7 @@ def corrigir_kernel_overrides(cross_compile): safe_run(["scripts/config", "--disable", opt], env=env) # Desativa o que não precisamos - for opt in disable_graphics: + for opt in disable_extras: safe_run(["scripts/config", "--disable", opt], env=env) # Formatos binários básicos @@ -433,7 +499,7 @@ def run(): console.rule("[bold yellow]Kernel / BusyBox / Python[/bold yellow]") console.print("1. Obter código-fonte do Kernel Linux") console.print("2. Compilar Kernel com Toolchain NFDOS") - console.print("3. Obter e compilar BusyBox") + console.print("3. Obter e compilar BusyBox com Toolchain NFDOS") console.print("4. Compilar Python estatico com Toolchain NFDOS") console.print("5. Obter e compilar Bibliotecas do Neurotron") console.print("6. Montar RootFS e gerar imagem bootável") @@ -501,6 +567,10 @@ def run(): # Passo 3 — Aplicar patches C23 aos headers corrigir_kernel_headers(linux_dir, env) + # Passo 3.1 — Aplicar patch para filtrar o mask para só conter bits seguros. + safe_run(["git", "checkout", "--", "arch/x86/mm/init.c"], cwd=linux_dir) + safe_run(f"cp {nfdos_dir}/init.c {linux_dir}/arch/x86/mm/init.c", shell=True) + # Passo 4 — Aplicar overrides minimalistas (serial-only, sem VGA) corrigir_kernel_overrides(cross_compile) @@ -841,13 +911,16 @@ def run(): qemu_cmd = ( f"qemu-system-x86_64 " - f"-machine q35,accel=kvm " - f"-cpu qemu64 " + f"-machine q35,accel=kvm " # q35,accel=kvm + f"-cpu qemu64 " # qemu64 f"-kernel {bz_image} " f"-initrd {nfdos_dir}/initramfs.cpio.gz " f"-append '{kernel_params}' " f"-drive file={data_disk},if=virtio,format=raw " f"-m 1024 " + # f"-vga std " + # f"-display default " + # f"-serial mon:stdio " f"-nographic " f"-no-reboot" )