···11Using flexible arrays in the kernel22-Last updated for 2.6.3122+Last updated for 2.6.3233Jonathan Corbet <corbet@lwn.net>4455Large contiguous memory allocations can be unreliable in the Linux kernel.···4040the current code, using flags to ask for high memory is likely to lead to4141notably unpleasant side effects.42424343+It is also possible to define flexible arrays at compile time with:4444+4545+ DEFINE_FLEX_ARRAY(name, element_size, total);4646+4747+This macro will result in a definition of an array with the given name; the4848+element size and total will be checked for validity at compile time.4949+4350Storing data into a flexible array is accomplished with a call to:44514552 int flex_array_put(struct flex_array *array, unsigned int element_nr,···8376Note that it is possible to get back a valid pointer for an element which8477has never been stored in the array. Memory for array elements is allocated8578one page at a time; a single allocation could provide memory for several8686-adjacent elements. The flexible array code does not know if a specific8787-element has been written; it only knows if the associated memory is8888-present. So a flex_array_get() call on an element which was never stored8989-in the array has the potential to return a pointer to random data. If the9090-caller does not have a separate way to know which elements were actually9191-stored, it might be wise, at least, to add GFP_ZERO to the flags argument9292-to ensure that all elements are zeroed.7979+adjacent elements. Flexible array elements are normally initialized to the8080+value FLEX_ARRAY_FREE (defined as 0x6c in <linux/poison.h>), so errors8181+involving that number probably result from use of unstored array entries.8282+Note that, if array elements are allocated with __GFP_ZERO, they will be8383+initialized to zero and this poisoning will not happen.93849494-There is no way to remove a single element from the array. It is possible,9595-though, to remove all elements with a call to:8585+Individual elements in the array can be cleared with:8686+8787+ int flex_array_clear(struct flex_array *array, unsigned int element_nr);8888+8989+This function will set the given element to FLEX_ARRAY_FREE and return9090+zero. If storage for the indicated element is not allocated for the array,9191+flex_array_clear() will return -EINVAL instead. Note that clearing an9292+element does not release the storage associated with it; to reduce the9393+allocated size of an array, call:9494+9595+ int flex_array_shrink(struct flex_array *array);9696+9797+The return value will be the number of pages of memory actually freed.9898+This function works by scanning the array for pages containing nothing but9999+FLEX_ARRAY_FREE bytes, so (1) it can be expensive, and (2) it will not work100100+if the array's pages are allocated with __GFP_ZERO.101101+102102+It is possible to remove all elements of an array with a call to:9610397104 void flex_array_free_parts(struct flex_array *array);98105