Applied libusb-1.0 patch set from Thomas Tsou <ttsou@vt.edu>:
[debian/gnuradio] / usrp / host / lib / fusb_libusb1.cc
1 /* -*- c++ -*- */
2 /*
3  * Copyright 2003 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 #include <fusb_libusb1.h>
28 #include <libusb-1.0/libusb.h>
29 #include <stdexcept>
30 #include <cstdio>
31 #include <assert.h>
32 #include <string.h>
33 #include <algorithm>
34 #include <errno.h>
35 #include <string.h>
36
37 #define MINIMIZE_TX_BUFFERING true 
38
39 static const int MAX_BLOCK_SIZE = fusb_sysconfig::max_block_size(); 
40 static const int DEFAULT_BLOCK_SIZE = MAX_BLOCK_SIZE;
41 static const int DEFAULT_BUFFER_SIZE = 4 * (1L << 20);  // 4 MB endpoint
42 static const int LIBUSB_TIMEOUT = 0;                    // no timeout
43
44 inline static fusb_ephandle_libusb1*
45 lut_get_ephandle (libusb_transfer *lut)
46 {
47   return (fusb_ephandle_libusb1 *) lut->user_data;
48 }
49
50 // ------------------------------------------------------------------------
51 //      libusb_transfer allocation, deallocation, and callback 
52 // ------------------------------------------------------------------------
53
54 static void
55 free_lut (libusb_transfer *lut)
56 {
57
58   // if this was an input transfer, free the buffer
59   if (lut->endpoint & 0x80)
60     delete [] ((unsigned char *) lut->buffer);
61
62   libusb_free_transfer(lut); 
63
64 }
65
66 /*
67  * The callback means the libusb_transfer is completed whether sent, cancelled,
68  * or failed. Move the libusb_transfer from the pending list to the
69  * completed list. If the cancel is from the destructor then free the 
70  * transfer instead; normally this won't happen since all endpoints should be
71  * destroyed first leaving the pending list empty.
72  */
73
74 static void
75 generic_callback(struct libusb_transfer *lut)
76 {
77
78   // Fish out devhandle from endpoint
79   fusb_devhandle_libusb1* dev_handle = 
80     lut_get_ephandle(lut)->get_fusb_devhandle_libusb1();
81
82   dev_handle->pending_remove(lut);
83
84   if (lut->status == LIBUSB_TRANSFER_CANCELLED && dev_handle->_teardown() == 1)
85   {
86     free_lut (lut);
87     return;
88   }
89   
90   lut_get_ephandle(lut)->completed_list_add(lut);
91
92
93
94 static libusb_transfer*
95 alloc_lut (fusb_ephandle_libusb1 *self, int buffer_length, int endpoint,
96            bool input_p, unsigned char *write_buffer,
97            fusb_devhandle_libusb1 *dh)
98 {
99
100   struct libusb_transfer* lut = libusb_alloc_transfer(0);
101
102   endpoint = (endpoint & 0x7f) | (input_p ? 0x80 : 0);
103
104   if (input_p)
105     write_buffer = new unsigned char [buffer_length];
106
107   // We need the base class libusb_device_handle
108   libusb_device_handle *dev_handle = dh->get_libusb_device_handle();
109
110   // Load the libusb_transfer for bulk transfer
111   libusb_fill_bulk_transfer (lut,               // transfer
112                              dev_handle,        // dev_handle 
113                              endpoint,          // endpoint
114                              write_buffer,      // buffer
115                              buffer_length,     // length
116                              generic_callback,  // callback 
117                              self,              // user_data
118                              LIBUSB_TIMEOUT);   // timeout
119
120   return lut;
121 }
122
123 // ------------------------------------------------------------------------
124 //                              device handle
125 // ------------------------------------------------------------------------
126
127 fusb_devhandle_libusb1::fusb_devhandle_libusb1 (libusb_device_handle *udh)
128   : fusb_devhandle (udh), d_teardown (false)
129 {
130   // that's it 
131 }
132
133 fusb_devhandle_libusb1::~fusb_devhandle_libusb1 ()
134 {
135   d_teardown = true;
136
137   std::list<libusb_transfer*>::reverse_iterator it;
138
139   // After cancellation the libusb_transfer is still active so delay freeing
140   // transfer until callback occurs. In most cases the pending list should
141   // already be empty by the time this destructor is called.
142
143   for (it = d_pending_rqsts.rbegin (); it != d_pending_rqsts.rend (); it++) {
144     _cancel_lut (*it);
145   }
146
147   // Wait for pending list to empty
148   _wait_for_completion ();
149
150 }
151
152 fusb_ephandle*
153 fusb_devhandle_libusb1::make_ephandle (int endpoint, bool input_p,
154                                        int block_size, int nblocks)
155 {
156   return new fusb_ephandle_libusb1 (this, endpoint, input_p,
157                                     block_size, nblocks);
158 }
159
160 /*
161  * devhandle list manipulators 
162  */
163
164 void 
165 fusb_devhandle_libusb1::pending_add (libusb_transfer *lut)
166 {
167   d_pending_rqsts.push_back (lut);
168 }
169
170
171 /*
172  * Attempt to cancel all transations associated with eph
173  */
174
175 void
176 fusb_devhandle_libusb1::_cancel_pending_rqsts (fusb_ephandle_libusb1 *eph)
177 {
178   std::list<libusb_transfer*>::reverse_iterator it;
179
180   for (it = d_pending_rqsts.rbegin (); it != d_pending_rqsts.rend (); it++){
181     if (lut_get_ephandle (*it) == eph)
182       _cancel_lut (*it);
183   }
184 }
185
186 /*
187  * Pull from the pending list
188  */
189
190 libusb_transfer *
191 fusb_devhandle_libusb1::pending_get ()
192 {
193   if (d_pending_rqsts.empty ())
194     return 0;
195
196   libusb_transfer *lut = d_pending_rqsts.front ();
197   d_pending_rqsts.pop_front ();
198   return lut;
199 }
200
201 /*
202  * Match libusb_tranfer with the pending list and erase 
203  * Return true if found, false otherwise
204  */
205
206 bool
207 fusb_devhandle_libusb1::pending_remove (libusb_transfer *lut)
208 {
209   std::list<libusb_transfer*>::iterator result;
210   result = find (d_pending_rqsts.begin (), d_pending_rqsts.end (), lut);
211
212   if (result == d_pending_rqsts.end ()) {
213     fprintf (stderr, "fusb::pending_remove: failed to find lut in pending_rqsts: %p\n", lut);
214
215     return false;
216   }
217   d_pending_rqsts.erase (result);
218   return true;
219 }
220
221 /*
222  * Submit the libusb_transfer to libusb
223  * iff successful, the transfer will be placed on the devhandle pending list.
224  */
225
226 bool
227 fusb_devhandle_libusb1::_submit_lut (libusb_transfer *lut)
228 {
229
230   int ret = libusb_submit_transfer (lut);
231   if (ret < 0) {
232     fprintf(stderr, "fusb::_submit_lut %d", ret);
233     return false;
234   }
235
236   pending_add(lut);
237   return true;
238
239 }
240
241 /*
242  * Attempt to cancel any pending libusb_transfer transactions. 
243  * Return true in the absence of errors, which does not mean that the transfer
244  * is cancelled. Cancellation can be checked after the callback is fired off
245  * by libusb. 
246  */ 
247
248 bool
249 fusb_devhandle_libusb1::_cancel_lut (libusb_transfer *lut)
250 {
251
252   int ret = libusb_cancel_transfer (lut);
253   if (ret < 0) {
254     fprintf (stderr, "fusb::_cancel_lut");
255     return false;
256   }
257   return true;
258
259 }
260
261 void
262 fusb_devhandle_libusb1::_wait_for_completion ()
263 {
264
265   int ret;
266   struct timeval tv;
267   tv.tv_sec = 1;
268   tv.tv_usec =  0;
269
270   // The regular libusb_handle_events sets a hardcoded timeout of 2
271   // seconds. Most of these calls should be changed to appropriate block / non-
272   // blocking version using libusb_handle_events_timeout. This was just a test
273   // usage. 
274
275   while (!d_pending_rqsts.empty ()) {
276     if ((ret = libusb_handle_events_timeout(NULL, &tv)) < 0) {
277       fprintf (stderr, "fusb: libusb_handle_events error %d\n", ret);
278       break;
279     }
280   }
281
282 }
283
284 // ------------------------------------------------------------------------
285 //                              endpoint handle
286 // ------------------------------------------------------------------------
287
288 fusb_ephandle_libusb1::fusb_ephandle_libusb1 (fusb_devhandle_libusb1 *dh,
289                                               int endpoint, bool input_p,
290                                               int block_size, int nblocks)
291   : fusb_ephandle (endpoint, input_p, block_size, nblocks),
292     d_devhandle (dh),
293     d_write_work_in_progress (0), d_write_buffer (0),
294     d_read_work_in_progress (0), d_read_buffer (0), d_read_buffer_end (0)
295 {
296
297   if (d_block_size < 0 || d_block_size > MAX_BLOCK_SIZE)
298     throw std::out_of_range ("fusb_ephandle_libusb1: block_size");
299
300   if (d_nblocks < 0)
301     throw std::out_of_range ("fusb_ephandle_libusb1: nblocks");
302
303   if (d_block_size == 0)
304     d_block_size = DEFAULT_BLOCK_SIZE;
305
306   if (d_nblocks == 0)
307     d_nblocks = std::max (1, DEFAULT_BUFFER_SIZE / d_block_size);
308
309   if (!d_input_p)
310     if (!MINIMIZE_TX_BUFFERING)
311       d_write_buffer = new unsigned char [d_block_size];
312
313   if (0)
314     fprintf(stderr, "fusb_ephandle_libusb1::ctor: d_block_size = %d  d_nblocks = %d\n",
315       d_block_size, d_nblocks);
316
317   // allocate libusb_transfers 
318   for (int i = 0; i < d_nblocks; i++)
319     d_free_list.push_back (alloc_lut (this, d_block_size, d_endpoint,
320                                       d_input_p, d_write_buffer, d_devhandle));
321 }
322
323 fusb_ephandle_libusb1::~fusb_ephandle_libusb1 ()
324 {
325
326   stop ();
327
328   libusb_transfer *lut;
329
330   while ((lut = free_list_get ()) != 0)
331     free_lut (lut);
332
333   while ((lut = completed_list_get ()) != 0)
334     free_lut (lut);
335
336   if (d_write_work_in_progress)
337     free_lut (d_write_work_in_progress);
338
339   delete [] d_write_buffer;
340
341   if (d_read_work_in_progress)
342     free_lut (d_read_work_in_progress);
343
344 }
345
346 bool
347 fusb_ephandle_libusb1::start ()
348 {
349
350   if (d_started)
351     return true;
352
353   d_started = true;
354
355   if (d_input_p) {
356      libusb_transfer *lut;
357
358      int nerrors = 0;
359      while ((lut = free_list_get ()) !=0 && nerrors < d_nblocks) {
360        if (!submit_lut (lut))
361          nerrors++;
362      }
363   }
364
365   return true;
366
367 }
368
369 /*
370  * Cancel all transfers in progress or pending and return to initial state 
371  */
372
373 bool
374 fusb_ephandle_libusb1::stop ()
375 {
376
377   if (!d_started)
378     return true;
379
380   if (d_write_work_in_progress){
381     free_list_add (d_write_work_in_progress);
382     d_write_work_in_progress = 0;
383   }
384
385   if (d_read_work_in_progress){
386     free_list_add (d_read_work_in_progress);
387     d_read_work_in_progress = 0;
388     d_read_buffer = 0;
389     d_read_buffer_end = 0;
390   }
391
392   d_devhandle->_cancel_pending_rqsts (this);
393
394   // Do work, reap transfers, etc. 
395   if (libusb_handle_events(NULL) < 0) { 
396     perror ("fusb::libusb_handle_events");
397     return false;
398   }
399
400   while (1) {
401     libusb_transfer *lut;
402     while ((lut = completed_list_get ()) != 0)
403       free_list_add (lut);
404
405     if (d_free_list.size () == (unsigned) d_nblocks)
406       break;
407
408     if (libusb_handle_events(NULL) < 0) {
409       perror ("fusb::libusb_handle_events");
410       return false;
411     }
412   }
413
414   d_started = false;
415   return true;
416
417 }
418
419 // ------------------------------------------------------------------------
420 //                      routines for writing    
421 // ------------------------------------------------------------------------
422
423 #if (MINIMIZE_TX_BUFFERING)
424
425 int
426 fusb_ephandle_libusb1::write (const void *buffer, int nbytes)
427 {
428
429   if (!d_started)       // doesn't matter here, but keeps semantics constant
430     return -1;
431   
432   if (d_input_p)
433     return -1;
434
435   assert(nbytes % 512 == 0);
436
437   unsigned char *src = (unsigned char *) buffer;
438
439   int n = 0;
440   while (n < nbytes){
441
442     struct libusb_transfer *lut = get_write_work_in_progress();
443     if (!lut)
444       return -1;
445     assert(lut->actual_length == 0);
446     int m = std::min(nbytes - n, MAX_BLOCK_SIZE);
447     lut->buffer = src;
448     lut->length = m;
449
450     n += m;
451     src += m;
452    
453     if (!submit_lut(lut))
454       return -1;
455
456     d_write_work_in_progress = 0;
457   }
458
459   return nbytes;
460 }
461
462 #else
463
464 int
465 fusb_ephandle_libusb1::write (const void *buffer, int nbytes)
466 {
467   if (!d_started)
468     return -1;
469
470   if (d_input_p)
471     return -1;
472
473   unsigned char *src = (unsigned char *) buffer;
474
475   int n = 0;
476   while (n < nbytes){
477
478     libusb_transfer *lut = get_write_work_in_progress ();
479     if (!lut)
480       return -1;
481     unsigned char *dst = (unsigned char *) lut->buffer;
482     int m = std::min (nbytes - n, lut->length - lut->actual_length);
483
484     memcpy (&dst[lut->actual_length], &src[n], m);
485     lut->actual_length += m;
486     n += m;
487
488     if (lut->actual_length == lut->length){
489       if (!submit_lut (lut))
490         return -1;
491       d_write_work_in_progress = 0;
492     }
493   }
494
495   return n;
496 }
497
498 #endif
499
500 struct libusb_transfer *
501 fusb_ephandle_libusb1::get_write_work_in_progress ()
502 {
503   if (d_write_work_in_progress)
504     return d_write_work_in_progress;
505
506   while (1) {
507
508     reap_complete_writes ();
509
510     struct libusb_transfer *lut = free_list_get ();
511
512     if (lut != 0){
513       assert (lut->actual_length == 0);
514       d_write_work_in_progress = lut;
515       return lut;
516     }
517
518     // Do work, reap transfers, etc. 
519     libusb_handle_events(NULL);
520   }
521 }
522
523 void
524 fusb_ephandle_libusb1::reap_complete_writes ()
525 {
526   // take a look at the completed list and xfer to free list after
527   // checking for errors.
528
529   libusb_transfer *lut;
530
531   while ((lut = completed_list_get ()) != 0) {
532
533     // Check for any errors or short writes that were reporetd in the transfer.
534     // libusb1 sets status, actual_length. 
535
536     if (lut->status != LIBUSB_TRANSFER_COMPLETED) { 
537       fprintf (stderr, "fusb: (status %d) \n", lut->status );
538     } 
539     else if (lut->actual_length != lut->length){
540       fprintf (stderr, "fusb: short write xfer: %d != %d\n",
541                lut->actual_length, lut->length);
542     }
543
544     free_list_add (lut);
545   }
546 }
547
548 void
549 fusb_ephandle_libusb1::wait_for_completion ()
550 {
551   d_devhandle->_wait_for_completion ();
552 }
553
554 // ------------------------------------------------------------------------
555 //                      routines for reading    
556 // ------------------------------------------------------------------------
557
558 int
559 fusb_ephandle_libusb1::read (void *buffer, int nbytes)
560 {
561   if (!d_started)       // doesn't matter here, but keeps semantics constant
562     return -1;
563
564   if (!d_input_p)
565     return -1;
566
567   unsigned char *dst = (unsigned char *) buffer;
568
569   int n = 0;
570   while (n < nbytes) {
571
572     if (d_read_buffer >= d_read_buffer_end)
573       if (!reload_read_buffer ())
574         return -1;
575
576     int m = std::min (nbytes - n, (int) (d_read_buffer_end - d_read_buffer));
577
578     memcpy (&dst[n], d_read_buffer, m);
579     d_read_buffer += m;
580     n += m;
581   }
582
583   return n;
584
585 }
586
587 bool
588 fusb_ephandle_libusb1::reload_read_buffer ()
589 {
590   assert (d_read_buffer >= d_read_buffer_end);
591
592   libusb_transfer *lut;
593
594   if (d_read_work_in_progress) {
595     lut = d_read_work_in_progress;
596     d_read_work_in_progress = 0;
597     d_read_buffer = 0;
598     d_read_buffer_end = 0;
599     lut->actual_length = 0;
600     if (!submit_lut (lut))
601       return false;
602   }
603
604   while (1) {
605
606     while ((lut = completed_list_get ()) == 0 ) {
607       if (libusb_handle_events(NULL) < 0) 
608         fprintf (stderr, "fusb: libusb_handle_events\n");
609     }
610
611     if (lut->status != LIBUSB_TRANSFER_COMPLETED) {
612       fprintf (stderr, "fust: (rd status %d) %s\n", lut->status, 
613                strerror (-lut->status));
614       lut->actual_length = 0;
615       free_list_add (lut);
616       return false;
617     }
618
619     d_read_work_in_progress = lut;
620     d_read_buffer = (unsigned char *) lut->buffer;
621     d_read_buffer_end = d_read_buffer + lut->actual_length;
622
623     return true;
624   }
625 }
626
627
628 /*
629  * ephandle list manipulation   
630  */
631
632
633 void
634 fusb_ephandle_libusb1::free_list_add (libusb_transfer *lut)
635 {
636   assert (lut_get_ephandle (lut) == this);
637   lut->actual_length = 0;
638   d_free_list.push_back (lut);
639 }
640
641 libusb_transfer *
642 fusb_ephandle_libusb1::free_list_get ()
643 {
644   if (d_free_list.empty ())
645     return 0;
646
647   libusb_transfer *lut = d_free_list.front ();
648   d_free_list.pop_front ();
649   return lut;
650 }
651
652 void
653 fusb_ephandle_libusb1::completed_list_add (libusb_transfer *lut)
654 {
655   assert (lut_get_ephandle (lut) == this);
656   d_completed_list.push_back (lut);
657 }
658
659 libusb_transfer *
660 fusb_ephandle_libusb1::completed_list_get ()
661 {
662   if (d_completed_list.empty ())
663     return 0;
664
665   libusb_transfer *lut = d_completed_list.front ();
666   d_completed_list.pop_front ();
667   return lut;
668 }
669
670 bool
671 fusb_ephandle_libusb1::submit_lut (libusb_transfer *lut)
672 {
673   if (!d_devhandle->_submit_lut (lut)) {
674     fprintf (stderr, "_submit_lut failed\n");
675     free_list_add (lut);
676     return false;
677   }
678   return true;
679 }