Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 316 lines (257 sloc) 10.854 kB
dc5be1c Initial check-in.
uli authored
1 //
2 // UKVirtualRingBuffer.m
3 // PlayBufferedSoundFile
4 //
5 /*
6 Copyright (c) 2002, Kurt Revis. All rights reserved.
7
8 Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
9
10 * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
11 * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
12 * Neither the name of Snoize nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
13
14 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
15 */
16
17
18 #import "UKVirtualRingBuffer.h"
19
20 #include <mach/mach.h>
21 #include <mach/mach_error.h>
22
23
24 @implementation UKVirtualRingBuffer
25
26 static void *allocateVirtualBuffer(UInt32 bufferLength);
27 static void deallocateVirtualBuffer(void *buffer, UInt32 bufferLength);
28
29
30 - (id)initWithLength:(UInt32)length
31 {
32 if (![super init])
33 return nil;
34
35 // We need to allocate entire VM pages, so round the specified length up to the next page if necessary.
36 bufferLength = round_page(length);
37
38 buffer = allocateVirtualBuffer(bufferLength);
39 if (buffer) {
40 bufferEnd = buffer + bufferLength;
41 } else {
42 [self release];
43 return nil;
44 }
45
46 readPointer = NULL;
47 writePointer = NULL;
48
49 return self;
50 }
51
52 - (void)dealloc
53 {
54 if (buffer)
55 deallocateVirtualBuffer(buffer, bufferLength);
56
57 [super dealloc];
58 }
59
60 - (void)empty
61 {
62 // Assumption:
63 // No one is reading or writing from the buffer, in any thread, when this method is called.
64
65 readPointer = NULL;
66 writePointer = NULL;
67 }
68
69 - (BOOL)isEmpty
70 {
71 return (readPointer != NULL && writePointer != NULL);
72 }
73
74
75 //
76 // Theory of operation:
77 //
78 // This class keeps a pointer to the next byte to be read (readPointer) and a pointer to the next byte to be written (writePointer).
79 // readPointer is only advanced in the reading thread (except for one case: when the buffer first has data written to it).
80 // writePointer is only advanced in the writing thread.
81 //
82 // Since loading and storing word length data is atomic, each pointer can safely be modified in one thread while the other thread
83 // uses it, IF each thread is careful to make a local copy of the "opposite" pointer when necessary.
84 //
85
86 //
87 // Read operations
88 //
89
90 - (UInt32)lengthAvailableToReadReturningPointer:(void **)returnedReadPointer
91 {
92 // Assumptions:
93 // returnedReadPointer != NULL
94
95 UInt32 length;
96 // Read this pointer exactly once, so we're safe in case it is changed in another thread
97 void *localWritePointer = writePointer;
98
99 // Depending on out-of-order execution and memory storage, either one of these may be NULL when the buffer is empty. So we must check both.
100 if (!readPointer || !localWritePointer) {
101 // The buffer is empty
102 length = 0;
103 } else if (localWritePointer > readPointer) {
104 // Write is ahead of read in the buffer
105 length = localWritePointer - readPointer;
106 } else {
107 // Write has wrapped around past read, OR write == read (the buffer is full)
108 length = bufferLength - (readPointer - localWritePointer);
109 }
110
111 *returnedReadPointer = readPointer;
112 return length;
113 }
114
115 - (void)didReadLength:(UInt32)length
116 {
117 // Assumptions:
118 // [self lengthAvailableToReadReturningPointer:] currently returns a value >= length
119 // length > 0
120
121 void *newReadPointer;
122
123 newReadPointer = readPointer + length;
124 if (newReadPointer >= bufferEnd)
125 newReadPointer -= bufferLength;
126
127 if (newReadPointer == writePointer) {
128 // We just read the last data out of the buffer, so it is now empty.
129 newReadPointer = NULL;
130 }
131
132 // Store the new read pointer. This is the only place this happens in the read thread.
133 readPointer = newReadPointer;
134 }
135
136
137 //
138 // Write operations
139 //
140
141 - (UInt32)lengthAvailableToWriteReturningPointer:(void **)returnedWritePointer
142 {
143 // Assumptions:
144 // returnedWritePointer != NULL
145
146 UInt32 length;
147 // Read this pointer exactly once, so we're safe in case it is changed in another thread
148 void *localReadPointer = readPointer;
149
150 // Either one of these may be NULL when the buffer is empty. So we must check both.
151 if (!localReadPointer || !writePointer) {
152 // The buffer is empty. Set it up to be written into.
153 // This is one of the two places the write pointer can change; both are in the write thread.
154 writePointer = buffer;
155 length = bufferLength;
156 } else if (writePointer <= localReadPointer) {
157 // Write is before read in the buffer, OR write == read (meaning that the buffer is full).
158 length = localReadPointer - writePointer;
159 } else {
160 // Write is behind read in the buffer. The available space wraps around.
161 length = (bufferEnd - writePointer) + (localReadPointer - buffer);
162 }
163
164 *returnedWritePointer = writePointer;
165 return length;
166 }
167
168 - (void)didWriteLength:(UInt32)length
169 {
170 // Assumptions:
171 // [self lengthAvailableToWriteReturningPointer:] currently returns a value >= length
172 // length > 0
173
174 void *oldWritePointer = writePointer;
175 void *newWritePointer;
176
177 // Advance the write pointer, wrapping around if necessary.
178 newWritePointer = writePointer + length;
179 if (newWritePointer >= bufferEnd)
180 newWritePointer -= bufferLength;
181
182 // This is one of the two places the write pointer can change; both are in the write thread.
183 writePointer = newWritePointer;
184
185 // Also, if the read pointer is NULL, then we just wrote into a previously empty buffer, so set the read pointer.
186 // This is the only place the read pointer is changed in the write thread.
187 // The read thread should never change the read pointer when it is NULL, so this is safe.
188 if (!readPointer)
189 readPointer = oldWritePointer;
190 }
191
192 @end
193
194
195 void *allocateVirtualBuffer(UInt32 bufferLength)
196 {
197 kern_return_t error;
198 vm_address_t originalAddress = NULL;
199 vm_address_t realAddress = NULL;
200 mach_port_t memoryEntry;
201 vm_size_t memoryEntryLength;
202 vm_address_t virtualAddress = NULL;
203
204 // We want to find where we can get 2 * bufferLength bytes of contiguous address space.
205 // So let's just allocate that space, remember its address, and deallocate it.
206 // (This doesn't actually have to touch all of that memory so it's not terribly expensive.)
207 error = vm_allocate(mach_task_self(), &originalAddress, 2 * bufferLength, TRUE);
208 if (error) {
209 #if DEBUG
210 mach_error("vm_allocate initial chunk", error);
211 #endif
212 return NULL;
213 }
214
215 error = vm_deallocate(mach_task_self(), originalAddress, 2 * bufferLength);
216 if (error) {
217 #if DEBUG
218 mach_error("vm_deallocate initial chunk", error);
219 #endif
220 return NULL;
221 }
222
223 // Then allocate a "real" block of memory at the same address, but with the normal bufferLength.
224 realAddress = originalAddress;
225 error = vm_allocate(mach_task_self(), &realAddress, bufferLength, FALSE);
226 if (error) {
227 #if DEBUG
228 mach_error("vm_allocate real chunk", error);
229 #endif
230 return NULL;
231 }
232 if (realAddress != originalAddress) {
233 #if DEBUG
234 NSLog(@"allocateVirtualBuffer: vm_allocate 2nd time didn't return same address (%p vs %p)", originalAddress, realAddress);
235 #endif
236 goto errorReturn;
237 }
238
239 // Then make a memory entry for the area we just allocated.
240 memoryEntryLength = bufferLength;
241 error = mach_make_memory_entry(mach_task_self(), &memoryEntryLength, realAddress, VM_PROT_READ | VM_PROT_WRITE, &memoryEntry, NULL);
242 if (error) {
243 #if DEBUG
244 mach_error("mach_make_memory_entry", error);
245 #endif
246 goto errorReturn;
247 }
248 if (!memoryEntry) {
249 #if DEBUG
250 NSLog(@"mach_make_memory_entry: returned memoryEntry of NULL");
251 #endif
252 goto errorReturn;
253 }
254 if (memoryEntryLength != bufferLength) {
255 #if DEBUG
256 NSLog(@"mach_make_memory_entry: size changed (from %0x to %0x)", bufferLength, memoryEntryLength);
257 #endif
258 goto errorReturn;
259 }
260
261 // And map the area immediately after the first block, with length bufferLength, to that memory entry.
262 virtualAddress = realAddress + bufferLength;
263 error = vm_map(mach_task_self(), &virtualAddress, bufferLength, 0, FALSE, memoryEntry, 0, FALSE, VM_PROT_READ | VM_PROT_WRITE, VM_PROT_READ | VM_PROT_WRITE, VM_INHERIT_DEFAULT);
264 if (error) {
265 #if DEBUG
266 mach_error("vm_map", error);
267 #endif
268 // TODO Retry from the beginning, instead of failing completely. There is a tiny (but > 0) probability that someone
269 // will allocate this space out from under us.
270 virtualAddress = NULL;
271 goto errorReturn;
272 }
273 if (virtualAddress != realAddress + bufferLength) {
274 #if DEBUG
275 NSLog(@"vm_map: didn't return correct address (%p vs %p)", realAddress + bufferLength, virtualAddress);
276 #endif
277 goto errorReturn;
278 }
279
280 // Success!
281 return (void *)realAddress;
282
283 #if DEBUG
284 // Here's a little test...
285 *realAddress = '?';
286 if (*virtualAddress != '?')
287 NSLog(@"UKVirtualRingBuffer: Test 1: vm magic failed");
288
289 *(virtualAddress + 1) = '!';
290 if (*(realAddress + 1) != '!')
291 NSLog(@"UKVirtualRingBuffer: Test 2: vm magic failed");
292 #endif
293
294 errorReturn:
295 if (realAddress)
296 vm_deallocate(mach_task_self(), realAddress, bufferLength);
297 if (virtualAddress)
298 vm_deallocate(mach_task_self(), virtualAddress, bufferLength);
299
300 return NULL;
301 }
302
303 void deallocateVirtualBuffer(void *buffer, UInt32 bufferLength)
304 {
305 kern_return_t error;
306
307 // We can conveniently deallocate both the vm_allocated memory and
308 // the vm_mapped region at the same time.
309 error = vm_deallocate(mach_task_self(), (vm_address_t)buffer, bufferLength * 2);
310 if (error) {
311 #if DEBUG
312 mach_error("vm_deallocate in dealloc", error);
313 #endif
314 }
315 }
Something went wrong with that request. Please try again.