Subject: M_WAITOK and M_NOWAIT
To: None <>
From: Hitoshi Asaeda <>
List: tech-kern
Date: 02/08/2002 11:56:48
Could you tell me about the differences between M_WAITOK and M_NOWAIT?

# Following question is based on last week -current kernel code.

man 9 malloc says malloc(9) with M_WAITOK doesn't return NULL.
In fact, there is some comment in kern_malloc.c, like;
	Kmem_malloc() can return NULL, even if it can wait,
	if there is no map space avaiable, because it can't
	fix that problem.
However, next to this comment, it seems that malloc using M_WAITOK may
return panic(9), not NULL, if some memory allocation error is occured.

Now, I tell my questions.

1. Is it never happened malloc(9) with M_WAITOK returns NULL?

Let's see the following sample. We make;
	foo = (struct foo *)malloc(sizeof(*foo), M_xxx, M_WAITOK);
After this, we don't need to check "foo == NULL" as below?
	if (foo == NULL)
		return ENOBUFS;
Actually, I find several cases which check or don't check,
"foo ==	NULL", in a code under /sys/netinet and /sys/netinet6.

2. (If you know) How about another BSD?
(I think their behavior is same for this condition.)

3. Are there any precise rules how to use M_WAITOK/M_NOWAIT?

Followings are correct sentences?

o. We should not (or must not) use M_WAITOK within a part set some
interrupt level, like splvm().
In this case, we should (or must) use M_NOWAIT.

o. We can use either one if no interrupt level is set on the function.

How about followings?

o. It's almost sure that malloc with M_WAITOK can successfully
allocate required memory space. *If* it causes error, panic is called,
but we accept this.

o. After all, M_NOWAIT never panic (really?). So we can use this in
every place as long as we check (foo == NULL).

Hitoshi Asaeda