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