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