基于linux与busybox的reboot命令流程分析

http://www.xuebuyuan.com/736763.html

基于Linux与Busybox的Reboot命令流程分析

***************************************************************************************************************************
作者:EasyWave                                                                                 时间:2013.01.26

类别:Linux 内核系统源码分析                                                             声明:转载,请保留链接

注意:如有错误,欢迎指正。这些是我学习的日志文章......

***************************************************************************************************************************

一:Busyobx层的分析

        这段时间,在忙到一个项目时,需要在busybox中用到reboot命令,开始在busybox中的shell中输入reboot命令,始终如下的信息,然后就停止在那里了,无法重启...为了彻底的弄明白这个问题,我在网络上找了很久,终于有个人写的一个reboot流程分析,我就借花献佛.在这里重新分析下busybox是如何运行这个命令,同时又是如何调用到Linux内核中的mach_reset中的arch_reset,当针对不同的ARM芯片时,作为Linux内核开发和驱动开发的朋友,对于这个流程还是一定要了解的。要不,出现问题,又如何找出问题呢。忘记了reboot的打印信息了,如下:

The system is going down NOW !!

Sending SIGTERM to all processes.

Sending SIGKILL to all processes.

Please stand by while rebooting the system.

Restarting system.

.


通过分析busybox1.20.0的代码可以看出在init.c中有这样一行的代码,如下:

int init_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;

int init_main(int argc UNUSED_PARAM, char **argv)

{

          static const int magic[] = {

                    RB_HALT_SYSTEM,

                    RB_POWER_OFF,

                    RB_AUTOBOOT

          };

          static const smallint signals[] = { SIGUSR1, SIGUSR2, SIGTERM };

          ......

          /* struct sysinfo is linux-specific */

#ifdef __linux__

          /* Make sure there is enough memory to do something useful. */

          if (ENABLE_SWAPONOFF) { //是否配置了swapoff命令

                    struct sysinfo info;

 

                    if (sysinfo(&info) == 0

                     && (info.mem_unit ? info.mem_unit : 1) * (long long)info.totalram < 1024*1024

                    ) {

                               message(L_CONSOLE, "Low memory, forcing swapon");

                               /* swapon -a requires /proc typically */

                               new_init_action(SYSINIT, "mount -t proc proc /proc", "");

                               /* Try to turn on swap */

                               new_init_action(SYSINIT, "swapon -a", "");

                               run_actions(SYSINIT);   /* wait and removing */

                    }

          }

#endif

          ......

/* Make the command line just say "init"  - thats all, nothing else */

          strncpy(argv[0], "init", strlen(argv[0]));

          /* Wipe argv[1]-argv[N] so they don't clutter the ps listing */

          while (*++argv)

                    memset(*argv, 0, strlen(*argv));

 

          /* Set up signal handlers */

          /* Set up signal handlers */

          if (!DEBUG_INIT) {

                    struct sigaction sa;

 

                    bb_signals(0

                               + (1 << SIGUSR1) /* halt */

                               + (1 << SIGTERM) /* reboot */

                               + (1 << SIGUSR2) /* poweroff */

                               , halt_reboot_pwoff);//看到这个halt_reboot_pwoff

                    signal(SIGQUIT, restart_handler); /* re-exec another init */ //看到这个restart_handler函数,这是我们需要分析的

 

                    /* Stop handler must allow only SIGCONT inside itself */

                    memset(&sa, 0, sizeof(sa));

                    sigfillset(&sa.sa_mask);

                    sigdelset(&sa.sa_mask, SIGCONT);

                    sa.sa_handler = stop_handler;

                    /* NB: sa_flags doesn't have SA_RESTART.

                     * It must be able to interrupt wait().

                     */

                    sigaction_set(SIGTSTP, &sa); /* pause */

                    /* Does not work as intended, at least in 2.6.20.

                     * SIGSTOP is simply ignored by init:

                     */

                    sigaction_set(SIGSTOP, &sa); /* pause */

 

                    /* SIGINT (Ctrl-Alt-Del) must interrupt wait(),

                     * setting handler without SA_RESTART flag.

                     */

                    bb_signals_recursive_norestart((1 << SIGINT), record_signo);

          }

          ......

}

单独拿出halt_reboot_pwoff和restart_handler这个函数来看看

/* The SIGUSR[12]/SIGTERM handler */

static void halt_reboot_pwoff(int sig) NORETURN;

static void halt_reboot_pwoff(int sig)

