Re: Kalloc and lck_mtx_lock
Re: Kalloc and lck_mtx_lock
- Subject: Re: Kalloc and lck_mtx_lock
- From: Quinn <email@hidden>
- Date: Wed, 24 Jun 2009 12:04:39 +0100
At 23:13 -0400 23/6/09, Greg wrote:
Hmm.. my apologies, I am admittedly a little bit deficient in my
understandings of the internals of the kernel, but I'm not sure as
to what you mean by this:
as you really don't have a good way of knowing whether your service
will ultimately be depended on by code that has to run to free
memory in order for the allocation to succeed.
OK, let's consider a concrete example. It's very common for folks
asking this question to be building KEXTs that run on the page fault
path. In that case allocating memory while holding a mutex can
easily deadlock the system. Your allocation blocks waiting for
memory. The pager blocks waiting for your service. Deadlock.
This obvious affects any KEXTs associated with the disk (VFS plug-ins
and I/O Storage Family stuff), but it can also affect network KEXTs
as well (because we support paging over the network). That doesn't
leave a lot of KEXTs that are safe from this one specific edge case.
And there are many more edge cases out there (-:
Unfortunately it would be extremely difficult (perhaps impossible),
and totally out of line with KISS, for me to avoid allocating while
holding a lock.
The kernel is not really a KISS-compliant environment. Sometimes you
have to jump through hoops to achieve correctness. If you have any
doubt about this, check out the HNode layer I created for VFS
plug-ins.
<http://developer.apple.com/SampleCode/MFSLives/listing2.html>
<http://developer.apple.com/SampleCode/MFSLives/listing1.html>
This design pattern is very common in kernel code: do lots of work,
then discover that you need memory, so abandon all that work, drop
all your locks, allocate the memory, and then redo all of that work.
There tends to be lots of gotos in kernel code (-:
One other question if I may, is it then better to call one of the
malloc functions (while holding a lock) in non-blocking way (i.e.
OSMalloc_noblock), or does it not matter?
Notwithstanding our general recommendation not to do this,
non-blocking is definitely better than blocking.
And if it does matter (and OSMalloc_noblock/kalloc_noblock is
better), then should I take much greater caution to check for it
returning NULL than if I were to use plain old OSMalloc?
Yes.
Which raises an interesting point. If you can handle the allocator
returning NULL, why not just write the code correctly in the first
place?
S+E
--
Quinn "The Eskimo!" <http://www.apple.com/developer/>
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Darwin-kernel mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden