前几天写的一个demo,没几行代码,但是涵盖的东西比较多:
撰写模块,创建内核线程,节点及cpu亲缘性设置,内核态获取时间,内核态分配大内存,时间处理等等...
已备后用。
-
#include <linux/module.h>
-
#include <linux/init.h>
-
#include <linux/kernel.h>
-
#include <linux/jiffies.h>
-
#include <linux/sched.h>
-
#include <linux/kthread.h>
-
-
MODULE_LICENSE("GPL");
-
MODULE_AUTHOR("Gu Zheng ");
-
-
#define COUNT 5*1024*1024
-
#define SIZE 4*1024
-
-
void *addrs[COUNT];
-
-
static int mem_alloc(void)
-
{
-
int i = 0;
-
while (i < COUNT) {
-
addrs[i] = vmalloc_node(SIZE, 1);
-
if (addrs[i] == NULL)
-
break;
-
i++;
-
}
-
return i;
-
}
-
-
static void write_node1_mem(void)
-
{
-
int i = 0;
-
while (i < COUNT) {
-
memset(addrs[i], 1, SIZE);
-
i++;
-
}
-
}
-
-
static void mem_free(void)
-
{
-
int i = 0;
-
while (i < COUNT) {
-
vfree(addrs[i]);
-
i++;
-
}
-
}
-
-
static struct timeval timeval_sub(struct timeval lhs, struct timeval rhs)
-
{
-
struct timeval tv_delta;
-
__kernel_time_t sec = lhs.tv_sec - rhs.tv_sec;
-
__kernel_suseconds_t usec = lhs.tv_usec - rhs.tv_usec;
-
if (usec < 0) {
-
usec += USEC_PER_SEC;
-
--sec;
-
}
-
tv_delta.tv_sec = sec;
-
tv_delta.tv_usec = usec;
-
return tv_delta;
-
}
-
-
static int test_func(void *data)
-
{
-
unsigned long jiff_1, jiff_2;
-
struct timeval time_start, time_end, time_cost;
-
int count = 0;
-
-
jiff_1 = (unsigned long)jiffies;
-
do_gettimeofday(&time_start);
-
count = mem_alloc();
-
do_gettimeofday(&time_end);
-
jiff_2 = (unsigned long)jiffies;
-
printk("==========alloc cost time=========n");
-
time_cost = timeval_sub(time_end, time_start);
-
printk("==========jiffies: %ld=======n", jiff_2 - jiff_1);
-
printk("==========%ld seconds, %ld micro-seconds====n",
-
time_cost.tv_sec, time_cost.tv_usec);
-
if (count != COUNT) {
-
printk("====vzalloc failed!====n");
-
return -1;
-
}
-
memset(&time_start, 0, sizeof(struct timeval));
-
memset(&time_end, 0, sizeof(struct timeval));
-
memset(&time_cost, 0, sizeof(struct timeval));
-
-
jiff_1 = (unsigned long)jiffies;
-
do_gettimeofday(&time_start);
-
write_node1_mem();
-
do_gettimeofday(&time_end);
-
jiff_2 = (unsigned long)jiffies;
-
printk("==========write cost time=========n");
-
time_cost = timeval_sub(time_end, time_start);
-
printk("==========jiffies: %ld=======n", jiff_2 - jiff_1);
-
printk("==========%ld seconds, %ld micro-seconds====n",
-
time_cost.tv_sec, time_cost.tv_usec);
-
do_exit(0);
-
}
-
-
static int __init mem_test_mod_init(void)
-
{
-
struct task_struct *my_task = NULL;
-
my_task = kthread_create_on_node(test_func, NULL, 1, "mem_test_deamon");
-
if (IS_ERR(my_task))
-
printk("====Create kthread failed!=====n");
-
kthread_bind(my_task, 25);
-
wake_up_process(my_task);
-
return 0;
-
}
-
-
static void __exit mem_test_mod_exit(void)
-
{
-
mem_free();
-
}
-
-
module_init(mem_test_mod_init);
-
module_exit(mem_test_mod_exit);
阅读(1423) | 评论(0) | 转发(0) |