0

I am trying to understanding devm_kzalloc() function implementation. It is allocating more than the requested memory(sizeof(struct devres) + size) to manage resources.

struct devres is defined as follows, the second member is an incomplete array.

struct devres {
        struct devres_node              node;
        /* -- 3 pointers */
        unsigned long long              data[]; /* guarantee ull alignment */
};

Following is the source to allocate memory.

    size_t tot_size = sizeof(struct devres) + size;
    struct devres *dr;

    dr = kmalloc_track_caller(tot_size, gfp);
    if (unlikely(!dr))
            return NULL;

    memset(dr, 0, tot_size);
    INIT_LIST_HEAD(&dr->node.entry);
    dr->node.release = release;
    return dr; 

I have following doubhts. . It is caliculating the tot_size, but in struct devres the array is imcomplete. . The devm_kzalloc() function(shown below) is returning dr->data as the starting of the requested memory. If we understand that array name contains the startig address of that array then we are allocating more than the requested memory. i.e size of unsigned long long + size.

void * devm_kzalloc(struct device *dev, size_t size, gfp_t gfp)
{
    struct devres *dr;

    /* use raw alloc_dr for kmalloc caller tracing */
    dr = alloc_dr(devm_kzalloc_release, size, gfp);
    if (unlikely(!dr))
            return NULL;

    set_node_dbginfo(&dr->node, "devm_kzalloc_release", size);
    devres_add(dev, dr->data);
    return dr->data;
}

Could you please help me to understand this.

TheCodeArtist
  • 21,479
  • 4
  • 69
  • 130
user3693586
  • 1,227
  • 5
  • 18
  • 40
  • 1
    It's not clear what you are asking. Do you not understand how flexible array members AKA struct hacks work? – Andrew C Oct 19 '14 at 03:41
  • what is the use of unsigned long long data[] in the resource allocation.How it can be used as a starting address of requested memory. – user3693586 Oct 19 '14 at 03:44
  • That's a "flexible array member" or "struct hack". Just search on either time and you'll find all kinds of stuff – Andrew C Oct 19 '14 at 03:46
  • Memory will not be allocated for flexible array member? – user3693586 Oct 19 '14 at 03:50
  • 1
    that's what the extra size parameter is for – Andrew C Oct 19 '14 at 03:51
  • I am sorry, could not understand clearly. extra memory will be allocated than the required. – user3693586 Oct 19 '14 at 03:55
  • Not an exact duplicate; Please go through the answers to [**this question**](http://stackoverflow.com/q/20221012/319204) to understand how the **incomplete/flexible array member in a struct** is meant to be used.. – TheCodeArtist Oct 19 '14 at 08:02

1 Answers1

0

Thanks

I have understood now.

Its flexible array member feature of C99 used in "struct devres" structure definition.

user3693586
  • 1,227
  • 5
  • 18
  • 40