first shot at re-adding libusb-0.12 support
[debian/gnuradio] / usrp / host / lib / usrp_prims_libusb.cc
1 /* -*- c++ -*- */
2 /*
3  * Copyright 2003,2004,2006,2009 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 "usrp/usrp_prims.h"
28 #include "usrp_commands.h"
29 #include "usrp_ids.h"
30 #include "usrp_i2c_addr.h"
31 #include "fpga_regs_common.h"
32 #include "fpga_regs_standard.h"
33 #include <usb.h>
34 #include <errno.h>
35 #include <stdio.h>
36 #include <unistd.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <ctype.h>
40 #include <time.h>               // FIXME should check with autoconf (nanosleep)
41 #include <algorithm>
42 #include <ad9862.h>
43 #include <assert.h>
44
45 extern "C" {
46 #include "md5.h"
47 };
48
49 #define VERBOSE 0
50
51 using namespace ad9862;
52
53 /*
54  * Forward Declarations
55  */
56
57 bool our_nanosleep (const struct timespec *delay);
58 const char *get_proto_filename (const std::string user_filename,
59                                 const char *env_var,
60                                 const char *def);
61 char *find_file (const char *filename, int hw_rev);
62 void load_status_msg (usrp_load_status_t s, const char *type,
63                       const char *filename);
64 bool usrp1_fpga_write (libusb_device_handle *udh, int regno, int value);
65 bool usrp1_fpga_read (libusb_device_handle *udh, int regno, int *value);
66 bool usrp_set_switch (libusb_device_handle *udh, int cmd_byte, bool on);
67
68 bool usrp_set_fpga_reset (struct usb_dev_handle *udh, bool on);
69 bool usrp_set_fpga_tx_enable (struct usb_dev_handle *udh, bool on);
70 bool usrp_set_fpga_rx_enable (struct usb_dev_handle *udh, bool on);
71 bool usrp_set_fpga_tx_reset (struct usb_dev_handle *udh, bool on);
72 bool usrp_set_fpga_rx_reset (struct usb_dev_handle *udh, bool on);
73
74
75
76 static const int FIRMWARE_HASH_SLOT     = 0;
77 static const int FPGA_HASH_SLOT         = 1;
78
79 static const int hash_slot_addr[2] = {
80   USRP_HASH_SLOT_0_ADDR,
81   USRP_HASH_SLOT_1_ADDR
82 };
83
84 static const char *default_firmware_filename = "std.ihx";
85 static const char *default_fpga_filename     = "std_2rxhb_2tx.rbf";
86
87 #include "std_paths.h"
88 #include <stdio.h>
89
90 void
91 usrp_one_time_init ()
92 {
93   static bool first = true;
94
95   if (first){
96     first = false;
97     usb_init ();                        // usb library init
98     usb_find_busses ();
99     usb_find_devices ();
100   }
101 }
102
103 void
104 usrp_rescan ()
105 {
106   usb_find_busses ();
107   usb_find_devices ();
108 }
109
110 // ----------------------------------------------------------------
111
112 /*
113  * q must be a real USRP, not an FX2.  Return its hardware rev number.
114  */
115 int
116 usrp_hw_rev (struct usb_device *q)
117 {
118   return q->descriptor.bcdDevice & 0x00FF;
119 }
120
121 /*
122  * q must be a real USRP, not an FX2.  Return true if it's configured.
123  */
124 static bool
125 _usrp_configured_p (struct usb_device *q)
126 {
127   return (q->descriptor.bcdDevice & 0xFF00) != 0;
128 }
129
130 bool
131 usrp_usrp_p (struct usb_device *q)
132 {
133   return (q->descriptor.idVendor == USB_VID_FSF
134           && q->descriptor.idProduct == USB_PID_FSF_USRP);
135 }
136
137 bool
138 usrp_fx2_p (struct usb_device *q)
139 {
140   return (q->descriptor.idVendor == USB_VID_CYPRESS
141           && q->descriptor.idProduct == USB_PID_CYPRESS_FX2);
142 }
143
144 // ----------------------------------------------------------------
145
146 struct usb_device *
147 usrp_find_device (int nth, bool fx2_ok_p, libusb_context *ctx)
148 {
149   struct usb_bus *p;
150   struct usb_device *q;
151   int    n_found = 0;
152
153   usrp_one_time_init ();
154   
155   p = usb_get_busses();
156   while (p != NULL){
157     q = p->devices;
158     while (q != NULL){
159       if (usrp_usrp_p (q) || (fx2_ok_p && usrp_fx2_p (q))){
160         if (n_found == nth)     // return this one
161           return q;
162         n_found++;              // keep looking
163       }
164       q = q->next;
165     }
166     p = p->next;
167   }
168   return 0;     // not found
169 }
170
171 struct usb_dev_handle *
172 usrp_open_interface (struct usb_device *dev, int interface, int altinterface)
173 {
174   struct usb_dev_handle *udh = usb_open (dev);
175   if (udh == 0)
176     return 0;
177
178   if (dev != usb_device (udh)){
179     fprintf (stderr, "%s:%d: internal error!\n", __FILE__, __LINE__);
180     abort ();
181   }
182
183 #if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
184   // There's no get get_configuration function, and with some of the newer kernels
185   // setting the configuration, even if to the same value, hoses any other processes
186   // that have it open.  Hence we opt to not set it at all (We've only
187   // got a single configuration anyway).  This may hose the win32 stuff...
188
189   // Appears to be required for libusb-win32 and Cygwin -- dew 09/20/06
190   if (usb_set_configuration (udh, 1) < 0){
191     /*
192      * Ignore this error.  
193      *
194      * Seems that something changed in drivers/usb/core/devio.c:proc_setconfig such that
195      * it returns -EBUSY if _any_ of the interfaces of a device are open.
196      * We've only got a single configuration, so setting it doesn't even seem
197      * like it should be required.
198      */
199   }
200 #endif
201
202   if (usb_claim_interface (udh, interface) < 0){
203     fprintf (stderr, "%s:usb_claim_interface: failed interface %d\n", __FUNCTION__,interface);
204     fprintf (stderr, "%s\n", usb_strerror());
205     usb_close (udh);
206     return 0;
207   }
208
209   if (usb_set_altinterface (udh, altinterface) < 0){
210     fprintf (stderr, "%s:usb_set_alt_interface: failed\n", __FUNCTION__);
211     fprintf (stderr, "%s\n", usb_strerror());
212     usb_release_interface (udh, interface);
213     usb_close (udh);
214     return 0;
215   }
216
217   return udh;
218 }
219
220 bool
221 usrp_close_interface (struct usb_dev_handle *udh)
222 {
223   // we're assuming that closing an interface automatically releases it.
224   return usb_close (udh) == 0;
225 }
226
227 // ----------------------------------------------------------------
228 // write internal ram using Cypress vendor extension
229
230 bool
231 write_internal_ram (struct usb_dev_handle *udh, unsigned char *buf,
232                     int start_addr, size_t len)
233 {
234   int addr;
235   int n;
236   int a;
237   int quanta = MAX_EP0_PKTSIZE;
238
239   for (addr = start_addr; addr < start_addr + (int) len; addr += quanta){
240     n = len + start_addr - addr;
241     if (n > quanta)
242       n = quanta;
243
244     a = usb_control_msg (udh, 0x40, 0xA0,
245                          addr, 0, (char *)(buf + (addr - start_addr)), n, 1000);
246
247     if (a < 0){
248       fprintf(stderr,"write_internal_ram failed: %s\n", usb_strerror());
249       return false;
250     }
251   }
252   return true;
253 }
254
255
256 // ----------------------------------------------------------------
257 // write vendor extension command to USRP
258
259 int
260 write_cmd (struct usb_dev_handle *udh,
261            int request, int value, int index,
262            unsigned char *bytes, int len)
263 {
264   int   requesttype = (request & 0x80) ? VRT_VENDOR_IN : VRT_VENDOR_OUT;
265
266   int r = usb_control_msg (udh, requesttype, request, value, index,
267                            (char *) bytes, len, 1000);
268   if (r < 0){
269     // we get EPIPE if the firmware stalls the endpoint.
270     if (errno != EPIPE)
271       fprintf (stderr, "usb_control_msg failed: %s\n", usb_strerror ());
272   }
273
274   return r;
275 }
276
277
278 bool
279 usrp_set_hash (struct usb_dev_handle *udh, int which,
280                const unsigned char hash[USRP_HASH_SIZE])
281 {
282   which &= 1;
283   
284   // we use the Cypress firmware down load command to jam it in.
285   int r = usb_control_msg (udh, 0x40, 0xa0, hash_slot_addr[which], 0,
286                            (char *) hash, USRP_HASH_SIZE, 1000);
287   return r == USRP_HASH_SIZE;
288 }
289
290 bool
291 usrp_get_hash (struct usb_dev_handle *udh, int which, 
292                unsigned char hash[USRP_HASH_SIZE])
293 {
294   which &= 1;
295   
296   // we use the Cypress firmware upload command to fetch it.
297   int r = usb_control_msg (udh, 0xc0, 0xa0, hash_slot_addr[which], 0,
298                            (char *) hash, USRP_HASH_SIZE, 1000);
299   return r == USRP_HASH_SIZE;
300 }
301
302 bool
303 usrp_write_fpga_reg (struct usb_dev_handle *udh, int reg, int value)
304 {
305   switch (usrp_hw_rev (usb_device (udh))){
306   case 0:                       // not supported ;)
307     abort();    
308
309   default:
310     return usrp1_fpga_write (udh, reg, value);
311   }
312 }
313
314 bool
315 usrp_read_fpga_reg (struct usb_dev_handle *udh, int reg, int *value)
316 {
317   switch (usrp_hw_rev (usb_device (udh))){
318   case 0:               // not supported ;)
319     abort();
320     
321   default:
322     return usrp1_fpga_read (udh, reg, value);
323   }
324 }
325
326
327
328
329 static usb_dev_handle *
330 open_nth_cmd_interface (int nth)
331 {
332   struct usb_device *udev = usrp_find_device (nth);
333   if (udev == 0){
334     fprintf (stderr, "usrp: failed to find usrp[%d]\n", nth);
335     return 0;
336   }
337
338   struct usb_dev_handle *udh;
339
340   udh = usrp_open_cmd_interface (udev);
341   if (udh == 0){
342     // FIXME this could be because somebody else has it open.
343     // We should delay and retry...
344     fprintf (stderr, "open_nth_cmd_interface: open_cmd_interface failed\n");
345     usb_strerror ();
346     return 0;
347   }
348
349   return udh;
350 }
351
352
353 usrp_load_status_t
354 usrp_load_firmware_nth (int nth, const char *filename, bool force, libusb_context *ctx){
355   struct usb_dev_handle *udh = open_nth_cmd_interface (nth);
356   if (udh == 0)
357     return ULS_ERROR;
358
359   usrp_load_status_t s = usrp_load_firmware (udh, filename, force);
360   usrp_close_interface (udh);
361
362   switch (s){
363
364   case ULS_ALREADY_LOADED:              // nothing changed...
365     return ULS_ALREADY_LOADED;
366     break;
367
368   case ULS_OK:
369     // we loaded firmware successfully.
370
371     // It's highly likely that the board will renumerate (simulate a
372     // disconnect/reconnect sequence), invalidating our current
373     // handle.
374
375     // FIXME.  Turn this into a loop that rescans until we refind ourselves
376     
377     struct timespec     t;      // delay for 1 second
378     t.tv_sec = 2;
379     t.tv_nsec = 0;
380     our_nanosleep (&t);
381
382     usb_find_busses ();         // rescan busses and devices
383     usb_find_devices ();
384
385     return ULS_OK;
386
387   default:
388   case ULS_ERROR:               // some kind of problem
389     return ULS_ERROR;
390   }
391 }
392
393 bool
394 usrp_load_standard_bits (int nth, bool force,
395                          const std::string fpga_filename,
396                          const std::string firmware_filename,
397                          libusb_context *ctx)
398 {
399   usrp_load_status_t    s;
400   const char            *filename;
401   const char            *proto_filename;
402   int hw_rev;
403
404   // first, figure out what hardware rev we're dealing with
405   {
406     struct usb_device *udev = usrp_find_device (nth);
407     if (udev == 0){
408       fprintf (stderr, "usrp: failed to find usrp[%d]\n", nth);
409       return false;
410     }
411     hw_rev = usrp_hw_rev (udev);
412   }
413
414   // start by loading the firmware
415
416   proto_filename = get_proto_filename(firmware_filename, "USRP_FIRMWARE",
417                                       default_firmware_filename);
418   filename = find_file(proto_filename, hw_rev);
419   if (filename == 0){
420     fprintf (stderr, "Can't find firmware: %s\n", proto_filename);
421     return false;
422   }
423
424   s = usrp_load_firmware_nth (nth, filename, force);
425   load_status_msg (s, "firmware", filename);
426
427   if (s == ULS_ERROR)
428     return false;
429
430   // if we actually loaded firmware, we must reload fpga ...
431   if (s == ULS_OK)
432     force = true;
433
434   // now move on to the fpga configuration bitstream
435
436   proto_filename = get_proto_filename(fpga_filename, "USRP_FPGA",
437                                       default_fpga_filename);
438   filename = find_file (proto_filename, hw_rev);
439   if (filename == 0){
440     fprintf (stderr, "Can't find fpga bitstream: %s\n", proto_filename);
441     return false;
442   }
443
444   struct usb_dev_handle *udh = open_nth_cmd_interface (nth);
445   if (udh == 0)
446     return false;
447   
448   s = usrp_load_fpga (udh, filename, force);
449   usrp_close_interface (udh);
450   load_status_msg (s, "fpga bitstream", filename);
451
452   if (s == ULS_ERROR)
453     return false;
454
455   return true;
456 }
457
458 void
459 power_down_9862s (struct usb_dev_handle *udh)
460 {
461   static const unsigned char regs[] = {
462     REG_RX_PWR_DN,      0x01,              // everything
463     REG_TX_PWR_DN,      0x0f,              // pwr dn digital and analog_both
464     REG_TX_MODULATOR,   0x00               // coarse & fine modulators disabled
465   };
466
467   switch (usrp_hw_rev (usb_device (udh))){
468   case 0:
469     break;
470
471   default:
472     usrp_9862_write_many_all (udh, regs, sizeof (regs));
473     break;
474   }
475 }
476
477
478 std::string
479 usrp_serial_number(struct usb_dev_handle *udh)
480 {
481   unsigned char iserial = usb_device(udh)->descriptor.iSerialNumber;
482   if (iserial == 0)
483     return "";
484
485   char buf[1024];
486   if (usb_get_string_simple(udh, iserial, buf, sizeof(buf)) < 0)
487     return "";
488
489   return buf;
490 }