What is the difference between devm_kzalloc() and kzalloc() in linux driver programming

前端 未结 2 1618
星月不相逢
星月不相逢 2020-12-28 17:01

I have found devm_kzalloc() and kzalloc() in device driver programmong. But I don\'t know when/where to use these functions. Can anyone please spec

2条回答
  •  無奈伤痛
    2020-12-28 17:19

    In simple words devm_kzalloc() and kzalloc() both are used for memory allocation in device driver but the difference is if you allocate memory by kzalloc() than you have to free that memory when the life cycle of that device driver is ended or when it is unloaded from kernel but if you do the same with devm_kzalloc() you need not to worry about freeing memory,that memory is freed automatically by device library itself.

    Both of them does the exactly the same thing but by using devm_kzalloc little overhead of freeing memory is released from programmers

    Let explain you by giving example, first example by using kzalloc

    static int pxa3xx_u2d_probe(struct platform_device *pdev)
    {
        int err;
        u2d = kzalloc(sizeof(struct pxa3xx_u2d_ulpi), GFP_KERNEL);     1
        if (!u2d)
             return -ENOMEM;
        u2d->clk = clk_get(&pdev->dev, NULL);
        if (IS_ERR(u2d->clk)) {
            err = PTR_ERR(u2d->clk);                                    2
            goto err_free_mem;
        }
    ...
        return 0;
    err_free_mem:
        kfree(u2d);
        return err;
    }
    static int pxa3xx_u2d_remove(struct platform_device *pdev)
    {
        clk_put(u2d->clk);               
        kfree(u2d);                                                     3
        return 0;
    }
    

    In this example you can this in funtion pxa3xx_u2d_remove(), kfree(u2d)(line indicated by 3) is there to free memory allocated by u2d now see the same code by using devm_kzalloc()

    static int pxa3xx_u2d_probe(struct platform_device *pdev)
    {
        int err;
        u2d = devm_kzalloc(&pdev->dev, sizeof(struct pxa3xx_u2d_ulpi), GFP_KERNEL);
        if (!u2d)
            return -ENOMEM;
        u2d->clk = clk_get(&pdev->dev, NULL);
        if (IS_ERR(u2d->clk)) {
             err = PTR_ERR(u2d->clk);
             goto err_free_mem;
        }
    ...
        return 0;
    err_free_mem:
        return err;
    }
    static int pxa3xx_u2d_remove(struct platform_device *pdev)
    {
        clk_put(u2d->clk);
        return 0;
    }
    

    there is no kfree() to free function because the same is done by devm_kzalloc()

提交回复
热议问题