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