Bootstrap

主机hung(夯死)模拟

本文所提出的主机夯死模拟的逻辑如下:

旨在模拟“CPU软锁定”(soft lock)情况,导致系统中的CPU被持续占用而无法进行其他任务处理。具体来说,它创建多个线程,周期性地执行一些CPU占用操作,以模拟CPU软锁的影响。

核心代码如下:

int softlock_thread_func(void *data)
{
    struct softlock_thread_data *thread_data = data;

    printk("Thread %d: Starting to block CPU\n", thread_data->id);
    while (!kthread_should_stop()) {
        cpu_relax();  // 占用 CPU
        mdelay(delay_ms);
        printk("Thread %d: Blocking CPU\n", thread_data->id);
    }

    kfree(thread_data);
    printk("Thread %d: Exiting\n", thread_data->id);
    return 0;
}
static int __init softlock_init(void)
{
    int i;
    num_threads = num_online_cpus();  // 动态设置线程数为CPU核心数的1.5倍
    delay_ms = (get_num_physpages() / (1024 * 1024)) * 10; // 动态设置延迟时间,基于系统内存情况

    printk("softlock module loaded\n");
    printk("Number of threads: %d\n", num_threads);
    printk("Delay per thread (ms): %d\n", delay_ms);

    softlock_threads = kmalloc(num_threads * sizeof(struct task_struct *), GFP_KERNEL);
    if (!softlock_threads) {
        printk("Failed to allocate memory for threads\n");
        return -ENOMEM;
    }

    for (i = 0; i < num_threads; i++) {
        struct softlock_thread_data *data = kmalloc(sizeof(struct softlock_thread_data), GFP_KERNEL);
        if (!data) {
            printk("Failed to allocate memory for thread data %d\n", i);
            continue;
        }

        data->id = i;
        softlock_threads[i] = kthread_create(softlock_thread_func, data, "softlock_thread%d", i);
        if (IS_ERR(softlock_threads[i])) {
            printk("Failed to create thread %d\n", i);
            kfree(data);
            continue;
        }

        kthread_bind(softlock_threads[i], i % num_possible_cpus());
        wake_up_process(softlock_threads[i]);
    }

    return 0;
}
;