{

          const char *m;

          unsigned rb;

 

          /* We may call run() and it unmasks signals,

           * including the one masked inside this signal handler.

           * Testcase which would start multiple reboot scripts:

           *  while true; do reboot; done

           * Preventing it:

           */

          reset_sighandlers_and_unblock_sigs();

 

          run_shutdown_and_kill_processes();

 

          m = "halt";

          rb = RB_HALT_SYSTEM;

          if (sig == SIGTERM) {

                    m = "reboot";

                    rb = RB_AUTOBOOT;

          } else if (sig == SIGUSR2) {

                    m = "poweroff";

                    rb = RB_POWER_OFF;

          }

          message(L_CONSOLE, "Requesting system %s", m);

          pause_and_low_level_reboot(rb);

          /* not reached */

}


restart_handler函数如下:

/* Handler for QUIT - exec "restart" action,

 * else (no such action defined) do nothing */

static void restart_handler(int sig UNUSED_PARAM)

{

          struct init_action *a;

 

          for (a = init_action_list; a; a = a->next) {

                    if (!(a->action_type & RESTART))

                               continue;

 

                    /* Starting from here, we won't return.

                     * Thus don't need to worry about preserving errno

                     * and such.

                     */

 

                    reset_sighandlers_and_unblock_sigs();

 

                    run_shutdown_and_kill_processes();

 

#ifdef RB_ENABLE_CAD

                    /* Allow Ctrl-Alt-Del to reboot the system.

                     * This is how kernel sets it up for init, we follow suit.

                     */

                    reboot(RB_ENABLE_CAD); /* misnomer */

#endif

 

                    if (open_stdio_to_tty(a->terminal)) {

                               dbg_message(L_CONSOLE, "Trying to re-exec %s", a->command);

                               /* Theoretically should be safe.

                                * But in practice, kernel bugs may leave

                                * unkillable processes, and wait() may block forever.

                                * Oh well. Hoping "new" init won't be too surprised

                                * by having children it didn't create.

                                */

                               //while (wait(NULL) > 0)

                               //        continue;

                               init_exec(a->command);

                    }

                    /* Open or exec failed */

                    pause_and_low_level_reboot(RB_HALT_SYSTEM);

                    /* not reached */

          }

}


通过分析,我们看到他们都会有调用这两个函数:reset_sighandlers_and_unblock_sigs();以及 run_shutdown_and_kill_processes();,我们重点关注如下这个函数:

static void run_shutdown_and_kill_processes(void)

{

          /* Run everything to be run at "shutdown".  This is done _prior_

           * to killing everything, in case people wish to use scripts to

           * shut things down gracefully... */

          run_actions(SHUTDOWN);

 

          message(L_CONSOLE | L_LOG, "The system is going down NOW!");

 

          /* Send signals to every process _except_ pid 1 */

          kill(-1, SIGTERM);

          message(L_CONSOLE | L_LOG, "Sent SIG%s to all processes", "TERM");

          sync();

          sleep(1);

 

          kill(-1, SIGKILL);

          message(L_CONSOLE, "Sent SIG%s to all processes", "KILL");

          sync();

          /*sleep(1); - callers take care about making a pause */

}


嘿嘿,终于看到了上面的打印信息:The system is going down NOW !! 以及Sending SIGTERM to all processes. 同时在上面的halt_reboot_pwoff和restart_handler中都会调用这样一个函数,如下:

static void pause_and_low_level_reboot(unsigned magic) NORETURN;

static void pause_and_low_level_reboot(unsigned magic)

{

          pid_t pid;

 

          /* Allow time for last message to reach serial console, etc */

          sleep(1);

 

          /* We have to fork here, since the kernel calls do_exit(EXIT_SUCCESS)

           * in linux/kernel/sys.c, which can cause the machine to panic when

           * the init process exits... */

          pid = vfork();

          if (pid == 0) { /* child */

                    reboot(magic);

                    _exit(EXIT_SUCCESS);

          }

          while (1)

                    sleep(1);

}


看到了吗?有一个reboot(magic)函数,对于vfork函数,请参考fork函数。这里不多说了.... 我们现在来看看reboot.h文件,如下:

/*

 * Definitions related to the reboot() system call,

 * shared between init.c and halt.c.

 */

 

#include <sys/reboot.h>

 

#ifndef RB_HALT_SYSTEM

# if defined(__linux__)

#  define RB_HALT_SYSTEM  0xcdef0123

#  define RB_ENABLE_CAD   0x89abcdef

#  define RB_DISABLE_CAD  0

#  define RB_POWER_OFF    0x4321fedc

#  define RB_AUTOBOOT     0x01234567

# elif defined(RB_HALT)

#  define RB_HALT_SYSTEM  RB_HALT

# endif

#endif

 

/* Stop system and switch power off if possible.  */

#ifndef RB_POWER_OFF

# if defined(RB_POWERDOWN)

#  define RB_POWER_OFF  RB_POWERDOWN

# elif defined(__linux__)

#  define RB_POWER_OFF  0x4321fedc

# else

#  warning "poweroff unsupported, using halt as fallback"

