电脑关机,操作系统如何实现呢? (C内核开发)

Shutdown computer, how operating systems achieve it? (C Kernel development)

我最近一直在用 C 开发 OS。但是我怎样才能关闭计算机?通过说 'shutdown the computer',我的意思是强制关机。

我怎样才能在 C 内核开发中做到这一点?
如有任何帮助,我们将不胜感激。

总结答案中的所有评论,使其保持不变:

处理电源管理和关机的现代方法(大约 2020 年)是使用 Advanced Configuration and Power Interface (ACPI), see for example Getting Started With ACPI and OS Shutdown

History of ACPI

ACPI was developed through collaboration between Intel, Microsoft, Toshiba, HP, and Phoenix in the mid-1990s. Before the development of ACPI, operating systems (OS) primarily used BIOS (Basic Input/Output System) interfaces for power management and device discovery and configuration. This power management approach used the OS’s ability to call the system BIOS natively for power management. The BIOS was also used to discover system devices and load drivers based on probing input/output (I/O) and attempting to match the correct driver to the correct device (plug and play). The location of devices could also be hard coded within the BIOS because the platform itself was non-enumerable.These solutions were problematic in three key ways. First, the behavior of OS applications could be negatively affected by the BIOS-configured power management settings, causing systems to go to sleep during presentations or other inconvenient times. Second, the power management interface was proprietary on each system. This required developers to learn how to configure power management for each individual system. Finally, the default settings for various devices could also conflict with each other, causing devices to crash, behave erratically, or become undiscoverable.ACPI was developed to solve these problems and others.

What is ACPI?

ACPI can first be understood as an architecture-independent power management and configuration framework that forms a subsystem within the host OS. This framework establishes a hardware register set to define power states (sleep, hibernate, wake, etc). The hardware register set can accommodate operations on dedicated hardware and general purpose hardware.The primary intention of the standard ACPI framework and the hardware register set is to enable power management and system configuration without directly calling firmware natively from the OS. ACPI serves as an interface layer between the system firmware (BIOS) and the OS, as shown in Figure0-1 and Figure0-2, with certain restrictions and rules.

来源:Advanced Configuration and Power Interface (ACPI) Specification, Version 6.3 January 2019

This answer 提供了 OS 控制计算机电源和关机问题的历史背景,以及为什么花了这么长时间才达到某些标准。引用:

Some history...

Before 1995 and the adoption of the ATX standard, the vast majority of desktop PCs had power switches which were directly connected to the power supply, and acted as mechanical switches only, interrupting the electric circuit when opened. It was therefore impossible for software to control the state of the power supply. But that wasn’t much of a problem initially: when the IBM PC was designed, storage media (including hard drives) had no caches, so when the hardware told the operating system that a write was finished, it really was. Under DOS, the kernel and shell worked together to ensure that when the DOS prompt was displayed, all the buffers were flushed; when software caches appeared, they adhered to this too (at least, the well-behaved ones did). Users were taught to exit programs, wait for the prompt, and wait for drive lights to switch off before powering the system down. (They might also need to PARK the drive heads but that’s another story.) Even with pre-95 versions Windows, users exited to DOS before switching the system off.

Windows 95 and other multi-tasking operating systems changed the picture: they didn’t “exit to DOS” on shutdown (either because they weren’t supposed to, or because there was no DOS to return to), so users couldn’t wait for a prompt to appear before switching off. In most truly multi-tasking systems there’s never really a quiescent state where the system is safe to power off, in normal operation; so most multi-tasking operating systems have a way for the user to say “I want to power the system down, prepare to do so”, and the operating system then needs to tell the user when it’s safe to power off. This ensures that all applications have finished writing the user’s files to disk, and that the system is in a consistent state (ignoring hard drive caches here...).

Shutting down PCs

