Imported Upstream version 3.0
[debian/gnuradio] / usrp / host / lib / usrp_prims.cc
1 /* -*- c++ -*- */
2 /*
3  * Copyright 2003,2004,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 2, 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_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 char *default_firmware_filename = "std.ihx";
62 static char *default_fpga_filename     = "std_2rxhb_2tx.rbf";
63
64 #include "std_paths.h"
65
66 static char *
67 find_file (const char *filename, int hw_rev)
68 {
69   char **sp = std_paths;
70   static char path[1000];
71   char *s;
72
73   s = getenv("USRP_PATH");
74   if (s) {
75     snprintf (path, sizeof (path), "%s/rev%d/%s", s, hw_rev, filename);
76     if (access (path, R_OK) == 0)
77       return path;
78   }
79
80   while (*sp){
81     snprintf (path, sizeof (path), "%s/rev%d/%s", *sp, hw_rev, filename);
82     if (access (path, R_OK) == 0)
83       return path;
84     sp++;
85   }
86   return 0;
87 }
88
89 static const char *
90 get_proto_filename(const std::string user_filename, const char *env_var, const char *def)
91 {
92   if (user_filename.length() != 0)
93     return user_filename.c_str();
94
95   char *s = getenv(env_var);
96   if (s && *s)
97     return s;
98
99   return def;
100 }
101
102
103 static void power_down_9862s (struct usb_dev_handle *udh);
104
105 void
106 usrp_one_time_init ()
107 {
108   static bool first = true;
109
110   if (first){
111     first = false;
112     usb_init ();                        // usb library init
113     usb_find_busses ();
114     usb_find_devices ();
115   }
116 }
117
118 void
119 usrp_rescan ()
120 {
121   usb_find_busses ();
122   usb_find_devices ();
123 }
124
125
126 // ----------------------------------------------------------------
127 // Danger, big, fragile KLUDGE.  The problem is that we want to be
128 // able to get from a usb_dev_handle back to a usb_device, and the
129 // right way to do this is buried in a non-installed include file.
130
131 static struct usb_device *
132 dev_handle_to_dev (usb_dev_handle *udh)
133 {
134   struct usb_dev_handle_kludge {
135     int                  fd;
136     struct usb_bus      *bus;
137     struct usb_device   *device;
138   };
139
140   return ((struct usb_dev_handle_kludge *) udh)->device;
141 }
142
143 // ----------------------------------------------------------------
144
145 /*
146  * q must be a real USRP, not an FX2.  Return its hardware rev number.
147  */
148 int
149 usrp_hw_rev (struct usb_device *q)
150 {
151   return q->descriptor.bcdDevice & 0x00FF;
152 }
153
154 /*
155  * q must be a real USRP, not an FX2.  Return true if it's configured.
156  */
157 static bool
158 _usrp_configured_p (struct usb_device *q)
159 {
160   return (q->descriptor.bcdDevice & 0xFF00) != 0;
161 }
162
163 bool
164 usrp_usrp_p (struct usb_device *q)
165 {
166   return (q->descriptor.idVendor == USB_VID_FSF
167           && q->descriptor.idProduct == USB_PID_FSF_USRP);
168 }
169
170 bool
171 usrp_fx2_p (struct usb_device *q)
172 {
173   return (q->descriptor.idVendor == USB_VID_CYPRESS
174           && q->descriptor.idProduct == USB_PID_CYPRESS_FX2);
175 }
176
177 bool
178 usrp_usrp0_p (struct usb_device *q)
179 {
180   return usrp_usrp_p (q) && usrp_hw_rev (q) == 0;
181 }
182
183 bool
184 usrp_usrp1_p (struct usb_device *q)
185 {
186   return usrp_usrp_p (q) && usrp_hw_rev (q) == 1;
187 }
188
189 bool
190 usrp_usrp2_p (struct usb_device *q)
191 {
192   return usrp_usrp_p (q) && usrp_hw_rev (q) == 2;
193 }
194
195
196 bool
197 usrp_unconfigured_usrp_p (struct usb_device *q)
198 {
199   return usrp_usrp_p (q) && !_usrp_configured_p (q);
200 }
201
202 bool
203 usrp_configured_usrp_p (struct usb_device *q)
204 {
205   return usrp_usrp_p (q) && _usrp_configured_p (q);
206 }
207
208 // ----------------------------------------------------------------
209
210 struct usb_device *
211 usrp_find_device (int nth, bool fx2_ok_p)
212 {
213   struct usb_bus *p;
214   struct usb_device *q;
215   int    n_found = 0;
216
217   usrp_one_time_init ();
218   
219   p = usb_get_busses();
220   while (p != NULL){
221     q = p->devices;
222     while (q != NULL){
223       if (usrp_usrp_p (q) || (fx2_ok_p && usrp_fx2_p (q))){
224         if (n_found == nth)     // return this one
225           return q;
226         n_found++;              // keep looking
227       }
228       q = q->next;
229     }
230     p = p->next;
231   }
232   return 0;     // not found
233 }
234
235 static struct usb_dev_handle *
236 usrp_open_interface (struct usb_device *dev, int interface, int altinterface)
237 {
238   struct usb_dev_handle *udh = usb_open (dev);
239   if (udh == 0)
240     return 0;
241
242   if (dev != dev_handle_to_dev (udh)){
243     fprintf (stderr, "%s:%d: internal error!\n", __FILE__, __LINE__);
244     abort ();
245   }
246
247 #if defined(_WIN32) || defined(__WIN32__) || defined(__CYGWIN__)
248   // There's no get get_configuration function, and with some of the newer kernels
249   // setting the configuration, even if to the same value, hoses any other processes
250   // that have it open.  Hence we opt to not set it at all (We've only
251   // got a single configuration anyway).  This may hose the win32 stuff...
252
253   // Appears to be required for libusb-win32 and Cygwin -- dew 09/20/06
254   if (usb_set_configuration (udh, 1) < 0){
255     /*
256      * Ignore this error.  
257      *
258      * Seems that something changed in drivers/usb/core/devio.c:proc_setconfig such that
259      * it returns -EBUSY if _any_ of the interfaces of a device are open.
260      * We've only got a single configuration, so setting it doesn't even seem
261      * like it should be required.
262      */
263   }
264 #endif
265
266   if (usb_claim_interface (udh, interface) < 0){
267     fprintf (stderr, "%s:usb_claim_interface: failed interface %d\n", __FUNCTION__,interface);
268     fprintf (stderr, "%s\n", usb_strerror());
269     usb_close (udh);
270     return 0;
271   }
272
273   if (usb_set_altinterface (udh, altinterface) < 0){
274     fprintf (stderr, "%s:usb_set_alt_interface: failed\n", __FUNCTION__);
275     fprintf (stderr, "%s\n", usb_strerror());
276     usb_release_interface (udh, interface);
277     usb_close (udh);
278     return 0;
279   }
280
281   return udh;
282 }
283
284 struct usb_dev_handle *
285 usrp_open_cmd_interface (struct usb_device *dev)
286 {
287   return usrp_open_interface (dev, USRP_CMD_INTERFACE, USRP_CMD_ALTINTERFACE);
288 }
289
290 struct usb_dev_handle *
291 usrp_open_rx_interface (struct usb_device *dev)
292 {
293   return usrp_open_interface (dev, USRP_RX_INTERFACE, USRP_RX_ALTINTERFACE);
294 }
295
296 struct usb_dev_handle *
297 usrp_open_tx_interface (struct usb_device *dev)
298 {
299   return usrp_open_interface (dev, USRP_TX_INTERFACE, USRP_TX_ALTINTERFACE);
300 }
301
302 bool
303 usrp_close_interface (struct usb_dev_handle *udh)
304 {
305   // we're assuming that closing an interface automatically releases it.
306   return usb_close (udh) == 0;
307 }
308
309 // ----------------------------------------------------------------
310 // write internal ram using Cypress vendor extension
311
312 static bool
313 write_internal_ram (struct usb_dev_handle *udh, unsigned char *buf,
314                     int start_addr, size_t len)
315 {
316   int addr;
317   int n;
318   int a;
319   int quanta = MAX_EP0_PKTSIZE;
320
321   for (addr = start_addr; addr < start_addr + (int) len; addr += quanta){
322     n = len + start_addr - addr;
323     if (n > quanta)
324       n = quanta;
325
326     a = usb_control_msg (udh, 0x40, 0xA0,
327                          addr, 0, (char *)(buf + (addr - start_addr)), n, 1000);
328
329     if (a < 0){
330       fprintf(stderr,"write_internal_ram failed: %s\n", usb_strerror());
331       return false;
332     }
333   }
334   return true;
335 }
336
337 // ----------------------------------------------------------------
338 // whack the CPUCS register using the upload RAM vendor extension
339
340 static bool
341 reset_cpu (struct usb_dev_handle *udh, bool reset_p)
342 {
343   unsigned char v;
344
345   if (reset_p)
346     v = 1;              // hold processor in reset
347   else
348     v = 0;              // release reset
349
350   return write_internal_ram (udh, &v, 0xE600, 1);
351 }
352
353 // ----------------------------------------------------------------
354 // Load intel format file into cypress FX2 (8051)
355
356 static bool
357 _usrp_load_firmware (struct usb_dev_handle *udh, const char *filename,
358                      unsigned char hash[USRP_HASH_SIZE])
359 {
360   FILE  *f = fopen (filename, "ra");
361   if (f == 0){
362     perror (filename);
363     return false;
364   }
365
366   if (!reset_cpu (udh, true))   // hold CPU in reset while loading firmware
367     goto fail;
368
369   
370   char s[1024];
371   int length;
372   int addr;
373   int type;
374   unsigned char data[256];
375   unsigned char checksum, a;
376   unsigned int b;
377   int i;
378
379   while (!feof(f)){
380     fgets(s, sizeof (s), f); /* we should not use more than 263 bytes normally */
381     if(s[0]!=':'){
382       fprintf(stderr,"%s: invalid line: \"%s\"\n", filename, s);
383       goto fail;
384     }
385     sscanf(s+1, "%02x", &length);
386     sscanf(s+3, "%04x", &addr);
387     sscanf(s+7, "%02x", &type);
388
389     if(type==0){
390
391       a=length+(addr &0xff)+(addr>>8)+type;
392       for(i=0;i<length;i++){
393         sscanf (s+9+i*2,"%02x", &b);
394         data[i]=b;
395         a=a+data[i];
396       }
397
398       sscanf (s+9+length*2,"%02x", &b);
399       checksum=b;
400       if (((a+checksum)&0xff)!=0x00){
401         fprintf (stderr, "  ** Checksum failed: got 0x%02x versus 0x%02x\n", (-a)&0xff, checksum);
402         goto fail;
403       }
404       if (!write_internal_ram (udh, data, addr, length))
405         goto fail;
406     }
407     else if (type == 0x01){      // EOF
408       break;
409     }
410     else if (type == 0x02){
411       fprintf(stderr, "Extended address: whatever I do with it?\n");
412       fprintf (stderr, "%s: invalid line: \"%s\"\n", filename, s);
413       goto fail;
414     }
415   }
416
417   // we jam the hash value into the FX2 memory before letting
418   // the cpu out of reset.  When it comes out of reset it
419   // may renumerate which will invalidate udh.
420
421   if (!usrp_set_hash (udh, FIRMWARE_HASH_SLOT, hash))
422     fprintf (stderr, "usrp: failed to write firmware hash slot\n");
423
424   if (!reset_cpu (udh, false))          // take CPU out of reset
425     goto fail;
426
427   fclose (f);
428   return true;
429
430  fail:
431   fclose (f);
432   return false;
433 }
434
435 // ----------------------------------------------------------------
436 // write vendor extension command to USRP
437
438 static int
439 write_cmd (struct usb_dev_handle *udh,
440            int request, int value, int index,
441            unsigned char *bytes, int len)
442 {
443   int   requesttype = (request & 0x80) ? VRT_VENDOR_IN : VRT_VENDOR_OUT;
444
445   int r = usb_control_msg (udh, requesttype, request, value, index,
446                            (char *) bytes, len, 1000);
447   if (r < 0){
448     // we get EPIPE if the firmware stalls the endpoint.
449     if (errno != EPIPE)
450       fprintf (stderr, "usb_control_msg failed: %s\n", usb_strerror ());
451   }
452
453   return r;
454 }
455
456 // ----------------------------------------------------------------
457 // load fpga
458
459 static bool
460 _usrp_load_fpga (struct usb_dev_handle *udh, const char *filename,
461                  unsigned char hash[USRP_HASH_SIZE])
462 {
463   bool ok = true;
464
465   FILE  *fp = fopen (filename, "rb");
466   if (fp == 0){
467     perror (filename);
468     return false;
469   }
470
471   unsigned char buf[MAX_EP0_PKTSIZE];   // 64 is max size of EP0 packet on FX2
472   int n;
473
474   usrp_set_led (udh, 1, 1);             // led 1 on
475
476
477   // reset FPGA (and on rev1 both AD9862's, thus killing clock)
478   usrp_set_fpga_reset (udh, 1);         // hold fpga in reset
479
480   if (write_cmd (udh, VRQ_FPGA_LOAD, 0, FL_BEGIN, 0, 0) != 0)
481     goto fail;
482   
483   while ((n = fread (buf, 1, sizeof (buf), fp)) > 0){
484     if (write_cmd (udh, VRQ_FPGA_LOAD, 0, FL_XFER, buf, n) != n)
485       goto fail;
486   }
487
488   if (write_cmd (udh, VRQ_FPGA_LOAD, 0, FL_END, 0, 0) != 0)
489     goto fail;
490   
491   fclose (fp);
492
493   if (!usrp_set_hash (udh, FPGA_HASH_SLOT, hash))
494     fprintf (stderr, "usrp: failed to write fpga hash slot\n");
495
496   // On the rev1 USRP, the {tx,rx}_{enable,reset} bits are
497   // controlled over the serial bus, and hence aren't observed until
498   // we've got a good fpga bitstream loaded.
499
500   usrp_set_fpga_reset (udh, 0);         // fpga out of master reset
501
502   // now these commands will work
503   
504   ok &= usrp_set_fpga_tx_enable (udh, 0);
505   ok &= usrp_set_fpga_rx_enable (udh, 0);
506
507   ok &= usrp_set_fpga_tx_reset (udh, 1);        // reset tx and rx paths
508   ok &= usrp_set_fpga_rx_reset (udh, 1);
509   ok &= usrp_set_fpga_tx_reset (udh, 0);        // reset tx and rx paths
510   ok &= usrp_set_fpga_rx_reset (udh, 0);
511
512   if (!ok)
513     fprintf (stderr, "usrp: failed to reset tx and/or rx path\n");
514
515   // Manually reset all regs except master control to zero.
516   // FIXME may want to remove this when we rework FPGA reset strategy.
517   // In the mean while, this gets us reproducible behavior.
518   for (int i = 0; i < FR_USER_0; i++){
519     if (i == FR_MASTER_CTRL)
520       continue;
521     usrp_write_fpga_reg(udh, i, 0);
522   }
523
524   power_down_9862s (udh);               // on the rev1, power these down!
525   usrp_set_led (udh, 1, 0);             // led 1 off
526
527   return true;
528
529  fail:
530   power_down_9862s (udh);               // on the rev1, power these down!
531   fclose (fp);
532   return false;
533 }
534
535 // ----------------------------------------------------------------
536
537 bool 
538 usrp_set_led (struct usb_dev_handle *udh, int which, bool on)
539 {
540   int r = write_cmd (udh, VRQ_SET_LED, on, which, 0, 0);
541
542   return r == 0;
543 }
544
545 bool
546 usrp_set_hash (struct usb_dev_handle *udh, int which,
547                const unsigned char hash[USRP_HASH_SIZE])
548 {
549   which &= 1;
550   
551   // we use the Cypress firmware down load command to jam it in.
552   int r = usb_control_msg (udh, 0x40, 0xa0, hash_slot_addr[which], 0,
553                            (char *) hash, USRP_HASH_SIZE, 1000);
554   return r == USRP_HASH_SIZE;
555 }
556
557 bool
558 usrp_get_hash (struct usb_dev_handle *udh, int which, 
559                unsigned char hash[USRP_HASH_SIZE])
560 {
561   which &= 1;
562   
563   // we use the Cypress firmware upload command to fetch it.
564   int r = usb_control_msg (udh, 0xc0, 0xa0, hash_slot_addr[which], 0,
565                            (char *) hash, USRP_HASH_SIZE, 1000);
566   return r == USRP_HASH_SIZE;
567 }
568
569 static bool
570 usrp_set_switch (struct usb_dev_handle *udh, int cmd_byte, bool on)
571 {
572   return write_cmd (udh, cmd_byte, on, 0, 0, 0) == 0;
573 }
574
575
576 static bool
577 usrp1_fpga_write (struct usb_dev_handle *udh,
578                   int regno, int value)
579 {
580   // on the rev1 usrp, we use the generic spi_write interface
581
582   unsigned char buf[4];
583
584   buf[0] = (value >> 24) & 0xff;        // MSB first
585   buf[1] = (value >> 16) & 0xff;
586   buf[2] = (value >>  8) & 0xff;
587   buf[3] = (value >>  0) & 0xff;
588   
589   return usrp_spi_write (udh, 0x00 | (regno & 0x7f),
590                          SPI_ENABLE_FPGA,
591                          SPI_FMT_MSB | SPI_FMT_HDR_1,
592                          buf, sizeof (buf));
593 }
594
595 static bool
596 usrp1_fpga_read (struct usb_dev_handle *udh,
597                  int regno, int *value)
598 {
599   *value = 0;
600   unsigned char buf[4];
601
602   bool ok = usrp_spi_read (udh, 0x80 | (regno & 0x7f),
603                            SPI_ENABLE_FPGA,
604                            SPI_FMT_MSB | SPI_FMT_HDR_1,
605                            buf, sizeof (buf));
606
607   if (ok)
608     *value = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
609
610   return ok;
611 }
612
613
614 bool
615 usrp_write_fpga_reg (struct usb_dev_handle *udh, int reg, int value)
616 {
617   switch (usrp_hw_rev (dev_handle_to_dev (udh))){
618   case 0:                       // not supported ;)
619     abort();    
620
621   default:
622     return usrp1_fpga_write (udh, reg, value);
623   }
624 }
625
626 bool
627 usrp_read_fpga_reg (struct usb_dev_handle *udh, int reg, int *value)
628 {
629   switch (usrp_hw_rev (dev_handle_to_dev (udh))){
630   case 0:               // not supported ;)
631     abort();
632     
633   default:
634     return usrp1_fpga_read (udh, reg, value);
635   }
636 }
637
638 bool 
639 usrp_set_fpga_reset (struct usb_dev_handle *udh, bool on)
640 {
641   return usrp_set_switch (udh, VRQ_FPGA_SET_RESET, on);
642 }
643
644 bool 
645 usrp_set_fpga_tx_enable (struct usb_dev_handle *udh, bool on)
646 {
647   return usrp_set_switch (udh, VRQ_FPGA_SET_TX_ENABLE, on);
648 }
649
650 bool 
651 usrp_set_fpga_rx_enable (struct usb_dev_handle *udh, bool on)
652 {
653   return usrp_set_switch (udh, VRQ_FPGA_SET_RX_ENABLE, on);
654 }
655
656 bool 
657 usrp_set_fpga_tx_reset (struct usb_dev_handle *udh, bool on)
658 {
659   return usrp_set_switch (udh, VRQ_FPGA_SET_TX_RESET, on);
660 }
661
662 bool 
663 usrp_set_fpga_rx_reset (struct usb_dev_handle *udh, bool on)
664 {
665   return usrp_set_switch (udh, VRQ_FPGA_SET_RX_RESET, on);
666 }
667
668
669 // ----------------------------------------------------------------
670 // conditional load stuff
671
672 static bool
673 compute_hash (const char *filename, unsigned char hash[USRP_HASH_SIZE])
674 {
675   assert (USRP_HASH_SIZE == 16);
676   memset (hash, 0, USRP_HASH_SIZE);
677
678   FILE *fp = fopen (filename, "rb");
679   if (fp == 0){
680     perror (filename);
681     return false;
682   }
683   int r = md5_stream (fp, hash);
684   fclose (fp);
685   
686   return r == 0;
687 }
688
689 static usrp_load_status_t
690 usrp_conditionally_load_something (struct usb_dev_handle *udh,
691                                    const char *filename,
692                                    bool force,
693                                    int slot,
694                                    bool loader (struct usb_dev_handle *,
695                                                 const char *,
696                                                 unsigned char [USRP_HASH_SIZE]))
697 {
698   unsigned char file_hash[USRP_HASH_SIZE];
699   unsigned char usrp_hash[USRP_HASH_SIZE];
700   
701   if (access (filename, R_OK) != 0){
702     perror (filename);
703     return ULS_ERROR;
704   }
705
706   if (!compute_hash (filename, file_hash))
707     return ULS_ERROR;
708
709   if (!force
710       && usrp_get_hash (udh, slot, usrp_hash)
711       && memcmp (file_hash, usrp_hash, USRP_HASH_SIZE) == 0)
712     return ULS_ALREADY_LOADED;
713
714   bool r = loader (udh, filename, file_hash);
715
716   if (!r)
717     return ULS_ERROR;
718
719   return ULS_OK;
720 }
721
722 usrp_load_status_t
723 usrp_load_firmware (struct usb_dev_handle *udh,
724                     const char *filename,
725                     bool force)
726 {
727   return usrp_conditionally_load_something (udh, filename, force,
728                                             FIRMWARE_HASH_SLOT,
729                                             _usrp_load_firmware);
730 }
731
732 usrp_load_status_t
733 usrp_load_fpga (struct usb_dev_handle *udh,
734                 const char *filename,
735                 bool force)
736 {
737   return usrp_conditionally_load_something (udh, filename, force,
738                                             FPGA_HASH_SLOT,
739                                             _usrp_load_fpga);
740 }
741
742 static usb_dev_handle *
743 open_nth_cmd_interface (int nth)
744 {
745   struct usb_device *udev = usrp_find_device (nth);
746   if (udev == 0){
747     fprintf (stderr, "usrp: failed to find usrp[%d]\n", nth);
748     return 0;
749   }
750
751   struct usb_dev_handle *udh;
752
753   udh = usrp_open_cmd_interface (udev);
754   if (udh == 0){
755     // FIXME this could be because somebody else has it open.
756     // We should delay and retry...
757     fprintf (stderr, "open_nth_cmd_interface: open_cmd_interface failed\n");
758     usb_strerror ();
759     return 0;
760   }
761
762   return udh;
763  }
764
765 static bool
766 our_nanosleep (const struct timespec *delay)
767 {
768   struct timespec       new_delay = *delay;
769   struct timespec       remainder;
770
771   while (1){
772     int r = nanosleep (&new_delay, &remainder);
773     if (r == 0)
774       return true;
775     if (errno == EINTR)
776       new_delay = remainder;
777     else {
778       perror ("nanosleep");
779       return false;
780     }
781   }
782 }
783
784 static bool
785 mdelay (int millisecs)
786 {
787   struct timespec       ts;
788   ts.tv_sec = millisecs / 1000;
789   ts.tv_nsec = (millisecs - (1000 * ts.tv_sec)) * 1000000;
790   return our_nanosleep (&ts);
791 }
792
793 usrp_load_status_t
794 usrp_load_firmware_nth (int nth, const char *filename, bool force){
795   struct usb_dev_handle *udh = open_nth_cmd_interface (nth);
796   if (udh == 0)
797     return ULS_ERROR;
798
799   usrp_load_status_t s = usrp_load_firmware (udh, filename, force);
800   usrp_close_interface (udh);
801
802   switch (s){
803
804   case ULS_ALREADY_LOADED:              // nothing changed...
805     return ULS_ALREADY_LOADED;
806     break;
807
808   case ULS_OK:
809     // we loaded firmware successfully.
810
811     // It's highly likely that the board will renumerate (simulate a
812     // disconnect/reconnect sequence), invalidating our current
813     // handle.
814
815     // FIXME.  Turn this into a loop that rescans until we refind ourselves
816     
817     struct timespec     t;      // delay for 1 second
818     t.tv_sec = 2;
819     t.tv_nsec = 0;
820     our_nanosleep (&t);
821
822     usb_find_busses ();         // rescan busses and devices
823     usb_find_devices ();
824
825     return ULS_OK;
826
827   default:
828   case ULS_ERROR:               // some kind of problem
829     return ULS_ERROR;
830   }
831 }
832
833 static void
834 load_status_msg (usrp_load_status_t s, const char *type, const char *filename)
835 {
836   char *e = getenv("USRP_VERBOSE");
837   bool verbose = e != 0;
838   
839   switch (s){
840   case ULS_ERROR:
841     fprintf (stderr, "usrp: failed to load %s %s.\n", type, filename);
842     break;
843     
844   case ULS_ALREADY_LOADED:
845     if (verbose)
846       fprintf (stderr, "usrp: %s %s already loaded.\n", type, filename);
847     break;
848
849   case ULS_OK:
850     if (verbose)
851       fprintf (stderr, "usrp: %s %s loaded successfully.\n", type, filename);
852     break;
853   }
854 }
855
856 bool
857 usrp_load_standard_bits (int nth, bool force,
858                          const std::string fpga_filename,
859                          const std::string firmware_filename)
860 {
861   usrp_load_status_t    s;
862   const char            *filename;
863   const char            *proto_filename;
864   int hw_rev;
865
866   // first, figure out what hardware rev we're dealing with
867   {
868     struct usb_device *udev = usrp_find_device (nth);
869     if (udev == 0){
870       fprintf (stderr, "usrp: failed to find usrp[%d]\n", nth);
871       return false;
872     }
873     hw_rev = usrp_hw_rev (udev);
874   }
875
876   // start by loading the firmware
877
878   proto_filename = get_proto_filename(firmware_filename, "USRP_FIRMWARE",
879                                       default_firmware_filename);
880   filename = find_file(proto_filename, hw_rev);
881   if (filename == 0){
882     fprintf (stderr, "Can't find firmware: %s\n", proto_filename);
883     return false;
884   }
885
886   s = usrp_load_firmware_nth (nth, filename, force);
887   load_status_msg (s, "firmware", filename);
888
889   if (s == ULS_ERROR)
890     return false;
891
892   // if we actually loaded firmware, we must reload fpga ...
893   if (s == ULS_OK)
894     force = true;
895
896   // now move on to the fpga configuration bitstream
897
898   proto_filename = get_proto_filename(fpga_filename, "USRP_FPGA",
899                                       default_fpga_filename);
900   filename = find_file (proto_filename, hw_rev);
901   if (filename == 0){
902     fprintf (stderr, "Can't find fpga bitstream: %s\n", proto_filename);
903     return false;
904   }
905
906   struct usb_dev_handle *udh = open_nth_cmd_interface (nth);
907   if (udh == 0)
908     return false;
909   
910   s = usrp_load_fpga (udh, filename, force);
911   usrp_close_interface (udh);
912   load_status_msg (s, "fpga bitstream", filename);
913
914   if (s == ULS_ERROR)
915     return false;
916
917   return true;
918 }
919
920 bool
921 _usrp_get_status (struct usb_dev_handle *udh, int which, bool *trouble)
922 {
923   unsigned char status;
924   *trouble = true;
925   
926   if (write_cmd (udh, VRQ_GET_STATUS, 0, which,
927                  &status, sizeof (status)) != sizeof (status))
928     return false;
929
930   *trouble = status;
931   return true;
932 }
933
934 bool
935 usrp_check_rx_overrun (struct usb_dev_handle *udh, bool *overrun_p)
936 {
937   return _usrp_get_status (udh, GS_RX_OVERRUN, overrun_p);
938 }
939
940 bool
941 usrp_check_tx_underrun (struct usb_dev_handle *udh, bool *underrun_p)
942 {
943   return _usrp_get_status (udh, GS_TX_UNDERRUN, underrun_p);
944 }
945
946
947 bool
948 usrp_i2c_write (struct usb_dev_handle *udh, int i2c_addr,
949                 const void *buf, int len)
950 {
951   if (len < 1 || len > MAX_EP0_PKTSIZE)
952     return false;
953
954   return write_cmd (udh, VRQ_I2C_WRITE, i2c_addr, 0,
955                     (unsigned char *) buf, len) == len;
956 }
957
958
959 bool
960 usrp_i2c_read (struct usb_dev_handle *udh, int i2c_addr,
961                void *buf, int len)
962 {
963   if (len < 1 || len > MAX_EP0_PKTSIZE)
964     return false;
965
966   return write_cmd (udh, VRQ_I2C_READ, i2c_addr, 0,
967                     (unsigned char *) buf, len) == len;
968 }
969
970 bool
971 usrp_spi_write (struct usb_dev_handle *udh,
972                 int optional_header, int enables, int format,
973                 const void *buf, int len)
974 {
975   if (len < 0 || len > MAX_EP0_PKTSIZE)
976     return false;
977
978   return write_cmd (udh, VRQ_SPI_WRITE,
979                     optional_header,
980                     ((enables & 0xff) << 8) | (format & 0xff),
981                     (unsigned char *) buf, len) == len;
982 }
983
984
985 bool
986 usrp_spi_read (struct usb_dev_handle *udh,
987                int optional_header, int enables, int format,
988                void *buf, int len)
989 {
990   if (len < 0 || len > MAX_EP0_PKTSIZE)
991     return false;
992
993   return write_cmd (udh, VRQ_SPI_READ,
994                     optional_header,
995                     ((enables & 0xff) << 8) | (format & 0xff),
996                     (unsigned char *) buf, len) == len;
997 }
998
999 bool
1000 usrp_9862_write (struct usb_dev_handle *udh, int which_codec,
1001                  int regno, int value)
1002 {
1003   if (0)
1004     fprintf (stderr, "usrp_9862_write which = %d, reg = %2d, val = %3d (0x%02x)\n",
1005              which_codec, regno, value, value);
1006
1007   unsigned char buf[1];
1008
1009   buf[0] = value;
1010   
1011   return usrp_spi_write (udh, 0x00 | (regno & 0x3f),
1012                          which_codec == 0 ? SPI_ENABLE_CODEC_A : SPI_ENABLE_CODEC_B,
1013                          SPI_FMT_MSB | SPI_FMT_HDR_1,
1014                          buf, 1);
1015 }
1016
1017 bool
1018 usrp_9862_read (struct usb_dev_handle *udh, int which_codec,
1019                 int regno, unsigned char *value)
1020 {
1021   return usrp_spi_read (udh, 0x80 | (regno & 0x3f),
1022                         which_codec == 0 ? SPI_ENABLE_CODEC_A : SPI_ENABLE_CODEC_B,
1023                         SPI_FMT_MSB | SPI_FMT_HDR_1,
1024                         value, 1);
1025 }
1026
1027 bool
1028 usrp_9862_write_many (struct usb_dev_handle *udh,
1029                       int which_codec,
1030                       const unsigned char *buf,
1031                       int len)
1032 {
1033   if (len & 0x1)
1034     return false;               // must be even
1035
1036   bool result = true;
1037
1038   while (len > 0){
1039     result &= usrp_9862_write (udh, which_codec, buf[0], buf[1]);
1040     len -= 2;
1041     buf += 2;
1042   }
1043
1044   return result;
1045 }
1046
1047
1048 bool
1049 usrp_9862_write_many_all (struct usb_dev_handle *udh,
1050                            const unsigned char *buf, int len)
1051 {
1052   // FIXME handle 2/2 and 4/4 versions
1053
1054   bool result;
1055   result  = usrp_9862_write_many (udh, 0, buf, len);
1056   result &= usrp_9862_write_many (udh, 1, buf, len);
1057   return result;
1058 }
1059
1060 static void
1061 power_down_9862s (struct usb_dev_handle *udh)
1062 {
1063   static const unsigned char regs[] = {
1064     REG_RX_PWR_DN,      0x01,                   // everything
1065     REG_TX_PWR_DN,      0x0f,                   // pwr dn digital and analog_both
1066     REG_TX_MODULATOR,   0x00                    // coarse & fine modulators disabled
1067   };
1068
1069   switch (usrp_hw_rev (dev_handle_to_dev (udh))){
1070   case 0:
1071     break;
1072
1073   default:
1074     usrp_9862_write_many_all (udh, regs, sizeof (regs));
1075     break;
1076   }
1077 }
1078
1079
1080
1081 static const int EEPROM_PAGESIZE = 16;
1082
1083 bool
1084 usrp_eeprom_write (struct usb_dev_handle *udh, int i2c_addr,
1085                    int eeprom_offset, const void *buf, int len)
1086 {
1087   unsigned char cmd[2];
1088   const unsigned char *p = (unsigned char *) buf;
1089   
1090   // The simplest thing that could possibly work:
1091   //   all writes are single byte writes.
1092   //
1093   // We could speed this up using the page write feature,
1094   // but we write so infrequently, why bother...
1095
1096   while (len-- > 0){
1097     cmd[0] = eeprom_offset++;
1098     cmd[1] = *p++;
1099     bool r = usrp_i2c_write (udh, i2c_addr, cmd, sizeof (cmd));
1100     mdelay (10);                // delay 10ms worst case write time
1101     if (!r)
1102       return false;
1103   }
1104   
1105   return true;
1106 }
1107
1108 bool
1109 usrp_eeprom_read (struct usb_dev_handle *udh, int i2c_addr,
1110                   int eeprom_offset, void *buf, int len)
1111 {
1112   unsigned char *p = (unsigned char *) buf;
1113
1114   // We setup a random read by first doing a "zero byte write".
1115   // Writes carry an address.  Reads use an implicit address.
1116
1117   unsigned char cmd[1];
1118   cmd[0] = eeprom_offset;
1119   if (!usrp_i2c_write (udh, i2c_addr, cmd, sizeof (cmd)))
1120     return false;
1121
1122   while (len > 0){
1123     int n = std::min (len, MAX_EP0_PKTSIZE);
1124     if (!usrp_i2c_read (udh, i2c_addr, p, n))
1125       return false;
1126     len -= n;
1127     p += n;
1128   }
1129   return true;
1130 }
1131  
1132 // ----------------------------------------------------------------
1133
1134 static bool
1135 slot_to_codec (int slot, int *which_codec)
1136 {
1137   *which_codec = 0;
1138   
1139   switch (slot){
1140   case SLOT_TX_A:
1141   case SLOT_RX_A:
1142     *which_codec = 0;
1143     break;
1144
1145   case SLOT_TX_B:
1146   case SLOT_RX_B:
1147     *which_codec = 1;
1148     break;
1149
1150   default:
1151     fprintf (stderr, "usrp_prims:slot_to_codec: invalid slot = %d\n", slot);
1152     return false;
1153   }
1154   return true;
1155 }
1156
1157 static bool
1158 tx_slot_p (int slot)
1159 {
1160   switch (slot){
1161   case SLOT_TX_A:
1162   case SLOT_TX_B:
1163     return true;
1164
1165   default:
1166     return false;
1167   }
1168 }
1169
1170 bool
1171 usrp_write_aux_dac (struct usb_dev_handle *udh, int slot,
1172                     int which_dac, int value)
1173 {
1174   int which_codec;
1175   
1176   if (!slot_to_codec (slot, &which_codec))
1177     return false;
1178
1179   if (!(0 <= which_dac && which_dac < 4)){
1180     fprintf (stderr, "usrp_write_aux_dac: invalid dac = %d\n", which_dac);
1181     return false;
1182   }
1183
1184   value &= 0x0fff;      // mask to 12-bits
1185   
1186   if (which_dac == 3){
1187     // dac 3 is really 12-bits.  Use value as is.
1188     bool r = true;
1189     r &= usrp_9862_write (udh, which_codec, 43, (value >> 4));       // most sig
1190     r &= usrp_9862_write (udh, which_codec, 42, (value & 0xf) << 4); // least sig
1191     return r;
1192   }
1193   else {
1194     // dac 0, 1, and 2 are really 8 bits.  
1195     value = value >> 4;         // shift value appropriately
1196     return usrp_9862_write (udh, which_codec, 36 + which_dac, value);
1197   }
1198 }
1199
1200
1201 bool
1202 usrp_read_aux_adc (struct usb_dev_handle *udh, int slot,
1203                    int which_adc, int *value)
1204 {
1205   *value = 0;
1206   int   which_codec;
1207
1208   if (!slot_to_codec (slot, &which_codec))
1209     return false;
1210
1211   if (!(0 <= which_codec && which_codec < 2)){
1212     fprintf (stderr, "usrp_read_aux_adc: invalid adc = %d\n", which_adc);
1213     return false;
1214   }
1215
1216   unsigned char aux_adc_control =
1217     AUX_ADC_CTRL_REFSEL_A               // on chip reference
1218     | AUX_ADC_CTRL_REFSEL_B;            // on chip reference
1219
1220   int   rd_reg = 26;    // base address of two regs to read for result
1221   
1222   // program the ADC mux bits
1223   if (tx_slot_p (slot))
1224     aux_adc_control |= AUX_ADC_CTRL_SELECT_A2 | AUX_ADC_CTRL_SELECT_B2;
1225   else {
1226     rd_reg += 2;
1227     aux_adc_control |= AUX_ADC_CTRL_SELECT_A1 | AUX_ADC_CTRL_SELECT_B1;
1228   }
1229   
1230   // I'm not sure if we can set the mux and issue a start conversion
1231   // in the same cycle, so let's do them one at a time.
1232
1233   usrp_9862_write (udh, which_codec, 34, aux_adc_control);
1234
1235   if (which_adc == 0)
1236     aux_adc_control |= AUX_ADC_CTRL_START_A;
1237   else {
1238     rd_reg += 4;
1239     aux_adc_control |= AUX_ADC_CTRL_START_B;
1240   }
1241
1242   // start the conversion
1243   usrp_9862_write (udh, which_codec, 34, aux_adc_control);
1244
1245   // read the 10-bit result back
1246   unsigned char v_lo = 0;
1247   unsigned char v_hi = 0;
1248   bool r = usrp_9862_read (udh, which_codec, rd_reg, &v_lo);
1249   r &= usrp_9862_read (udh, which_codec, rd_reg + 1, &v_hi);
1250
1251   if (r)
1252     *value = ((v_hi << 2) | ((v_lo >> 6) & 0x3)) << 2;  // format as 12-bit
1253   
1254   return r;
1255 }
1256
1257 // ----------------------------------------------------------------
1258
1259 static int slot_to_i2c_addr (int slot)
1260 {
1261   switch (slot){
1262   case SLOT_TX_A:       return I2C_ADDR_TX_A;
1263   case SLOT_RX_A:       return I2C_ADDR_RX_A;
1264   case SLOT_TX_B:       return I2C_ADDR_TX_B;
1265   case SLOT_RX_B:       return I2C_ADDR_RX_B;
1266   default:              return -1;
1267   }
1268 }
1269
1270 static void
1271 set_chksum (unsigned char *buf)
1272 {
1273   int sum = 0;
1274   unsigned int i;
1275   for (i = 0; i < DB_EEPROM_CLEN - 1; i++)
1276     sum += buf[i];
1277   buf[i] = -sum;
1278 }
1279
1280 static usrp_dbeeprom_status_t
1281 read_dboard_eeprom (struct usb_dev_handle *udh,
1282                     int slot_id, unsigned char *buf)
1283 {
1284   int i2c_addr = slot_to_i2c_addr (slot_id);
1285   if (i2c_addr == -1)
1286     return UDBE_BAD_SLOT;
1287
1288   if (!usrp_eeprom_read (udh, i2c_addr, 0, buf, DB_EEPROM_CLEN))
1289     return UDBE_NO_EEPROM;
1290
1291   if (buf[DB_EEPROM_MAGIC] != DB_EEPROM_MAGIC_VALUE)
1292     return UDBE_INVALID_EEPROM;
1293
1294   int sum = 0;
1295   for (unsigned int i = 0; i < DB_EEPROM_CLEN; i++)
1296     sum += buf[i];
1297
1298   if ((sum & 0xff) != 0)
1299     return UDBE_INVALID_EEPROM;
1300
1301   return UDBE_OK;
1302 }
1303
1304 usrp_dbeeprom_status_t
1305 usrp_read_dboard_eeprom (struct usb_dev_handle *udh,
1306                          int slot_id, usrp_dboard_eeprom *eeprom)
1307 {
1308   unsigned char buf[DB_EEPROM_CLEN];
1309
1310   memset (eeprom, 0, sizeof (*eeprom));
1311
1312   usrp_dbeeprom_status_t s = read_dboard_eeprom (udh, slot_id, buf);
1313   if (s != UDBE_OK)
1314     return s;
1315
1316   eeprom->id = (buf[DB_EEPROM_ID_MSB] << 8) | buf[DB_EEPROM_ID_LSB];
1317   eeprom->oe = (buf[DB_EEPROM_OE_MSB] << 8) | buf[DB_EEPROM_OE_LSB];
1318   eeprom->offset[0] = (buf[DB_EEPROM_OFFSET_0_MSB] << 8) | buf[DB_EEPROM_OFFSET_0_LSB];
1319   eeprom->offset[1] = (buf[DB_EEPROM_OFFSET_1_MSB] << 8) | buf[DB_EEPROM_OFFSET_1_LSB];
1320
1321   return UDBE_OK;
1322 }
1323
1324 bool
1325 usrp_write_dboard_offsets (struct usb_dev_handle *udh, int slot_id,
1326                            short offset0, short offset1)
1327 {
1328   unsigned char buf[DB_EEPROM_CLEN];
1329
1330   usrp_dbeeprom_status_t s = read_dboard_eeprom (udh, slot_id, buf);
1331   if (s != UDBE_OK)
1332     return false;
1333
1334   buf[DB_EEPROM_OFFSET_0_LSB] = (offset0 >> 0) & 0xff;
1335   buf[DB_EEPROM_OFFSET_0_MSB] = (offset0 >> 8) & 0xff;
1336   buf[DB_EEPROM_OFFSET_1_LSB] = (offset1 >> 0) & 0xff;
1337   buf[DB_EEPROM_OFFSET_1_MSB] = (offset1 >> 8) & 0xff;
1338   set_chksum (buf);
1339
1340   return usrp_eeprom_write (udh, slot_to_i2c_addr (slot_id),
1341                             0, buf, sizeof (buf));
1342 }
1343
1344 std::string
1345 usrp_serial_number(struct usb_dev_handle *udh)
1346 {
1347   u_int8_t iserial = usb_device(udh)->descriptor.iSerialNumber;
1348   if (iserial == 0)
1349     return "";
1350
1351   char buf[1024];
1352   if (usb_get_string_simple(udh, iserial, buf, sizeof(buf)) < 0)
1353     return "";
1354
1355   return buf;
1356 }