#  define RB_POWER_OFF  RB_HALT_SYSTEM

# endif

#endif

而在linux的内核中的定义如下:


busybox和linux内核中的REBOOT的定义值是一样的。看到了没有了。这个很重要的哦,否则busybox是无法调用linux内核的reboot函数。

 

二:Linux内核层的分析


Linux内核是如何衔接busybox的reboot函数的呢,如下代码:

/*

 * Reboot system call: for obvious reasons only root may call it,

 * and even root needs to set up some magic numbers in the registers

 * so that some mistake won't make this reboot the whole machine.

 * You can also set the meaning of the ctrl-alt-del-key here.

 *

 * reboot doesn't sync: do that yourself before calling this.

 */

SYSCALL_DEFINE4(reboot, int, magic1, int, magic2, unsigned int, cmd,

                    void __user *, arg)

{

          char buffer[256];

          int ret = 0;

 

          /* We only trust the superuser with rebooting the system. */

          if (!capable(CAP_SYS_BOOT))

                    return -EPERM;

 

          /* For safety, we require "magic" arguments. */

          if (magic1 != LINUX_REBOOT_MAGIC1 ||

              (magic2 != LINUX_REBOOT_MAGIC2 &&

                          magic2 != LINUX_REBOOT_MAGIC2A &&

                               magic2 != LINUX_REBOOT_MAGIC2B &&

                          magic2 != LINUX_REBOOT_MAGIC2C))

                    return -EINVAL;

 

          /* Instead of trying to make the power_off code look like

           * halt when pm_power_off is not set do it the easy way.

           */

          if ((cmd == LINUX_REBOOT_CMD_POWER_OFF) && !pm_power_off)

                    cmd = LINUX_REBOOT_CMD_HALT;

 

          lock_kernel();

          switch (cmd) {

          case LINUX_REBOOT_CMD_RESTART:

                    kernel_restart(NULL); //这个就是重新启动Linx的命令

                    break;

 

          case LINUX_REBOOT_CMD_CAD_ON:

                    C_A_D = 1;

                    break;

 

          case LINUX_REBOOT_CMD_CAD_OFF:

                    C_A_D = 0;

                    break;

 

          case LINUX_REBOOT_CMD_HALT:

                    kernel_halt();

                    unlock_kernel();

                    do_exit(0);

                    panic("cannot halt");

 

          case LINUX_REBOOT_CMD_POWER_OFF:

                    kernel_power_off();

                    unlock_kernel();

                    do_exit(0);

                    break;

 

          case LINUX_REBOOT_CMD_RESTART2:

                    if (strncpy_from_user(&buffer[0], arg, sizeof(buffer) - 1) < 0) {

                               unlock_kernel();

                               return -EFAULT;

                    }

                    buffer[sizeof(buffer) - 1] = '\0';

 

                    kernel_restart(buffer);

                    break;

 

#ifdef CONFIG_KEXEC

          case LINUX_REBOOT_CMD_KEXEC:

                    ret = kernel_kexec();

                    break;

#endif

 

#ifdef CONFIG_HIBERNATION

          case LINUX_REBOOT_CMD_SW_SUSPEND:

                    ret = hibernate();

                    break;

#endif

 

          default:

                    ret = -EINVAL;

                    break;

          }

          unlock_kernel();

          return ret;

}


继续跟踪kernel_restart()函数,如下:

 

最终会调用一个machine_restart(cmd)函数,这个是跟具体的芯片有很大的关系的,我们进一步的分析如下:

 

 

 

看到了吗,最终是调用arch_reset来复位整个系统的。同时我们也看到了S3C2440的reset的函数如下:

 

在arm_pm_restart = s3c24xx_pm_restart()函数,最终也是调用arm_machine_restart(mod, cmd)来实现的。而在arm_machine_restart()函数中,最终也是调用arch_reset()函数来实现,而这个函数是在哪里呢。在S3C2440没有看到arch_reset函数的实现,因此从S3C2410中找到了如下的代码,请继续看下面的代码:

 

       终于看到了arch_reset函数,最终是采用S3C2410或者S3C2440的WatchDog来实现reboot的命令的。大家可以想想,busybox的poweroff命令,是如何实现通过Linux系统关闭整个系统的电源呢,其实很简单,只需要实现下面的函数中的pm_power_off的回调函数即可。

 

       我们可以通过一个GPIO来控制整个系统的电源,而通过上面的pm_power_off的回调函数来实现,只需要在pm_power_off函数对GPIO进行操作就可以了。你看不是很简单吗?

 ====================================================================

at91sam9g10复位过程:

1) at91_arch_reset() = at91sam9261_reset();

kernel/arch/arm/mach-at91/at91sam9261.c

/* --------------------------------------------------------------------

 *  AT91SAM9261 processor initialization

 * -------------------------------------------------------------------- */

 

