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