Two features brought system power under operating system control: APM on the one hand, and ATX on the other. APM, which was designed for laptops initially, provided mechanisms for software to request changes in the system’s power state: fully on, in standby, suspended, or off. ATX changed the physical connections in the system so that power control became possible everywhere: it required that the power button no longer be a switch directly connected to the power supply, but instead that it be connected to the motherboard, and that the motherboard control the power supply itself. The power supply was also changed so that it would supply a small amount of current all the time, allowing the system to be left in “soft off” status, i.e. with enough capabilities to turn itself back on again when requested to do so.

You can see an example of the use of APM to power off a PC in Shutdown, a small assembly-language program written for DOS. Operating systems such as Windows 95 (with the APM drivers installed) would do the same thing.

It was quite exciting (to me anyway) to see APM and ATX roll out progressively in the second half of the nineties, and see systems suddenly acquire the ability to turn themselves off without human intervention, and to turn themselves back on at the press of a key on some systems. This was yet another sign of PCs “growing up” (“real” computers, i.e. Unix workstations in my mind at the time, had had the ability for a while, as had Macs).

Why did it take so long?

All this doesn’t address the actual question:

Was it really that hard to implement a self shut-off? What is the reason it took quite long for computers to feature this.

如果你从一开始就设计好,其实并不难 实施自我关闭,许多系统都具有这种能力 在 PC 获得它之前的好几年。

[..]在九十年代初期,尽管现在看起来令人惊讶,但有一个公平的 关于计算未来的不确定性。苹果是 凭借更便宜的 Mac 卷土重来,工作站制造商 发布低价系统(或者更确切地说,不那么昂贵的系统), 各种操作系统和平台争先恐后 (Be,RiscPC...),IBM 仍在推动 OS/2 和 Taligent,Microsoft 推Windows NT等

最终,一个公司联盟自行“补救” 这种情况:英特尔和微软(当时简称为 温特尔)。这开始于九十年代初,但还没有完成 有一会儿;当 ATX 于 1995 年发布时(由 Intel 在其 自己的),专家们喜欢它,但不确定它会说服 行业,尽管他们很快就被证明是错误的。 Windows95 虽然达成了协议,但英特尔和微软成为了 PC 平台(特别是 PC 系统设计指南)。

这里是a Microsoft patent90年代的软件控制计算机休眠,与软件控制的电源管理有关。

实际上,软件控制关机是一种关机模拟,因为真正的关机发生在硬件电源实际关闭时.有效的软关机是让计算机完全不做任何事并消耗尽可能少的电力。因此 OS 确保 结束所有进程并使 CPU 转到模拟关闭的特定 OS 例程 (注意:此状态通常不能除非通过重启的硬件中断,否则会被逆转)。 OS 使软关机的例程是否使用 ACPI 或其他一些 method/interface 来模拟是另一个问题。

This post 粗略地描述了 linux 内核的关闭过程,以获得一个概念。

[..]Anyways in there we have basically three functions that sketch the process of shutting down the system

void kernel_halt(void) // which ends with a system in halt state
void kernel_power_off(void) // which ends with a system powered off
void kernel_restart(char *cmd) // which ends the system to yet restart it

Those functions are very brief and can be hence pasted here in complete. Their code best shows what steps are taken on the way to shutdown in the kernel. (the comments are by me and might not be 100% ideal and correct, check yourself for being sure. It is simple a try.

void kernel_halt(void)
{
    // 1st step does:
    // a) call functions/callback registered to run at reboot/shutdown
    // b) set system_sate to SYSTEM_HALT
    // c) stop the userspacetool interaction
    // d) call device_shutdown() function
    kernel_shutdown_prepare(SYSTEM_HALT);

    // 2nd step: I think this is mostly a necessity for multi-cpu systems
    migrate_to_reboot_cpu();

    // 3rd step:
    // syscore_shutdown - Execute all the registered system core shutdown callbacks 
    syscore_shutdown();

    // 4th messages
    pr_emerg("System halted\n");
    kmsg_dump(KMSG_DUMP_HALT);

    // 5th call arch specific cpu-halt-code
    machine_halt();
}