void __init at91sam9261_initialize(unsigned long main_clock)

{

    /* Map peripherals */

    iotable_init(at91sam9261_io_desc, ARRAY_SIZE(at91sam9261_io_desc));

 

    if (cpu_is_at91sam9g10())

        iotable_init(at91sam9g10_sram_desc, ARRAY_SIZE(at91sam9g10_sram_desc));

    else

        iotable_init(at91sam9261_sram_desc, ARRAY_SIZE(at91sam9261_sram_desc));

 

 

    at91_arch_reset = at91sam9261_reset;

    pm_power_off = at91sam9261_poweroff;

    at91_extern_irq = (1 << AT91SAM9261_ID_IRQ0) | (1 << AT91SAM9261_ID_IRQ1)

            | (1 << AT91SAM9261_ID_IRQ2);

 

    /* Init clock subsystem */

    at91_clock_init(main_clock);

 

    /* Register the processor-specific clocks */

    at91sam9261_register_clocks();

 

    /* Register GPIO subsystem */

    at91_gpio_init(at91sam9261_gpio, 3);

}

 

static void at91sam9261_reset(void)

{

#ifdef CONFIG_ARCH_AT91SAM9G10 

        at91_lcdc_write(ATMEL_LCDC_PWRCON, 1 << ATMEL_LCDC_GUARDT_OFFSET);

    while (at91_lcdc_read(ATMEL_LCDC_PWRCON) & ATMEL_LCDC_BUSY)

        msleep(10);

    at91_lcdc_write(ATMEL_LCDC_DMACON, 0);

    while (at91_lcdc_read(ATMEL_LCDC_DMACON) & ATMEL_LCDC_DMABUSY)

        msleep(10);

    local_irq_disable();

#endif

    printk(KERN_ERR "software rest!!!\n") ;

    // at91_sys_write(AT91_RSTC_CR, AT91_RSTC_KEY | AT91_RSTC_PROCRST | AT91_RSTC_PERRST);

at91_sys_write(AT91_RSTC_MR, AT91_RSTC_KEY | AT91_RSTC_ERSTL);    at91_sys_write(AT91_RSTC_CR, AT91_RSTC_KEY | AT91_RSTC_PROCRST | AT91_RSTC_PERRST |AT91_RSTC_EXTRST );

 }

 

static void at91sam9261_poweroff(void)

{

    at91_sys_write(AT91_SHDW_CR, AT91_SHDW_KEY | AT91_SHDW_SHDW);

}

2) arch_reset();

kernel/arch/arm/mach-at91/include/mach/system.h

static inline void arch_reset(char mode, const char *cmd)

{

    /* call the CPU-specific reset function */

    if (at91_arch_reset)

        (at91_arch_reset)();

}

3) arm_machine_restart();

arch/arm/kernel/process.c

void arm_machine_restart(char mode, const char *cmd)

{

   

    printk("in: %s:%s !\n",__FILE__,__FUNCTION__); 

    /* 

     * Clean and disable cache, and turn off interrupts

     */

    cpu_proc_fin();

 

    /* 

     * Tell the mm system that we are going to reboot -

     * we may need it to insert some 1:1 mappings so that

     * soft boot works.

     */

    setup_mm_for_reboot(mode);

 

    /* 

     * Now call the architecture specific reboot code.

     */

    arch_reset(mode, cmd);

 

    /* 

     * Whoops - the architecture was unable to reboot.

     * Tell the user!

     */

    mdelay(1000);

    printk("Reboot failed -- System halted\n");

    while (1);

}

4) machine_restart()

kernel/arch/arm/kernel/process.c

void machine_power_off(void)

{

    if (pm_power_off)

        pm_power_off();

}

 

void machine_restart(char *cmd)

{

        printk("in:%s:%s\n",__FILE__,__FUNCTION__);

        arm_pm_restart(reboot_mode, cmd);

}

 

void (*arm_pm_restart)(char str, const char *cmd) = arm_machine_restart;

EXPORT_SYMBOL_GPL(arm_pm_restart);

 

5) kernel_restart()

kernel/kernel/sys.c

void kernel_restart_prepare(char *cmd)

{

    blocking_notifier_call_chain(&reboot_notifier_list, SYS_RESTART, cmd);

    system_state = SYSTEM_RESTART;

    device_shutdown();

    sysdev_shutdown();

}

 

/**

 *  kernel_restart - reboot the system

 *  @cmd: pointer to buffer containing command to execute for restart

 *      or %NULL

 *

 *  Shutdown everything and perform a clean reboot.

 *  This is not safe to call in interrupt context.

 */

void kernel_restart(char *cmd)

