usrp: Fixed firmware load regression
[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 2 second
696     t.tv_sec = 2;
697     t.tv_nsec = 0;
698     our_nanosleep (&t);
699
700     usrp_rescan ();
701
702     return ULS_OK;
703
704   default:
705   case ULS_ERROR:               // some kind of problem
706     return ULS_ERROR;
707   }
708 }
709
710 static void
711 load_status_msg (usrp_load_status_t s, const char *type, const char *filename)
712 {
713   char *e = getenv("USRP_VERBOSE");
714   bool verbose = e != 0;
715
716   switch (s){
717   case ULS_ERROR:
718     fprintf (stderr, "usrp: failed to load %s %s.\n", type, filename);
719     break;
720
721   case ULS_ALREADY_LOADED:
722     if (verbose)
723       fprintf (stderr, "usrp: %s %s already loaded.\n", type, filename);
724     break;
725
726   case ULS_OK:
727     if (verbose)
728       fprintf (stderr, "usrp: %s %s loaded successfully.\n", type, filename);
729     break;
730   }
731 }
732
733 bool
734 usrp_load_standard_bits (int nth, bool force,
735                          const std::string fpga_filename,
736                          const std::string firmware_filename,
737                          libusb_context *ctx)
738 {
739   usrp_load_status_t    s;
740   const char            *filename;
741   const char            *proto_filename;
742   int hw_rev;
743
744   // first, figure out what hardware rev we're dealing with
745   {
746     libusb_device *udev = usrp_find_device (nth, false, ctx);
747     if (udev == 0){
748       fprintf (stderr, "usrp: failed to find usrp[%d]\n", nth);
749       return false;
750     }
751     hw_rev = usrp_hw_rev (udev);
752   }
753
754   // start by loading the firmware
755
756   proto_filename = get_proto_filename(firmware_filename, "USRP_FIRMWARE",
757                                       default_firmware_filename);
758   filename = find_file(proto_filename, hw_rev);
759   if (filename == 0){
760     fprintf (stderr, "Can't find firmware: %s\n", proto_filename);
761     return false;
762   }
763   s = usrp_load_firmware_nth (nth, filename, force, ctx);
764   load_status_msg (s, "firmware", filename);
765
766   if (s == ULS_ERROR)
767     return false;
768
769   // if we actually loaded firmware, we must reload fpga ...
770   if (s == ULS_OK)
771     force = true;
772
773   // now move on to the fpga configuration bitstream
774
775   proto_filename = get_proto_filename(fpga_filename, "USRP_FPGA",
776                                       default_fpga_filename);
777   filename = find_file (proto_filename, hw_rev);
778   if (filename == 0){
779     fprintf (stderr, "Can't find fpga bitstream: %s\n", proto_filename);
780     return false;
781   }
782   libusb_device_handle *udh = open_nth_cmd_interface (nth, ctx);
783   if (udh == 0)
784     return false;
785
786   s = usrp_load_fpga (udh, filename, force);
787   usrp_close_interface (udh);
788   load_status_msg (s, "fpga bitstream", filename);
789
790   if (s == ULS_ERROR)
791     return false;
792
793   return true;
794 }
795
796
797 bool
798 _usrp_get_status (libusb_device_handle *udh, int which, bool *trouble)
799 {
800   unsigned char status;
801   *trouble = true;
802
803   if (write_cmd (udh, VRQ_GET_STATUS, 0, which,
804                  &status, sizeof (status)) != sizeof (status))
805     return false;
806
807   *trouble = status;
808   return true;
809 }
810
811 bool
812 usrp_check_rx_overrun (libusb_device_handle *udh, bool *overrun_p)
813 {
814   return _usrp_get_status (udh, GS_RX_OVERRUN, overrun_p);
815 }
816
817 bool
818 usrp_check_tx_underrun (libusb_device_handle *udh, bool *underrun_p)
819 {
820   return _usrp_get_status (udh, GS_TX_UNDERRUN, underrun_p);
821 }
822
823
824 bool
825 usrp_i2c_write (libusb_device_handle *udh, int i2c_addr,
826                 const void *buf, int len)
827 {
828   if (len < 1 || len > MAX_EP0_PKTSIZE)
829     return false;
830
831   return write_cmd (udh, VRQ_I2C_WRITE, i2c_addr, 0,
832                     (unsigned char *) buf, len) == len;
833 }
834
835
836 bool
837 usrp_i2c_read (libusb_device_handle *udh, int i2c_addr,
838                void *buf, int len)
839 {
840   if (len < 1 || len > MAX_EP0_PKTSIZE)
841     return false;
842
843   return write_cmd (udh, VRQ_I2C_READ, i2c_addr, 0,
844                     (unsigned char *) buf, len) == len;
845 }
846
847 bool
848 usrp_spi_write (libusb_device_handle *udh,
849                 int optional_header, int enables, int format,
850                 const void *buf, int len)
851 {
852   if (len < 0 || len > MAX_EP0_PKTSIZE)
853     return false;
854
855   return write_cmd (udh, VRQ_SPI_WRITE,
856                     optional_header,
857                     ((enables & 0xff) << 8) | (format & 0xff),
858                     (unsigned char *) buf, len) == len;
859 }
860
861
862 bool
863 usrp_spi_read (libusb_device_handle *udh,
864                int optional_header, int enables, int format,
865                void *buf, int len)
866 {
867   if (len < 0 || len > MAX_EP0_PKTSIZE)
868     return false;
869
870   return write_cmd (udh, VRQ_SPI_READ,
871                     optional_header,
872                     ((enables & 0xff) << 8) | (format & 0xff),
873                     (unsigned char *) buf, len) == len;
874 }
875
876 bool
877 usrp_9862_write (libusb_device_handle *udh, int which_codec,
878                  int regno, int value)
879 {
880   if (0)
881     fprintf (stderr, "usrp_9862_write which = %d, reg = %2d, val = %3d (0x%02x)\n",
882              which_codec, regno, value, value);
883
884   unsigned char buf[1];
885
886   buf[0] = value;
887
888   return usrp_spi_write (udh, 0x00 | (regno & 0x3f),
889                          which_codec == 0 ? SPI_ENABLE_CODEC_A : SPI_ENABLE_CODEC_B,
890                          SPI_FMT_MSB | SPI_FMT_HDR_1,
891                          buf, 1);
892 }
893
894 bool
895 usrp_9862_read (libusb_device_handle *udh, int which_codec,
896                 int regno, unsigned char *value)
897 {
898   return usrp_spi_read (udh, 0x80 | (regno & 0x3f),
899                         which_codec == 0 ? SPI_ENABLE_CODEC_A : SPI_ENABLE_CODEC_B,
900                         SPI_FMT_MSB | SPI_FMT_HDR_1,
901                         value, 1);
902 }
903
904 bool
905 usrp_9862_write_many (libusb_device_handle *udh,
906                       int which_codec,
907                       const unsigned char *buf,
908                       int len)
909 {
910   if (len & 0x1)
911     return false;               // must be even
912
913   bool result = true;
914
915   while (len > 0){
916     result &= usrp_9862_write (udh, which_codec, buf[0], buf[1]);
917     len -= 2;
918     buf += 2;
919   }
920
921   return result;
922 }
923
924
925 bool
926 usrp_9862_write_many_all (libusb_device_handle *udh,
927                            const unsigned char *buf, int len)
928 {
929   // FIXME handle 2/2 and 4/4 versions
930
931   bool result;
932   result  = usrp_9862_write_many (udh, 0, buf, len);
933   result &= usrp_9862_write_many (udh, 1, buf, len);
934   return result;
935 }
936
937 static void
938 power_down_9862s (libusb_device_handle *udh)
939 {
940   static const unsigned char regs[] = {
941     REG_RX_PWR_DN,      0x01,           // everything
942     REG_TX_PWR_DN,      0x0f,           // pwr dn digital and analog_both
943     REG_TX_MODULATOR,   0x00            // coarse & fine modulators disabled
944   };
945
946   switch (usrp_hw_rev (_get_usb_device (udh))){
947   case 0:
948     break;
949
950   default:
951     usrp_9862_write_many_all (udh, regs, sizeof (regs));
952     break;
953   }
954 }
955
956
957 static const int EEPROM_PAGESIZE = 16;
958
959 bool
960 usrp_eeprom_write (libusb_device_handle *udh, int i2c_addr,
961                    int eeprom_offset, const void *buf, int len)
962 {
963   unsigned char cmd[2];
964   const unsigned char *p = (unsigned char *) buf;
965
966   // The simplest thing that could possibly work:
967   //   all writes are single byte writes.
968   //
969   // We could speed this up using the page write feature,
970   // but we write so infrequently, why bother...
971
972   while (len-- > 0){
973     cmd[0] = eeprom_offset++;
974     cmd[1] = *p++;
975     bool r = usrp_i2c_write (udh, i2c_addr, cmd, sizeof (cmd));
976     mdelay (10);                // delay 10ms worst case write time
977     if (!r)
978       return false;
979   }
980
981   return true;
982 }
983
984 bool
985 usrp_eeprom_read (libusb_device_handle *udh, int i2c_addr,
986                   int eeprom_offset, void *buf, int len)
987 {
988   unsigned char *p = (unsigned char *) buf;
989
990   // We setup a random read by first doing a "zero byte write".
991   // Writes carry an address.  Reads use an implicit address.
992
993   unsigned char cmd[1];
994   cmd[0] = eeprom_offset;
995   if (!usrp_i2c_write (udh, i2c_addr, cmd, sizeof (cmd)))
996     return false;
997
998   while (len > 0){
999     int n = std::min (len, MAX_EP0_PKTSIZE);
1000     if (!usrp_i2c_read (udh, i2c_addr, p, n))
1001       return false;
1002     len -= n;
1003     p += n;
1004   }
1005   return true;
1006 }
1007
1008 // ----------------------------------------------------------------
1009
1010 static bool
1011 slot_to_codec (int slot, int *which_codec)
1012 {
1013   *which_codec = 0;
1014
1015   switch (slot){
1016   case SLOT_TX_A:
1017   case SLOT_RX_A:
1018     *which_codec = 0;
1019     break;
1020
1021   case SLOT_TX_B:
1022   case SLOT_RX_B:
1023     *which_codec = 1;
1024     break;
1025
1026   default:
1027     fprintf (stderr, "usrp_prims:slot_to_codec: invalid slot = %d\n", slot);
1028     return false;
1029   }
1030   return true;
1031 }
1032
1033 static bool
1034 tx_slot_p (int slot)
1035 {
1036   switch (slot){
1037   case SLOT_TX_A:
1038   case SLOT_TX_B:
1039     return true;
1040
1041   default:
1042     return false;
1043   }
1044 }
1045
1046 bool
1047 usrp_write_aux_dac (libusb_device_handle *udh, int slot,
1048                     int which_dac, int value)
1049 {
1050   int which_codec;
1051
1052   if (!slot_to_codec (slot, &which_codec))
1053     return false;
1054
1055   if (!(0 <= which_dac && which_dac < 4)){
1056     fprintf (stderr, "usrp_write_aux_dac: invalid dac = %d\n", which_dac);
1057     return false;
1058   }
1059
1060   value &= 0x0fff;      // mask to 12-bits
1061
1062   if (which_dac == 3){
1063     // dac 3 is really 12-bits.  Use value as is.
1064     bool r = true;
1065     r &= usrp_9862_write (udh, which_codec, 43, (value >> 4));       // most sig
1066     r &= usrp_9862_write (udh, which_codec, 42, (value & 0xf) << 4); // least sig
1067     return r;
1068   }
1069   else {
1070     // dac 0, 1, and 2 are really 8 bits.
1071     value = value >> 4;         // shift value appropriately
1072     return usrp_9862_write (udh, which_codec, 36 + which_dac, value);
1073   }
1074 }
1075
1076
1077 bool
1078 usrp_read_aux_adc (libusb_device_handle *udh, int slot,
1079                    int which_adc, int *value)
1080 {
1081   *value = 0;
1082   int   which_codec;
1083
1084   if (!slot_to_codec (slot, &which_codec))
1085     return false;
1086
1087   if (!(0 <= which_codec && which_codec < 2)){
1088     fprintf (stderr, "usrp_read_aux_adc: invalid adc = %d\n", which_adc);
1089     return false;
1090   }
1091
1092   unsigned char aux_adc_control =
1093     AUX_ADC_CTRL_REFSEL_A               // on chip reference
1094     | AUX_ADC_CTRL_REFSEL_B;            // on chip reference
1095
1096   int   rd_reg = 26;    // base address of two regs to read for result
1097
1098   // program the ADC mux bits
1099   if (tx_slot_p (slot))
1100     aux_adc_control |= AUX_ADC_CTRL_SELECT_A2 | AUX_ADC_CTRL_SELECT_B2;
1101   else {
1102     rd_reg += 2;
1103     aux_adc_control |= AUX_ADC_CTRL_SELECT_A1 | AUX_ADC_CTRL_SELECT_B1;
1104   }
1105
1106   // I'm not sure if we can set the mux and issue a start conversion
1107   // in the same cycle, so let's do them one at a time.
1108
1109   usrp_9862_write (udh, which_codec, 34, aux_adc_control);
1110
1111   if (which_adc == 0)
1112     aux_adc_control |= AUX_ADC_CTRL_START_A;
1113   else {
1114     rd_reg += 4;
1115     aux_adc_control |= AUX_ADC_CTRL_START_B;
1116   }
1117
1118   // start the conversion
1119   usrp_9862_write (udh, which_codec, 34, aux_adc_control);
1120
1121   // read the 10-bit result back
1122   unsigned char v_lo = 0;
1123   unsigned char v_hi = 0;
1124   bool r = usrp_9862_read (udh, which_codec, rd_reg, &v_lo);
1125   r &= usrp_9862_read (udh, which_codec, rd_reg + 1, &v_hi);
1126
1127   if (r)
1128     *value = ((v_hi << 2) | ((v_lo >> 6) & 0x3)) << 2;  // format as 12-bit
1129
1130   return r;
1131 }
1132
1133 // ----------------------------------------------------------------
1134
1135 static int slot_to_i2c_addr (int slot)
1136 {
1137   switch (slot){
1138   case SLOT_TX_A:       return I2C_ADDR_TX_A;
1139   case SLOT_RX_A:       return I2C_ADDR_RX_A;
1140   case SLOT_TX_B:       return I2C_ADDR_TX_B;
1141   case SLOT_RX_B:       return I2C_ADDR_RX_B;
1142   default:              return -1;
1143   }
1144 }
1145
1146 static void
1147 set_chksum (unsigned char *buf)
1148 {
1149   int sum = 0;
1150   unsigned int i;
1151   for (i = 0; i < DB_EEPROM_CLEN - 1; i++)
1152     sum += buf[i];
1153   buf[i] = -sum;
1154 }
1155
1156 static usrp_dbeeprom_status_t
1157 read_dboard_eeprom (libusb_device_handle *udh,
1158                     int slot_id, unsigned char *buf)
1159 {
1160   int i2c_addr = slot_to_i2c_addr (slot_id);
1161   if (i2c_addr == -1)
1162     return UDBE_BAD_SLOT;
1163
1164   if (!usrp_eeprom_read (udh, i2c_addr, 0, buf, DB_EEPROM_CLEN))
1165     return UDBE_NO_EEPROM;
1166
1167   if (buf[DB_EEPROM_MAGIC] != DB_EEPROM_MAGIC_VALUE)
1168     return UDBE_INVALID_EEPROM;
1169
1170   int sum = 0;
1171   for (unsigned int i = 0; i < DB_EEPROM_CLEN; i++)
1172     sum += buf[i];
1173
1174   if ((sum & 0xff) != 0)
1175     return UDBE_INVALID_EEPROM;
1176
1177   return UDBE_OK;
1178 }
1179
1180 usrp_dbeeprom_status_t
1181 usrp_read_dboard_eeprom (libusb_device_handle *udh,
1182                          int slot_id, usrp_dboard_eeprom *eeprom)
1183 {
1184   unsigned char buf[DB_EEPROM_CLEN];
1185
1186   memset (eeprom, 0, sizeof (*eeprom));
1187
1188   usrp_dbeeprom_status_t s = read_dboard_eeprom (udh, slot_id, buf);
1189   if (s != UDBE_OK)
1190     return s;
1191
1192   eeprom->id = (buf[DB_EEPROM_ID_MSB] << 8) | buf[DB_EEPROM_ID_LSB];
1193   eeprom->oe = (buf[DB_EEPROM_OE_MSB] << 8) | buf[DB_EEPROM_OE_LSB];
1194   eeprom->offset[0] = (buf[DB_EEPROM_OFFSET_0_MSB] << 8) | buf[DB_EEPROM_OFFSET_0_LSB];
1195   eeprom->offset[1] = (buf[DB_EEPROM_OFFSET_1_MSB] << 8) | buf[DB_EEPROM_OFFSET_1_LSB];
1196
1197   return UDBE_OK;
1198 }
1199
1200 bool
1201 usrp_write_dboard_offsets (libusb_device_handle *udh, int slot_id,
1202                            short offset0, short offset1)
1203 {
1204   unsigned char buf[DB_EEPROM_CLEN];
1205
1206   usrp_dbeeprom_status_t s = read_dboard_eeprom (udh, slot_id, buf);
1207   if (s != UDBE_OK)
1208     return false;
1209
1210   buf[DB_EEPROM_OFFSET_0_LSB] = (offset0 >> 0) & 0xff;
1211   buf[DB_EEPROM_OFFSET_0_MSB] = (offset0 >> 8) & 0xff;
1212   buf[DB_EEPROM_OFFSET_1_LSB] = (offset1 >> 0) & 0xff;
1213   buf[DB_EEPROM_OFFSET_1_MSB] = (offset1 >> 8) & 0xff;
1214   set_chksum (buf);
1215
1216   return usrp_eeprom_write (udh, slot_to_i2c_addr (slot_id),
1217                             0, buf, sizeof (buf));
1218 }
1219
1220 // ----------------------------------------------------------------
1221
1222 std::string
1223 usrp_serial_number(libusb_device_handle *udh)
1224 {
1225   libusb_device_descriptor desc =
1226     _get_usb_device_descriptor (_get_usb_device (udh));
1227
1228   unsigned char iserial = desc.iSerialNumber;
1229   if (iserial == 0)
1230     return "";
1231
1232   unsigned char buf[1024];
1233   if (_get_usb_string_descriptor (udh, iserial, buf, sizeof(buf)) < 0)
1234     return "";
1235
1236   return (char*) buf;
1237 }
1238
1239
1240
1241