Subject: Re: Many thanks and a new question...
To: Joshua Dinerstein <forge@netbsd.warped.com>
From: Jeremy Cooper <jeremy@broder.com>
List: tech-kern
Date: 07/21/1997 16:06:57
On Mon, 21 Jul 1997, Joshua Dinerstein wrote:

> > > [ Use malloc() or stack for large variables/buffers? ]
> >
> > [ Use malloc(). ]
>
> 	1- There appear to be 2 malloc functions in the kernel: MALLOC and 
> malloc. These 2 functions are taking quite a different set of arguments. 
>
> 	2- What is the MALLOC function for? (Specifically) And when 
> should it be used over the malloc function.
> 
> 	3- Vice versa for the malloc function. When should it be used instead 
> of MALLOC. The MALLOC allows you to set the "type" of memory to be allocated.

The "type" and "flag" arguments to malloc() serve two purposes.  The
"type" argument is really more like a "purpose" argument.   It helps
the VM statistics gathering functions keep track of the amount of memory
currently allocated for a specific use.  Check sys/malloc.h for a type
that is appropriate to your usage.

The "flags" argument is a way to state the urgency of the operation.
The only two flags that I know of are M_NOWAIT and M_WAITOK.  The M_NOWAIT
flag informs the kernel that you are not willing to block or sleep for the
memory - M_WAITOK implies the opposite.  M_NOWAIT is typically used in
code that has no associated process context, such as inside an interrupt
handler, while M_WAITOK is used everywhere else.

Finally, MALLOC() is a macro that calls malloc().  You use it to reduce
the amount of typing needed to make a proper call to malloc(), and to help
improve memory diagnostics when you compile a kernel with the DIAGNOSTIC
option.  The following two code fragments are the same.

  int *myints;
  MALLOC(myints, int *, sizeof(int) * 1024, M_DEVBUF, M_WAITOK);   

  int *myints;
  myints = (int *) malloc((u_long) sizeof(int) * 1024, M_DEVBUF, M_WAITOK);

-J