{

    kernel_restart_prepare(cmd);

    if (!cmd)

        printk(KERN_EMERG "Restarting system.\n");

    else

        printk(KERN_EMERG "Restarting system with command '%s'.\n", cmd);

    machine_restart(cmd);

}

EXPORT_SYMBOL_GPL(kernel_restart);

6) SYSCALL_DEFINE4()

kernel/kernel/sys.c

/*

 * Reboot system call: for obvious reasons only root may call it,

 * and even root needs to set up some magic numbers in the registers

 * so that some mistake won't make this reboot the whole machine.

 * You can also set the meaning of the ctrl-alt-del-key here.

 *

 * reboot doesn't sync: do that yourself before calling this.

 */

SYSCALL_DEFINE4(reboot, int, magic1, int, magic2, unsigned int, cmd,

        void __user *, arg)

{

    char buffer[256];

    int ret = 0;

 

    /* We only trust the superuser with rebooting the system. */

    if (!capable(CAP_SYS_BOOT))

        return -EPERM;

 

    /* For safety, we require "magic" arguments. */

    if (magic1 != LINUX_REBOOT_MAGIC1 ||

        (magic2 != LINUX_REBOOT_MAGIC2 &&

                    magic2 != LINUX_REBOOT_MAGIC2A &&

            magic2 != LINUX_REBOOT_MAGIC2B &&

                    magic2 != LINUX_REBOOT_MAGIC2C))

        return -EINVAL;

 

    /* Instead of trying to make the power_off code look like

     * halt when pm_power_off is not set do it the easy way.

     */

    if ((cmd == LINUX_REBOOT_CMD_POWER_OFF) && !pm_power_off)

        cmd = LINUX_REBOOT_CMD_HALT;

 

    lock_kernel();

    switch (cmd) {

    case LINUX_REBOOT_CMD_RESTART:

            printk("in %s:%s:%d\n",__FILE__,__FUNCTION__,__LINE__)  ;

            kernel_restart(NULL);

        break;

 

    case LINUX_REBOOT_CMD_CAD_ON:

        C_A_D = 1;

        break;

 

    case LINUX_REBOOT_CMD_CAD_OFF:

        C_A_D = 0;

        break;

 

    case LINUX_REBOOT_CMD_HALT:

        kernel_halt();

        unlock_kernel();

        do_exit(0);

        panic("cannot halt");

 

    case LINUX_REBOOT_CMD_POWER_OFF:

        kernel_power_off();

        unlock_kernel();

        do_exit(0);

        break;

 

    case LINUX_REBOOT_CMD_RESTART2:

        if (strncpy_from_user(&buffer[0], arg, sizeof(buffer) - 1) < 0) {

            unlock_kernel();

            return -EFAULT;

        }

        buffer[sizeof(buffer) - 1] = '\0';

 

        printk("in %s:%s:%d\n",__FILE__,__FUNCTION__,__LINE__)  ;

        kernel_restart(buffer);

        break;

#ifdef CONFIG_KEXEC

    case LINUX_REBOOT_CMD_KEXEC:

        ret = kernel_kexec();

        break;

#endif

 

#ifdef CONFIG_HIBERNATION

    case LINUX_REBOOT_CMD_SW_SUSPEND:

        ret = hibernate();

        break;

#endif

 

    default:

        ret = -EINVAL;

        break;

    }

    unlock_kernel();

    return ret;

}

7) kernel/include/linux/reboot.h

/*

 * Magic values required to use _reboot() system call.

 */

 

#define LINUX_REBOOT_MAGIC1 0xfee1dead

#define LINUX_REBOOT_MAGIC2 672274793

#define LINUX_REBOOT_MAGIC2A    85072278

#define LINUX_REBOOT_MAGIC2B    369367448

#define LINUX_REBOOT_MAGIC2C    537993216

 

 

/*

 * Commands accepted by the _reboot() system call.

 *

 * RESTART     Restart system using default command and mode.

 * HALT        Stop OS and give system control to ROM monitor, if any.

 * CAD_ON      Ctrl-Alt-Del sequence causes RESTART command.

 * CAD_OFF     Ctrl-Alt-Del sequence sends SIGINT to init task.

 * POWER_OFF   Stop OS and remove all power from system, if possible.

 * RESTART2    Restart system using given command string.

 * SW_SUSPEND  Suspend system using software suspend if compiled in.

 * KEXEC       Restart system using a previously loaded Linux kernel

 */

 

#define LINUX_REBOOT_CMD_RESTART    0x01234567

#define LINUX_REBOOT_CMD_HALT       0xCDEF0123

#define LINUX_REBOOT_CMD_CAD_ON     0x89ABCDEF

#define LINUX_REBOOT_CMD_CAD_OFF    0x00000000

#define LINUX_REBOOT_CMD_POWER_OFF  0x4321FEDC

#define LINUX_REBOOT_CMD_RESTART2   0xA1B2C3D4

