• linux驱动38:后备高速缓存


    设备驱动程序常常会反复地分配同一大小的内存块,为这些反复使用的内存块增加某些特殊的内存池——后备高速缓存。

    linux内核的高速缓存管理称为slab分配器,头文件,类型struct kmem_cache。

    一、api接口:

    1、创建高速缓存对象

    struct kmem_cache *kmem_cache_create(const char *name, size_t size, size_t offset, unsigned long flags, void (*constructor)(void *));

    name:名称

    size:内存块大小

    offset:页面第一个对象的偏移量,通常为0

    flags:控制如何分配

    constructor:可选,初始化内存块函数,会多次调用(一个内存块调用一次)

    2、分配内存对象

    void *kmem_cache_alloc(struct kmem_cache *cache, gfp_t flags);

    参数flags和传递给kmalloc的相同

    3、释放内存对象

    void kmem_cache_free(struct kmem_cache *cache,  void *mem_obj);

    4、释放高速缓存

    void kmem_cache_destroy(struct kmem_cache *cache);

    二、demo

    1. #include
    2. #include
    3. #include
    4. #include
    5. typedef struct
    6. {
    7. int num;
    8. char str[32];
    9. }TEST_S;
    10. static struct kmem_cache *pKmemCache = NULL;
    11. static int cacheCnt = 0;
    12. void constructor(void *args)
    13. {
    14. //printk("constructor. \n");
    15. TEST_S *test = (TEST_S *)args;
    16. test->num = 7;
    17. memset(test->str, 0x0, 32);
    18. cacheCnt++;
    19. }
    20. static int __init hello_init(void)
    21. {
    22. printk("hello_init. \n");
    23. pKmemCache = kmem_cache_create("test", sizeof(TEST_S), 0, SLAB_HWCACHE_ALIGN, constructor);
    24. if (!pKmemCache)
    25. {
    26. printk("kmem_cache_create failed. \n");
    27. return -ENOMEM;
    28. }
    29. void *p = kmem_cache_alloc(pKmemCache, GFP_KERNEL);
    30. if (!p)
    31. {
    32. printk("kmem_cache_alloc failed. \n");
    33. return -1;
    34. }
    35. TEST_S *test = (TEST_S *)p;
    36. printk("num:%d\n", test->num);
    37. printk("cacheCnt:%d\n", cacheCnt);
    38. kmem_cache_free(pKmemCache, p);
    39. return 0;
    40. }
    41. static void __exit hello_exit(void)
    42. {
    43. printk("hello_exit. \n");
    44. if (pKmemCache)
    45. {
    46. kmem_cache_destroy(pKmemCache);
    47. pKmemCache = NULL;
    48. }
    49. }
    50. MODULE_LICENSE("GPL");
    51. module_init(hello_init);
    52. module_exit(hello_exit);

  • 相关阅读:
    RocketMQ 消息负载均衡策略解析——图解、源码级解析
    Java final关键字具有什么功能呢?
    ESD器件对高速信号有什么影响吗
    2.Seq2Seq注意力机制
    leetcode - 2707. Extra Characters in a String
    Go Error 错误处理总结
    【已解决】Vue3+Element-plus中icon图标不显示的问题
    Nginx 前端 安装,打包,发布项目到服务 流程
    串口通信之计算校验和
    计算机网络的性能指标
  • 原文地址:https://blog.csdn.net/dongyoubin/article/details/127712534