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