#define LINUX_REBOOT_CMD_SW_SUSPEND 0xD000FCE2

#define LINUX_REBOOT_CMD_KEXEC      0x45584543

8) busybox/init/reboot.h

#include <sys/reboot.h>

 

#ifndef RB_HALT_SYSTEM

# if defined(__linux__)

#  define RB_HALT_SYSTEM  0xcdef0123

#  define RB_ENABLE_CAD   0x89abcdef

#  define RB_DISABLE_CAD  0

#  define RB_POWER_OFF    0x4321fedc

#  define RB_AUTOBOOT     0x01234567

# elif defined(RB_HALT)

#  define RB_HALT_SYSTEM  RB_HALT

# endif

#endif

 

/* Stop system and switch power off if possible.  */

#ifndef RB_POWER_OFF

# if defined(RB_POWERDOWN)

#  define RB_POWER_OFF  RB_POWERDOWN

# elif defined(__linux__)

#  define RB_POWER_OFF  0x4321fedc

# else

#  warning "poweroff unsupported, using halt as fallback"

#  define RB_POWER_OFF  RB_HALT_SYSTEM

# endif

#endif

9) pause_and_low_level_reboot()

busybox/init/init.c

static void pause_and_low_level_reboot(unsigned magic) NORETURN;

static void pause_and_low_level_reboot(unsigned magic)

{

    pid_t pid;

 

    /* Allow time for last message to reach serial console, etc */

    sleep(1);

 

    /* We have to fork here, since the kernel calls do_exit(EXIT_SUCCESS)

     * in linux/kernel/sys.c, which can cause the machine to panic when

     * the init process exits... */

    pid = vfork();

    if (pid == 0) { /* child */

        reboot(magic);

        _exit(EXIT_SUCCESS);

    }    

    while (1)

        sleep(1);

}

static void run_shutdown_and_kill_processes(void)

{

    /* Run everything to be run at "shutdown".  This is done _prior_

     * to killing everything, in case people wish to use scripts to

     * shut things down gracefully... */

    run_actions(SHUTDOWN);

 

    message(L_CONSOLE | L_LOG, "The system is going down NOW!");

 

    /* Send signals to every process _except_ pid 1 */

    kill(-1, SIGTERM);

    message(L_CONSOLE | L_LOG, "Sent SIG%s to all processes", "TERM");

    sync();

    sleep(1);

 

    kill(-1, SIGKILL);

    message(L_CONSOLE, "Sent SIG%s to all processes", "KILL");

    sync();

    /*sleep(1); - callers take care about making a pause */

}

 

/* The SIGPWR/SIGUSR[12]/SIGTERM handler */

static void halt_reboot_pwoff(int sig) NORETURN;

static void halt_reboot_pwoff(int sig)

{

    const char *m;

    unsigned rb;

 

    /* We may call run() and it unmasks signals,

     * including the one masked inside this signal handler.

     * Testcase which would start multiple reboot scripts:

     *  while true; do reboot; done

     * Preventing it:

     */

    reset_sighandlers_and_unblock_sigs();

 

    run_shutdown_and_kill_processes();

 

    m = "halt";

    rb = RB_HALT_SYSTEM;

    if (sig == SIGTERM) {

        m = "reboot";

        rb = RB_AUTOBOOT;

    } else if (sig == SIGUSR2) {

        m = "poweroff";

        rb = RB_POWER_OFF;

    }

    message(L_CONSOLE, "Requesting system %s", m);

    pause_and_low_level_reboot(rb);

    /* not reached */

}

 

 

/* Handler for QUIT - exec "restart" action,

 * else (no such action defined) do nothing */

static void exec_restart_action(void)

{

    struct init_action *a;

 

    for (a = init_action_list; a; a = a->next) {

        if (!(a->action_type & RESTART))

            continue;

 

        /* Starting from here, we won't return.

         * Thus don't need to worry about preserving errno

         * and such.

         */

 

        reset_sighandlers_and_unblock_sigs();

 

        run_shutdown_and_kill_processes();

 

#ifdef RB_ENABLE_CAD

        /* Allow Ctrl-Alt-Del to reboot the system.

         * This is how kernel sets it up for init, we follow suit.

         */

        reboot(RB_ENABLE_CAD); /* misnomer */

#endif

        if (open_stdio_to_tty(a->terminal)) {

            dbg_message(L_CONSOLE, "Trying to re-exec %s", a->command);

            /* Theoretically should be safe.

             * But in practice, kernel bugs may leave

             * unkillable processes, and wait() may block forever.

             * Oh well. Hoping "new" init won't be too surprised

             * by having children it didn't create.

             */

            //while (wait(NULL) > 0)

            //  continue;

            init_exec(a->command);

        }

        /* Open or exec failed */

        pause_and_low_level_reboot(RB_HALT_SYSTEM);

        /* not reached */

    }

}

