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