OSX 10.6 x86_64 fixes for configure and libusb; Audio is next
[debian/gnuradio] / usrp / host / lib / fusb_darwin.cc
1 /* -*- c++ -*- */
2 /*
3  * Copyright 2006 Free Software Foundation, Inc.
4  * 
5  * This file is part of GNU Radio.
6  *
7  * GNU Radio is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 3, or (at your option)
10  * any later version.
11  * 
12  * GNU Radio is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with GNU Radio; see the file COPYING.  If not, write to
19  * the Free Software Foundation, Inc., 51 Franklin Street,
20  * Boston, MA 02110-1301, USA.
21  */
22
23 #ifdef HAVE_CONFIG_H
24 #include "config.h"
25 #endif
26
27 // tell mld_threads to NOT use omni_threads,
28 // but rather Darwin's pthreads
29 #define _USE_OMNI_THREADS_
30 #define DO_DEBUG 0
31
32 #include <usb.h>
33 #include "fusb.h"
34 #include "fusb_darwin.h"
35 #include "darwin_libusb.h"
36 #include <iostream>
37
38 static const int USB_TIMEOUT = 100;     // in milliseconds
39 static const UInt8 NUM_QUEUE_ITEMS = 20;
40
41 fusb_devhandle_darwin::fusb_devhandle_darwin (usb_dev_handle* udh)
42   : fusb_devhandle (udh)
43 {
44   // that's it
45 }
46
47 fusb_devhandle_darwin::~fusb_devhandle_darwin ()
48 {
49   // nop
50 }
51
52 fusb_ephandle*
53 fusb_devhandle_darwin::make_ephandle (int endpoint, bool input_p,
54                                       int block_size, int nblocks)
55 {
56   return new fusb_ephandle_darwin (this, endpoint, input_p,
57                                    block_size, nblocks);
58 }
59
60 // ----------------------------------------------------------------
61
62 fusb_ephandle_darwin::fusb_ephandle_darwin (fusb_devhandle_darwin* dh,
63                                             int endpoint, bool input_p,
64                                             int block_size, int nblocks)
65   : fusb_ephandle (endpoint, input_p, block_size, nblocks),
66     d_devhandle (dh), d_pipeRef (0), d_transferType (0),
67     d_interfaceRef (0),  d_interface (0), d_queue (0),
68     d_buffer (0), d_bufLenBytes (0)
69 {
70   d_bufLenBytes = fusb_sysconfig::max_block_size();
71
72 // create circular buffer
73   d_buffer = new circular_buffer<char> (NUM_QUEUE_ITEMS * d_bufLenBytes,
74                                         !d_input_p, d_input_p);
75
76 // create the queue
77   d_queue = new circular_linked_list <s_buffer_ptr> (NUM_QUEUE_ITEMS);
78   d_queue->iterate_start ();
79   s_node_ptr l_node = d_queue->iterate_next ();
80   while (l_node) {
81     l_node->both (new s_both<s_buffer_ptr> (l_node, this));
82     s_buffer_ptr l_buf = new s_buffer (d_bufLenBytes);
83     l_node->object (l_buf);
84     l_node = d_queue->iterate_next ();
85     l_buf = NULL;
86   }
87
88   d_readRunning = new mld_mutex ();
89   d_runThreadRunning = new mld_mutex ();
90   d_runBlock = new mld_condition ();
91   d_readBlock = new mld_condition ();
92 }
93
94 fusb_ephandle_darwin::~fusb_ephandle_darwin ()
95 {
96   stop ();
97
98   d_queue->iterate_start ();
99   s_node_ptr l_node = d_queue->iterate_next ();
100   while (l_node) {
101     s_both_ptr l_both = l_node->both ();
102     delete l_both;
103     l_both = NULL;
104     l_node->both (NULL);
105     s_buffer_ptr l_buf = l_node->object ();
106     delete l_buf;
107     l_buf = NULL;
108     l_node->object (NULL);
109     l_node = d_queue->iterate_next ();
110   }
111   delete d_queue;
112   d_queue = NULL;
113   delete d_buffer;
114   d_buffer = NULL;
115   delete d_readRunning;
116   d_readRunning = NULL;
117   delete d_runThreadRunning;
118   d_runThreadRunning = NULL;
119   delete d_runBlock;
120   d_runBlock = NULL;
121   delete d_readBlock;
122   d_readBlock = NULL;
123 }
124
125 bool
126 fusb_ephandle_darwin::start ()
127 {
128   UInt8  direction, number, interval;
129   UInt16 maxPacketSize;
130
131 // reset circular buffer
132   d_buffer->reset ();
133
134 // reset the queue
135   d_queue->num_used (0);
136   d_queue->iterate_start ();
137   s_node_ptr l_node = d_queue->iterate_next ();
138   while (l_node) {
139     l_node->both()->set (l_node, this);
140     l_node->object()->reset ();
141     l_node->set_available ();
142     l_node = d_queue->iterate_next ();
143   }
144
145   d_pipeRef = d_transferType = 0;
146
147   usb_dev_handle* dev = d_devhandle->get_usb_dev_handle ();
148   if (! dev)
149     USB_ERROR_STR (false, -ENXIO, "fusb_ephandle_darwin::start: "
150                    "null device");
151
152   darwin_dev_handle* device = (darwin_dev_handle*) dev->impl_info;
153   if (! device)
154     USB_ERROR_STR (false, -ENOENT, "fusb_ephandle_darwin::start: "
155                    "device not initialized");
156
157   if (usb_debug) {
158     std::cerr << "fusb_ephandle_darwin::start: dev = " <<
159       (void*) dev << ", device = " << (void*) device << std::endl;
160   }
161
162   d_interfaceRef = device->interface;
163   if (! d_interfaceRef)
164     USB_ERROR_STR (false, -EACCES, "fusb_ephandle_darwin::start: "
165                    "interface used without being claimed");
166   d_interface = *d_interfaceRef;
167
168 // get read or write pipe info (depends on "d_input_p")
169
170   if (usb_debug > 3) {
171     std::cerr << "fusb_ephandle_darwin::start d_endpoint = " << d_endpoint
172               << ", d_input_p = " << (d_input_p ? "TRUE" : "FALSE") << std::endl;
173   }
174
175   int l_endpoint = (d_input_p ? USB_ENDPOINT_IN : USB_ENDPOINT_OUT);
176   int pipeRef = ep_to_pipeRef (device, d_endpoint | l_endpoint);
177   if (pipeRef < 0)
178     USB_ERROR_STR (false, -EINVAL, "fusb_ephandle_darwin::start "
179                    " invalid pipeRef.\n");
180
181   d_pipeRef = pipeRef;
182   d_interface->GetPipeProperties (d_interfaceRef,
183                                   d_pipeRef,
184                                   &direction,
185                                   &number,
186                                   &d_transferType,
187                                   &maxPacketSize,
188                                   &interval);
189   if (usb_debug == 3) {
190     std::cerr << "fusb_ephandle_darwin::start: " << (d_input_p ? "read" : "write")
191               << ": ep = " << d_endpoint << ", pipeRef = " << d_pipeRef << "interface = "
192               << d_interface << ", interfaceRef = " << d_interfaceRef
193               << ", if_direction = " << direction << ", if_# = " << number
194               << ", if_interval = " << interval << ", if_maxPacketSize = "
195               << maxPacketSize << std::endl;
196   }
197
198   // set global start boolean
199   d_started = true;
200
201   // lock the runBlock mutex, before creating the run thread.
202   // this guarantees that we can control execution between these 2 threads
203   d_runBlock->mutex ()->lock ();
204
205   // create the run thread, which allows OSX to process I/O separately
206   d_runThread = new mld_thread (run_thread, this);
207
208   // wait until the run thread (and possibky read thread) are -really-
209   // going; this will unlock the mutex before waiting for a signal ()
210   d_runBlock->wait ();
211
212   if (usb_debug) {
213     std::cerr << "fusb_ephandle_darwin::start: " << (d_input_p ? "read" : "write")
214               << " started." << std::endl;
215   }
216
217   return (true);
218 }
219
220 void
221 fusb_ephandle_darwin::run_thread (void* arg)
222 {
223   fusb_ephandle_darwin* This = static_cast<fusb_ephandle_darwin*>(arg);
224
225   // lock the run thread running mutex; if ::stop() is called, it will
226   // first abort() the pipe then wait for the run thread to finish,
227   // via a lock() on this mutex
228   mld_mutex_ptr l_runThreadRunning = This->d_runThreadRunning;
229   l_runThreadRunning->lock ();
230
231   mld_mutex_ptr l_readRunning = This->d_readRunning;
232   mld_condition_ptr l_readBlock = This->d_readBlock;
233   mld_mutex_ptr l_readBlock_mutex = l_readBlock->mutex ();
234
235   bool l_input_p = This->d_input_p;
236
237   if (usb_debug) {
238     std::cerr << "fusb_ephandle_darwin::run_thread: starting for "
239               << (l_input_p ? "read" : "write") << "." << std::endl;
240   }
241
242   usb_interface_t** l_interfaceRef = This->d_interfaceRef;
243   usb_interface_t* l_interface = This->d_interface;
244   CFRunLoopSourceRef l_cfSource;
245
246 // create async run loop
247   l_interface->CreateInterfaceAsyncEventSource (l_interfaceRef, &l_cfSource);
248   CFRunLoopAddSource (CFRunLoopGetCurrent (), l_cfSource,
249                       kCFRunLoopDefaultMode);
250 // get run loop reference, to allow other threads to stop
251   This->d_CFRunLoopRef = CFRunLoopGetCurrent ();
252
253   mld_thread_ptr l_rwThread = NULL;
254
255   if (l_input_p) {
256     // lock the readBlock mutex, before creating the read thread.
257     // this guarantees that we can control execution between these 2 threads
258     l_readBlock_mutex->lock ();
259     // create the read thread, which just issues all of the starting
260     // async read commands, then returns
261     l_rwThread = new mld_thread (read_thread, arg);
262     // wait until the the read thread is -really- going; this will
263     // unlock the read block mutex before waiting for a signal ()
264     l_readBlock->wait ();
265   }
266
267   // now signal the run condition to release and finish ::start().
268
269   // lock the runBlock mutex first; this will force waiting until the
270   // ->wait() command is issued in ::start()
271   mld_mutex_ptr l_run_block_mutex = This->d_runBlock->mutex ();
272   l_run_block_mutex->lock ();
273
274   // now that the lock is in place, signal the parent thread that
275   // things are running
276   This->d_runBlock->signal ();
277
278   // release the run_block mutex, just in case
279   l_run_block_mutex->unlock ();
280
281   // run the loop
282   CFRunLoopRun ();
283
284   if (l_input_p) {
285     // wait for read_thread () to finish, if needed
286     l_readRunning->lock ();
287     l_readRunning->unlock ();
288   }
289
290   // remove run loop stuff
291   CFRunLoopRemoveSource (CFRunLoopGetCurrent (),
292                          l_cfSource, kCFRunLoopDefaultMode);
293
294   if (usb_debug) {
295     std::cerr << "fusb_ephandle_darwin::run_thread: finished for "
296               << (l_input_p ? "read" : "write") << "." << std::endl;
297   }
298
299   // release the run thread running mutex
300   l_runThreadRunning->unlock ();
301 }
302
303 void
304 fusb_ephandle_darwin::read_thread (void* arg)
305 {
306   if (usb_debug) {
307     std::cerr << "fusb_ephandle_darwin::read_thread: starting." << std::endl;
308   }
309
310   fusb_ephandle_darwin* This = static_cast<fusb_ephandle_darwin*>(arg);
311
312   // before doing anything else, lock the read running mutex.  this
313   // mutex does flow control between this thread and the run_thread
314   mld_mutex_ptr l_readRunning = This->d_readRunning;
315   l_readRunning->lock ();
316
317   // signal the read condition from run_thread() to continue
318
319   // lock the readBlock mutex first; this will force waiting until the
320   // ->wait() command is issued in ::run_thread()
321   mld_condition_ptr l_readBlock = This->d_readBlock;
322   mld_mutex_ptr l_read_block_mutex = l_readBlock->mutex ();
323   l_read_block_mutex->lock ();
324
325   // now that the lock is in place, signal the parent thread that
326   // things are running here
327   l_readBlock->signal ();
328
329   // release the run_block mutex, just in case
330   l_read_block_mutex->unlock ();
331
332   // queue up all of the available read requests
333   s_queue_ptr l_queue = This->d_queue;
334   l_queue->iterate_start ();
335   s_node_ptr l_node = l_queue->iterate_next ();
336   while (l_node) {
337     This->read_issue (l_node->both ());
338     l_node = l_queue->iterate_next ();
339   }
340
341   if (usb_debug) {
342     std::cerr << "fusb_ephandle_darwin::read_thread: finished." << std::endl;
343   }
344
345   // release the read running mutex, to let the parent thread knows
346   // that this thread is finished
347   l_readRunning->unlock ();
348 }
349
350 void
351 fusb_ephandle_darwin::read_issue (s_both_ptr l_both)
352 {
353   if ((! l_both) || (! d_started)) {
354     if (usb_debug > 4) {
355       std::cerr << "fusb_ephandle_darwin::read_issue: Doing nothing; "
356                 << "l_both is " << (void*) l_both << "; started is "
357                 << (d_started ? "TRUE" : "FALSE") << std::endl;
358     }
359     return;
360   }
361
362 // set the node and buffer from the input "both"
363   s_node_ptr l_node = l_both->node ();
364   s_buffer_ptr l_buf = l_node->object ();
365   void* v_buffer = (void*) l_buf->buffer ();
366
367 // read up to d_bufLenBytes
368   size_t bufLen = d_bufLenBytes;
369   l_buf->n_used (bufLen);
370
371 // setup system call result
372   io_return_t result = kIOReturnSuccess;
373
374   if (d_transferType == kUSBInterrupt)
375 /* This is an interrupt pipe. We can't specify a timeout. */
376     result = d_interface->ReadPipeAsync
377       (d_interfaceRef, d_pipeRef, v_buffer, bufLen,
378        (IOAsyncCallback1) read_completed, (void*) l_both);
379   else
380     result = d_interface->ReadPipeAsyncTO
381       (d_interfaceRef, d_pipeRef, v_buffer, bufLen, 0, USB_TIMEOUT,
382        (IOAsyncCallback1) read_completed, (void*) l_both);
383
384   if (result != kIOReturnSuccess)
385     USB_ERROR_STR_NO_RET (- darwin_to_errno (result),
386                           "fusb_ephandle_darwin::read_issue "
387                           "(ReadPipeAsync%s): %s",
388                           d_transferType == kUSBInterrupt ? "" : "TO",
389                           darwin_error_str (result));
390   else if (usb_debug > 4) {
391     std::cerr << "fusb_ephandle_darwin::read_issue: Queued " << (void*) l_both
392               << " (" << bufLen << " Bytes)" << std::endl;
393   }
394 }
395
396 void
397 fusb_ephandle_darwin::read_completed (void* refCon,
398                                       io_return_t result,
399                                       void* io_size)
400 {
401   size_t l_size = (size_t) io_size;
402   s_both_ptr l_both = static_cast<s_both_ptr>(refCon);
403   fusb_ephandle_darwin* This = static_cast<fusb_ephandle_darwin*>(l_both->This ());
404   s_node_ptr l_node = l_both->node ();
405   circular_buffer<char>* l_buffer = This->d_buffer;
406   s_buffer_ptr l_buf = l_node->object ();
407   size_t l_i_size = l_buf->n_used ();
408
409   if (This->d_started && (l_i_size != l_size)) {
410     std::cerr << "fusb_ephandle_darwin::read_completed: Expected " << l_i_size
411               << " bytes; read " << l_size << "." << std::endl;
412   } else if (usb_debug > 4) {
413     std::cerr << "fusb_ephandle_darwin::read_completed: Read " << (void*) l_both
414               << " (" << l_size << " bytes)" << std::endl;
415   }
416
417 // add this read to the transfer buffer
418   if (l_buffer->enqueue (l_buf->buffer (), l_size) == -1) {
419     fputs ("iU", stderr);
420     fflush (stderr);
421   }
422
423 // set buffer's # data to 0
424   l_buf->n_used (0);
425
426 // issue another read for this "both"
427   This->read_issue (l_both);
428 }
429
430 int
431 fusb_ephandle_darwin::read (void* buffer, int nbytes)
432 {
433   size_t l_nbytes = (size_t) nbytes;
434   d_buffer->dequeue ((char*) buffer, &l_nbytes);
435
436   if (usb_debug > 4) {
437     std::cerr << "fusb_ephandle_darwin::read: request for " << nbytes
438               << " bytes, " << l_nbytes << " bytes retrieved." << std::endl;
439   }
440
441   return ((int) l_nbytes);
442 }
443
444 int
445 fusb_ephandle_darwin::write (const void* buffer, int nbytes)
446 {
447   size_t l_nbytes = (size_t) nbytes;
448
449   if (! d_started) {
450     if (usb_debug) {
451       std::cerr << "fusb_ephandle_darwin::write: Not yet started." << std::endl;
452     }
453     return (0);
454   }
455
456   while (l_nbytes != 0) {
457 // find out how much data to copy; limited to "d_bufLenBytes" per node
458     size_t t_nbytes = (l_nbytes > d_bufLenBytes) ? d_bufLenBytes : l_nbytes;
459
460 // get next available node to write into;
461 // blocks internally if none available
462     s_node_ptr l_node = d_queue->find_next_available_node ();
463
464 // copy the input into the node's buffer
465     s_buffer_ptr l_buf = l_node->object ();
466     l_buf->buffer ((char*) buffer, t_nbytes);
467     void* v_buffer = (void*) l_buf->buffer ();
468
469 // setup callback parameter & system call return
470     s_both_ptr l_both = l_node->both ();
471     io_return_t result = kIOReturnSuccess;
472
473     if (d_transferType == kUSBInterrupt)
474 /* This is an interrupt pipe ... can't specify a timeout. */
475       result = d_interface->WritePipeAsync
476         (d_interfaceRef, d_pipeRef, v_buffer, t_nbytes,
477          (IOAsyncCallback1) write_completed, (void*) l_both);
478     else
479       result = d_interface->WritePipeAsyncTO
480         (d_interfaceRef, d_pipeRef, v_buffer, t_nbytes, 0, USB_TIMEOUT,
481          (IOAsyncCallback1) write_completed, (void*) l_both);
482
483     if (result != kIOReturnSuccess)
484       USB_ERROR_STR (-1, - darwin_to_errno (result),
485                      "fusb_ephandle_darwin::write_thread "
486                      "(WritePipeAsync%s): %s",
487                      d_transferType == kUSBInterrupt ? "" : "TO",
488                      darwin_error_str (result));
489     else if (usb_debug > 4) {
490       std::cerr << "fusb_ephandle_darwin::write_thread: Queued " << (void*) l_both
491                 << " (" << t_nbytes << " Bytes)" << std::endl;
492     }
493     l_nbytes -= t_nbytes;
494   }
495
496   return (nbytes);
497 }
498
499 void
500 fusb_ephandle_darwin::write_completed (void* refCon,
501                                        io_return_t result,
502                                        void* io_size)
503 {
504   s_both_ptr l_both = static_cast<s_both_ptr>(refCon);
505   fusb_ephandle_darwin* This = static_cast<fusb_ephandle_darwin*>(l_both->This ());
506   size_t l_size = (size_t) io_size;
507   s_node_ptr l_node = l_both->node ();
508   s_queue_ptr l_queue = This->d_queue;
509   s_buffer_ptr l_buf = l_node->object ();
510   size_t l_i_size = l_buf->n_used ();
511
512   if (This->d_started && (l_i_size != l_size)) {
513     std::cerr << "fusb_ephandle_darwin::write_completed: Expected " << l_i_size
514               << " bytes written; wrote " << l_size << "." << std::endl;
515   } else if (usb_debug > 4) {
516     std::cerr << "fusb_ephandle_darwin::write_completed: Wrote " << (void*) l_both
517               << " (" << l_size << " Bytes)" << std::endl;
518   }
519
520 // set buffer's # data to 0
521   l_buf->n_used (0);
522 // make the node available for reuse
523   l_queue->make_node_available (l_node);
524 }
525
526 void
527 fusb_ephandle_darwin::abort ()
528 {
529   if (usb_debug) {
530     std::cerr << "fusb_ephandle_darwin::abort: starting." << std::endl;
531   }
532
533   io_return_t result = d_interface->AbortPipe (d_interfaceRef, d_pipeRef);
534
535   if (result != kIOReturnSuccess)
536     USB_ERROR_STR_NO_RET (- darwin_to_errno (result),
537                           "fusb_ephandle_darwin::abort "
538                           "(AbortPipe): %s", darwin_error_str (result));
539   if (usb_debug) {
540     std::cerr << "fusb_ephandle_darwin::abort: finished." << std::endl;
541   }
542 }
543
544 bool
545 fusb_ephandle_darwin::stop ()
546 {
547   if (! d_started)
548     return (true);
549
550   if (usb_debug) {
551     std::cerr << "fusb_ephandle_darwin::stop: stopping "
552               << (d_input_p ? "read" : "write") << "." << std::endl;
553   }
554
555   d_started = false;
556
557 // abort any pending IO transfers
558   abort ();
559
560 // wait for write transfer to finish
561   wait_for_completion ();
562
563 // tell IO buffer to abort any waiting conditions
564   d_buffer->abort ();
565
566 // stop the run loop
567   CFRunLoopStop (d_CFRunLoopRef);
568
569 // wait for the runThread to stop
570   d_runThreadRunning->lock ();
571   d_runThreadRunning->unlock ();
572
573   if (usb_debug) {
574     std::cerr << "fusb_ephandle_darwin::stop: " << (d_input_p ? "read" : "write")
575               << " stopped." << std::endl;
576   }
577
578   return (true);
579 }
580
581 void
582 fusb_ephandle_darwin::wait_for_completion ()
583 {
584   if (d_queue)
585     while (d_queue->in_use ())
586       usleep (1000);
587 }