高通linux-reboot 分析 reboot 分析 1       版本 平台:高通8009 busybox:1.24 linux kernel:3.18.48   2       流程 可以通过reboot、halt、poweroff等命令,对linux操作系统进行控制,具体的操作流程如下:   3       分析 在arm 板上,可知: # ls /sbin/reboot -la lrwxrwx... 阅读详情

相关推荐

Unity开源游戏源码精选:17个亲测可运行教学项目

Unity游戏开发中,掌握真实项目结构与工程实践远比熟记API更重要。本文围绕‘Unity开源项目’和‘游戏源码’两大核心概念,解析高质量开源资源的本质特征——结构清晰、逻辑可溯、修改即时反馈。从基础的MonoBehaviour生命周期组织,到进阶的ScriptableObject数据驱动、事件总线解耦,再到架构级的DOTS ECS设计与网络同步模式,技术价值在于将抽象原理落地为可调试、可验证、可迁移的代码范式。适用于新手建立开发直觉、中级开发者突破系统设计瓶颈,以及团队构建可维护框架。所有项目均基于Uni

weixin_31528001的博客 745

Linux电源管理(3)_Generic PM之Reboot过程

1. 前言 在使用计算机的过程中,关机和重启是最先学会的两个操作。同样,这两个操作在Linux中也存在,称作shutdown和restart。这就是本文要描述的对象。 在Linux Kernel中,主流的shutdown和restart都是通过“reboot”系统调用(具体可参考kernel/sys.c)来实现的,这也是本文使用“Generic PM之Reboot过程”作为标题的原因。另外

蓝精灵的专栏 881

STK12与Python联合仿真(一):环境搭建

STK仿真python接口,安装与测试

qq_42635142的博客 1万+

Linux系统下的重启,关机命令以及reboot挂死问题

会 强制重新开机,不调用shutdown指令的功能,看起来跟普通的重启动作是不同的,或许会发生数据丢失的状况,从描述来看,少做了很多动作。2、保存当前系统状态:系统会将当前系统的状态保存到/var/log/wtmp文件中,包括系统的运行时间、用户登录信息等。而halt实际上是调用shutdown -h now,可以不理会系统当前状态而直接关机,但在有的系统中,halt不会关。runlevel 0: halt 系统停机状态,系统默认运行级别不能设为0,否则不能正常启动。

weixin_44517278的博客 1万+

【可信数据空间-连接器技术架构设计方案】

一句话概括连接器是可信数据空间的“数据保镖”和“外交官”。连接器就是一个部署在你本地的软件代理,它代表你安全地对外提供数据服务,确保在共享数据价值的同时,牢牢守住数据的所有权和控制权。它是实现“数据可用不可见”这一理想的关键技术部件。一个生动的比喻:银行的金库和接待员想象一下,你的数据就是藏在银行金库里的黄金和钞票。金库(你的内部数据库): 绝对安全,外人绝对不能进。接待员(连接器): 坐在银行大厅里,负责与客户打交道。客户向接待员提出请求:“我想取1000元。

u014716614的博客 2291

BUCK电路为何无法实现100%占空比?自举电路原理与替代方案解析

在开关电源设计中,DC-DC转换器是实现电压变换的核心器件,其工作原理基于功率开关管的周期性导通与关断。BUCK(降压)电路作为一种经典拓扑,通过调节开关管的占空比来控制输出电压。然而,其占空比存在理论上限,无法达到100%,这一限制源于高边开关管的驱动需求。为了驱动高边N沟道MOSFET(NMOS),需要栅极电压高于源极电压,而自举(Bootstrap)电路通过利用开关节点电压的跳变,巧妙地生成了这一高压驱动信号。自举电路必须在每个开关周期内存在续流阶段(低边管导通)为电容充电,这从根本上限制了最大占空比

weixin_32239523的博客 317

Linux 系统Trouble shouting及修复FATAL: NO bootale medium found! System halted

Trouble shouting系统修复要从linux系统启动过程入手,之前写过一篇关于linux开机启动过程的详细描述的文章http://blog.csdn.net/avilifans/article/details/12059447,可以参考一下。 开机后,首先是加载bios程序,获取启动顺序,找到第一个启动设备。然后是读取第一个启动设备的mbr扇区信息。 Mbr  正常的情况下看

风花雪月 4239

(2024,DDPM,DDIM,流匹配,SDE,ODE)扩散:基础教程

本文的目标是尽可能简单地教授扩散。第一节介绍扩散的基本原理。第二节和第三节展示如何构建随机和确定性扩散采样器。第四部分介绍了密切相关的流匹配,可看作是扩散的推广。​第五节,强调实践中最重要的一些设计选择,包括采样器、噪声时间表和参数化方法。

qq_44681809的博客 1万+

用好WinSCP,无惧Linux命令

很多人惧怕Linux系统的命令操作模式。实际上对于普通用来说用到命令的概率非常小。 我们在实践过程中发现管理Linux系统,最多使用如下两个工具: WinSCP(必用):可视化界面工具,实现文件管理与命令执行(满足90%的Linux操作)。 Putty(可选):交互式命令才会用到。 在此做一个“武断”的总结:使用Linux就是使用WinSCP这个可视化工具。 WinSCP是一个SFTP+SSH工具,S简单理解为Security、Strong,即更安全、增强的FTP模式。SSH是Linux所采用的.

weixin_42660856的博客 4668

Golang实现企业级AI智能体安全合规自动化检测系统

需求:自动化解析欧盟AI法案、中国网络安全法、美国NIST框架等多国法规,提取具体合规要求并映射到企业技术实现。技术挑战法规文本非结构化,语义复杂,存在大量法律术语与技术术语交叉多语言支持(中文、英文、欧盟24种官方语言)法规动态更新(平均每季度更新2-3次)架构创新性:提出了"规则引擎+AI模型+实时监控"的混合架构,兼顾了合规要求的明确性与智能体行为的动态性。性能突破:通过Golang协程、多级缓存、数据库优化等技术,实现了12,800 req/s的高吞吐量和38ms的低延迟。准确性提升。

shao.bing的专栏 727

HAL STM32+EC11编码器实现增减调节及单击、双击、长按功能

HAL STM32+EC11编码器实现增减调节及单击、双击、长按功能

perseverance51博客 4245

linux reboot执行后,重启不成功,怎么办

不知道哪个程序阻止了重启。

柳鲲鹏 2393

ThingsBoard教程(十六):RPC部件的使用

前言 各位读者好,截止目前,ThingsBoard系列文章已经做了十篇,分别是 ThingsBoard教程(一):ThingBoard介绍及安装 ThingsBoard教程(二):租户,租户配置,部件组模块的使用 ThingsBoard教程(三):系统设置模块的使用 ThingsBoard教程(四):规则链简介与操作 ThingsBoard教程(五):客户,资产管理 ThingsBoard教程(六):设备管理 ThingsBoard教程(七):模拟设备遥测 ThingsBoard教程(八):自定义UI T

知无涯 4591

linux reboot 流程,基于Linux与Busybox的Reboot命令流程分析

一:Busyobx层的分析这段时间,在忙到一个项目时,需要在busybox中用到reboot命令,开始在busybox中的shell中输入reboot命令,始终如下的信息,然后就停止在那里了,无法重启...为了彻底的弄明白这个问题,我在网络上找了很久,终于有个人写的一个reboot流程分析,我就借花献佛.在这里重新分析下busybox是如何运行这个命令,同时又是如何调用到Linux内核中的mach...

weixin_29002209的博客 909

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

BusyBox 版本1.10-2

BusyBox 版本1.10-2 用户在console下输入reboot命令, busybox会调用到halt_main int halt_main(int argc ATTRIBUTE_UNUSED, char **argv) { ..... /* Perform action. */ if (ENABLE_INIT && !(flags & 4)) { if (ENABLE

sunxianchuan123的专栏 797

华为的C语言编程规范.pdf

华为技术有限公司内部技术规范。本规范制定了编写C语言程序的基本原则、规则和建议。从代码的清晰、简洁、可测试、安全、程序效率、可移植各个方面对C语言编程作出了具体指导。

busybox之reboot命令流程分析

busybox初始化注册reboot处理信号 busybox启动的时候,会注册reboot的处理信号 init_main bb_signals(0 + (1 << SIGUSR1) /* halt */ + (1 << SIGTERM) /* reboot */ + (1 << SIGUSR2) /* poweroff */ , ha...

ych的专栏 2936

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

BusyBox reboot 流程分析

用户在console下输入reboot命令, busybox会调用到halt_main   int halt_main(int argc ATTRIBUTE_UNUSED, char **argv) { ..... /* Perform action. */  if (ENABLE_INIT && !(flags & 4)) {   if (ENABLE_FEATURE_INITR

嵌入式与人工智能天地 2361

Linux reboot全过程

嵌入式Linux 下面的reboot命令看似简单,但出问题时定位起来发现别有洞天。 下面就按在shell下执行reboot命令之后程序的执行过程进行解析。 Busybox:1.23.2 ——制作跟文件系统,/sbin/reboot程序的由来 Libc:2.6.1 ——标准C库 Linux kernel:2.6.35 ——内核版本

风之伤 4万+
上一篇: mybatis sql语句中的foreach标签
下一篇: sql只修改第一二行数据
weixin_34038293
博客等级 码龄11年 5720粉丝 1233原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值