Cleanup in preparation for merge
[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: %i\n", a);
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   return r == USRP_HASH_SIZE;
423 }
424
425 bool
426 usrp_get_hash (libusb_device_handle *udh, int which,
427                unsigned char hash[USRP_HASH_SIZE])
428 {
429   which &= 1;
430
431   // we use the Cypress firmware upload command to fetch it.
432   int r = _usb_control_transfer (udh, 0xc0, 0xa0, hash_slot_addr[which], 0,
433                                 (unsigned char *) hash, USRP_HASH_SIZE, 1000);
434   return r == USRP_HASH_SIZE;
435 }
436
437
438
439 static bool
440 usrp_set_switch (libusb_device_handle *udh, int cmd_byte, bool on)
441 {
442   return write_cmd (udh, cmd_byte, on, 0, 0, 0) == 0;
443 }
444
445 static bool
446 usrp1_fpga_write (libusb_device_handle *udh,
447                   int regno, int value)
448 {
449   // on the rev1 usrp, we use the generic spi_write interface
450
451   unsigned char buf[4];
452
453   buf[0] = (value >> 24) & 0xff;        // MSB first
454   buf[1] = (value >> 16) & 0xff;
455   buf[2] = (value >>  8) & 0xff;
456   buf[3] = (value >>  0) & 0xff;
457
458   return usrp_spi_write (udh, 0x00 | (regno & 0x7f),
459                          SPI_ENABLE_FPGA,
460                          SPI_FMT_MSB | SPI_FMT_HDR_1,
461                          buf, sizeof (buf));
462 }
463
464 static bool
465 usrp1_fpga_read (libusb_device_handle *udh,
466                  int regno, int *value)
467 {
468   *value = 0;
469   unsigned char buf[4];
470
471   bool ok = usrp_spi_read (udh, 0x80 | (regno & 0x7f),
472                            SPI_ENABLE_FPGA,
473                            SPI_FMT_MSB | SPI_FMT_HDR_1,
474                            buf, sizeof (buf));
475
476   if (ok)
477     *value = (buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3];
478
479   return ok;
480 }
481
482 bool
483 usrp_write_fpga_reg (libusb_device_handle *udh, int reg, int value)
484 {
485   switch (usrp_hw_rev (_get_usb_device (udh))){
486   case 0:                       // not supported ;)
487     abort();
488
489   default:
490     return usrp1_fpga_write (udh, reg, value);
491   }
492 }
493
494 bool
495 usrp_read_fpga_reg (libusb_device_handle *udh, int reg, int *value)
496 {
497   switch (usrp_hw_rev (_get_usb_device (udh))){
498   case 0:               // not supported ;)
499     abort();
500
501   default:
502     return usrp1_fpga_read (udh, reg, value);
503   }
504 }
505
506 bool
507 usrp_set_fpga_reset (libusb_device_handle *udh, bool on)
508 {
509   return usrp_set_switch (udh, VRQ_FPGA_SET_RESET, on);
510 }
511
512 bool
513 usrp_set_fpga_tx_enable (libusb_device_handle *udh, bool on)
514 {
515   return usrp_set_switch (udh, VRQ_FPGA_SET_TX_ENABLE, on);
516 }
517
518 bool
519 usrp_set_fpga_rx_enable (libusb_device_handle *udh, bool on)
520 {
521   return usrp_set_switch (udh, VRQ_FPGA_SET_RX_ENABLE, on);
522 }
523
524 bool
525 usrp_set_fpga_tx_reset (libusb_device_handle *udh, bool on)
526 {
527   return usrp_set_switch (udh, VRQ_FPGA_SET_TX_RESET, on);
528 }
529
530 bool
531 usrp_set_fpga_rx_reset (libusb_device_handle *udh, bool on)
532 {
533   return usrp_set_switch (udh, VRQ_FPGA_SET_RX_RESET, on);
534 }
535
536
537 // ----------------------------------------------------------------
538 // conditional load stuff
539
540 static bool
541 compute_hash (const char *filename, unsigned char hash[USRP_HASH_SIZE])
542 {
543   assert (USRP_HASH_SIZE == 16);
544   memset (hash, 0, USRP_HASH_SIZE);
545
546   FILE *fp = fopen (filename, "rb");
547   if (fp == 0){
548     perror (filename);
549     return false;
550   }
551   int r = md5_stream (fp, hash);
552   fclose (fp);
553
554   return r == 0;
555 }
556
557 static usrp_load_status_t
558 usrp_conditionally_load_something (libusb_device_handle *udh,
559                                    const char *filename,
560                                    bool force,
561                                    int slot,
562                                    bool loader (libusb_device_handle *,
563                                                 const char *,
564                                                 unsigned char [USRP_HASH_SIZE]))
565 {
566   unsigned char file_hash[USRP_HASH_SIZE];
567   unsigned char usrp_hash[USRP_HASH_SIZE];
568
569   if (access (filename, R_OK) != 0){
570     perror (filename);
571     return ULS_ERROR;
572   }
573
574   if (!compute_hash (filename, file_hash))
575     return ULS_ERROR;
576
577   if (!force
578       && usrp_get_hash (udh, slot, usrp_hash)
579       && memcmp (file_hash, usrp_hash, USRP_HASH_SIZE) == 0)
580     return ULS_ALREADY_LOADED;
581
582   bool r = loader (udh, filename, file_hash);
583
584   if (!r)
585     return ULS_ERROR;
586
587   return ULS_OK;
588 }
589
590 usrp_load_status_t
591 usrp_load_firmware (libusb_device_handle *udh,
592                     const char *filename,
593                     bool force)
594 {
595   return usrp_conditionally_load_something (udh, filename, force,
596                                             FIRMWARE_HASH_SLOT,
597                                             _usrp_load_firmware);
598 }
599
600 usrp_load_status_t
601 usrp_load_fpga (libusb_device_handle *udh,
602                 const char *filename,
603                 bool force)
604 {
605   return usrp_conditionally_load_something (udh, filename, force,
606                                             FPGA_HASH_SLOT,
607                                             _usrp_load_fpga);
608 }
609
610 static libusb_device_handle *
611 open_nth_cmd_interface (int nth, libusb_context *ctx)
612 {
613
614   libusb_device *udev = usrp_find_device (nth, false, ctx);
615   if (udev == 0){
616     fprintf (stderr, "usrp: failed to find usrp[%d]\n", nth);
617     return 0;
618   }
619
620   libusb_device_handle *udh;
621
622   udh = usrp_open_cmd_interface (udev);
623   if (udh == 0){
624     // FIXME this could be because somebody else has it open.
625     // We should delay and retry...
626     fprintf (stderr, "open_nth_cmd_interface: open_cmd_interface failed\n");
627     return 0;
628   }
629
630   return udh;
631 }
632
633 static bool
634 our_nanosleep (const struct timespec *delay)
635 {
636   struct timespec       new_delay = *delay;
637   struct timespec       remainder;
638
639   while (1){
640     int r = nanosleep (&new_delay, &remainder);
641     if (r == 0)
642       return true;
643     if (errno == EINTR)
644       new_delay = remainder;
645     else {
646       perror ("nanosleep");
647       return false;
648     }
649   }
650 }
651
652 static bool
653 mdelay (int millisecs)
654 {
655   struct timespec       ts;
656   ts.tv_sec = millisecs / 1000;
657   ts.tv_nsec = (millisecs - (1000 * ts.tv_sec)) * 1000000;
658   return our_nanosleep (&ts);
659 }
660
661
662 usrp_load_status_t
663 usrp_load_firmware_nth (int nth, const char *filename, bool force, libusb_context *ctx)
664 {
665   libusb_device_handle *udh = open_nth_cmd_interface (nth, ctx);
666   if (udh == 0)
667     return ULS_ERROR;
668
669   usrp_load_status_t s = usrp_load_firmware (udh, filename, force);
670   usrp_close_interface (udh);
671
672   switch (s){
673
674   case ULS_ALREADY_LOADED:              // nothing changed...
675     return ULS_ALREADY_LOADED;
676     break;
677
678   case ULS_OK:
679     // we loaded firmware successfully.
680
681     // It's highly likely that the board will renumerate (simulate a
682     // disconnect/reconnect sequence), invalidating our current
683     // handle.
684
685     // FIXME.  Turn this into a loop that rescans until we refind ourselves
686
687     struct timespec     t;      // delay for 1 second
688     t.tv_sec = 2;
689     t.tv_nsec = 0;
690     our_nanosleep (&t);
691
692     return ULS_OK;
693
694   default:
695   case ULS_ERROR:               // some kind of problem
696     return ULS_ERROR;
697   }
698 }
699
700 static void
701 load_status_msg (usrp_load_status_t s, const char *type, const char *filename)
702 {
703   char *e = getenv("USRP_VERBOSE");
704   bool verbose = e != 0;
705
706   switch (s){
707   case ULS_ERROR:
708     fprintf (stderr, "usrp: failed to load %s %s.\n", type, filename);
709     break;
710
711   case ULS_ALREADY_LOADED:
712     if (verbose)
713       fprintf (stderr, "usrp: %s %s already loaded.\n", type, filename);
714     break;
715
716   case ULS_OK:
717     if (verbose)
718       fprintf (stderr, "usrp: %s %s loaded successfully.\n", type, filename);
719     break;
720   }
721 }
722
723 bool
724 usrp_load_standard_bits (int nth, bool force,
725                          const std::string fpga_filename,
726                          const std::string firmware_filename,
727                          libusb_context *ctx)
728 {
729   usrp_load_status_t    s;
730   const char            *filename;
731   const char            *proto_filename;
732   int hw_rev;
733
734   // first, figure out what hardware rev we're dealing with
735   {
736     libusb_device *udev = usrp_find_device (nth, false, ctx);
737     if (udev == 0){
738       fprintf (stderr, "usrp: failed to find usrp[%d]\n", nth);
739       return false;
740     }
741     hw_rev = usrp_hw_rev (udev);
742   }
743
744   // start by loading the firmware
745
746   proto_filename = get_proto_filename(firmware_filename, "USRP_FIRMWARE",
747                                       default_firmware_filename);
748   filename = find_file(proto_filename, hw_rev);
749   if (filename == 0){
750     fprintf (stderr, "Can't find firmware: %s\n", proto_filename);
751     return false;
752   }
753   s = usrp_load_firmware_nth (nth, filename, force, ctx);
754   load_status_msg (s, "firmware", filename);
755
756   if (s == ULS_ERROR)
757     return false;
758
759   // if we actually loaded firmware, we must reload fpga ...
760   if (s == ULS_OK)
761     force = true;
762
763   // now move on to the fpga configuration bitstream
764
765   proto_filename = get_proto_filename(fpga_filename, "USRP_FPGA",
766                                       default_fpga_filename);
767   filename = find_file (proto_filename, hw_rev);
768   if (filename == 0){
769     fprintf (stderr, "Can't find fpga bitstream: %s\n", proto_filename);
770     return false;
771   }
772   libusb_device_handle *udh = open_nth_cmd_interface (nth, ctx);
773   if (udh == 0)
774     return false;
775
776   s = usrp_load_fpga (udh, filename, force);
777   usrp_close_interface (udh);
778   load_status_msg (s, "fpga bitstream", filename);
779
780   if (s == ULS_ERROR)
781     return false;
782
783   return true;
784 }
785
786
787 bool
788 _usrp_get_status (libusb_device_handle *udh, int which, bool *trouble)
789 {
790   unsigned char status;
791   *trouble = true;
792
793   if (write_cmd (udh, VRQ_GET_STATUS, 0, which,
794                  &status, sizeof (status)) != sizeof (status))
795     return false;
796
797   *trouble = status;
798   return true;
799 }
800
801 bool
802 usrp_check_rx_overrun (libusb_device_handle *udh, bool *overrun_p)
803 {
804   return _usrp_get_status (udh, GS_RX_OVERRUN, overrun_p);
805 }
806
807 bool
808 usrp_check_tx_underrun (libusb_device_handle *udh, bool *underrun_p)
809 {
810   return _usrp_get_status (udh, GS_TX_UNDERRUN, underrun_p);
811 }
812
813
814 bool
815 usrp_i2c_write (libusb_device_handle *udh, int i2c_addr,
816                 const void *buf, int len)
817 {
818   if (len < 1 || len > MAX_EP0_PKTSIZE)
819     return false;
820
821   return write_cmd (udh, VRQ_I2C_WRITE, i2c_addr, 0,
822                     (unsigned char *) buf, len) == len;
823 }
824
825
826 bool
827 usrp_i2c_read (libusb_device_handle *udh, int i2c_addr,
828                void *buf, int len)
829 {
830   if (len < 1 || len > MAX_EP0_PKTSIZE)
831     return false;
832
833   return write_cmd (udh, VRQ_I2C_READ, i2c_addr, 0,
834                     (unsigned char *) buf, len) == len;
835 }
836
837 bool
838 usrp_spi_write (libusb_device_handle *udh,
839                 int optional_header, int enables, int format,
840                 const void *buf, int len)
841 {
842   if (len < 0 || len > MAX_EP0_PKTSIZE)
843     return false;
844
845   return write_cmd (udh, VRQ_SPI_WRITE,
846                     optional_header,
847                     ((enables & 0xff) << 8) | (format & 0xff),
848                     (unsigned char *) buf, len) == len;
849 }
850
851
852 bool
853 usrp_spi_read (libusb_device_handle *udh,
854                int optional_header, int enables, int format,
855                void *buf, int len)
856 {
857   if (len < 0 || len > MAX_EP0_PKTSIZE)
858     return false;
859
860   return write_cmd (udh, VRQ_SPI_READ,
861                     optional_header,
862                     ((enables & 0xff) << 8) | (format & 0xff),
863                     (unsigned char *) buf, len) == len;
864 }
865
866 bool
867 usrp_9862_write (libusb_device_handle *udh, int which_codec,
868                  int regno, int value)
869 {
870   if (0)
871     fprintf (stderr, "usrp_9862_write which = %d, reg = %2d, val = %3d (0x%02x)\n",
872              which_codec, regno, value, value);
873
874   unsigned char buf[1];
875
876   buf[0] = value;
877
878   return usrp_spi_write (udh, 0x00 | (regno & 0x3f),
879                          which_codec == 0 ? SPI_ENABLE_CODEC_A : SPI_ENABLE_CODEC_B,
880                          SPI_FMT_MSB | SPI_FMT_HDR_1,
881                          buf, 1);
882 }
883
884 bool
885 usrp_9862_read (libusb_device_handle *udh, int which_codec,
886                 int regno, unsigned char *value)
887 {
888   return usrp_spi_read (udh, 0x80 | (regno & 0x3f),
889                         which_codec == 0 ? SPI_ENABLE_CODEC_A : SPI_ENABLE_CODEC_B,
890                         SPI_FMT_MSB | SPI_FMT_HDR_1,
891                         value, 1);
892 }
893
894 bool
895 usrp_9862_write_many (libusb_device_handle *udh,
896                       int which_codec,
897                       const unsigned char *buf,
898                       int len)
899 {
900   if (len & 0x1)
901     return false;               // must be even
902
903   bool result = true;
904
905   while (len > 0){
906     result &= usrp_9862_write (udh, which_codec, buf[0], buf[1]);
907     len -= 2;
908     buf += 2;
909   }
910
911   return result;
912 }
913
914
915 bool
916 usrp_9862_write_many_all (libusb_device_handle *udh,
917                            const unsigned char *buf, int len)
918 {
919   // FIXME handle 2/2 and 4/4 versions
920
921   bool result;
922   result  = usrp_9862_write_many (udh, 0, buf, len);
923   result &= usrp_9862_write_many (udh, 1, buf, len);
924   return result;
925 }
926
927 static void
928 power_down_9862s (libusb_device_handle *udh)
929 {
930   static const unsigned char regs[] = {
931     REG_RX_PWR_DN,      0x01,           // everything
932     REG_TX_PWR_DN,      0x0f,           // pwr dn digital and analog_both
933     REG_TX_MODULATOR,   0x00            // coarse & fine modulators disabled
934   };
935
936   switch (usrp_hw_rev (_get_usb_device (udh))){
937   case 0:
938     break;
939
940   default:
941     usrp_9862_write_many_all (udh, regs, sizeof (regs));
942     break;
943   }
944 }
945
946
947 static const int EEPROM_PAGESIZE = 16;
948
949 bool
950 usrp_eeprom_write (libusb_device_handle *udh, int i2c_addr,
951                    int eeprom_offset, const void *buf, int len)
952 {
953   unsigned char cmd[2];
954   const unsigned char *p = (unsigned char *) buf;
955
956   // The simplest thing that could possibly work:
957   //   all writes are single byte writes.
958   //
959   // We could speed this up using the page write feature,
960   // but we write so infrequently, why bother...
961
962   while (len-- > 0){
963     cmd[0] = eeprom_offset++;
964     cmd[1] = *p++;
965     bool r = usrp_i2c_write (udh, i2c_addr, cmd, sizeof (cmd));
966     mdelay (10);                // delay 10ms worst case write time
967     if (!r)
968       return false;
969   }
970
971   return true;
972 }
973
974 bool
975 usrp_eeprom_read (libusb_device_handle *udh, int i2c_addr,
976                   int eeprom_offset, void *buf, int len)
977 {
978   unsigned char *p = (unsigned char *) buf;
979
980   // We setup a random read by first doing a "zero byte write".
981   // Writes carry an address.  Reads use an implicit address.
982
983   unsigned char cmd[1];
984   cmd[0] = eeprom_offset;
985   if (!usrp_i2c_write (udh, i2c_addr, cmd, sizeof (cmd)))
986     return false;
987
988   while (len > 0){
989     int n = std::min (len, MAX_EP0_PKTSIZE);
990     if (!usrp_i2c_read (udh, i2c_addr, p, n))
991       return false;
992     len -= n;
993     p += n;
994   }
995   return true;
996 }
997
998 // ----------------------------------------------------------------
999
1000 static bool
1001 slot_to_codec (int slot, int *which_codec)
1002 {
1003   *which_codec = 0;
1004
1005   switch (slot){
1006   case SLOT_TX_A:
1007   case SLOT_RX_A:
1008     *which_codec = 0;
1009     break;
1010
1011   case SLOT_TX_B:
1012   case SLOT_RX_B:
1013     *which_codec = 1;
1014     break;
1015
1016   default:
1017     fprintf (stderr, "usrp_prims:slot_to_codec: invalid slot = %d\n", slot);
1018     return false;
1019   }
1020   return true;
1021 }
1022
1023 static bool
1024 tx_slot_p (int slot)
1025 {
1026   switch (slot){
1027   case SLOT_TX_A:
1028   case SLOT_TX_B:
1029     return true;
1030
1031   default:
1032     return false;
1033   }
1034 }
1035
1036 bool
1037 usrp_write_aux_dac (libusb_device_handle *udh, int slot,
1038                     int which_dac, int value)
1039 {
1040   int which_codec;
1041
1042   if (!slot_to_codec (slot, &which_codec))
1043     return false;
1044
1045   if (!(0 <= which_dac && which_dac < 4)){
1046     fprintf (stderr, "usrp_write_aux_dac: invalid dac = %d\n", which_dac);
1047     return false;
1048   }
1049
1050   value &= 0x0fff;      // mask to 12-bits
1051
1052   if (which_dac == 3){
1053     // dac 3 is really 12-bits.  Use value as is.
1054     bool r = true;
1055     r &= usrp_9862_write (udh, which_codec, 43, (value >> 4));       // most sig
1056     r &= usrp_9862_write (udh, which_codec, 42, (value & 0xf) << 4); // least sig
1057     return r;
1058   }
1059   else {
1060     // dac 0, 1, and 2 are really 8 bits.
1061     value = value >> 4;         // shift value appropriately
1062     return usrp_9862_write (udh, which_codec, 36 + which_dac, value);
1063   }
1064 }
1065
1066
1067 bool
1068 usrp_read_aux_adc (libusb_device_handle *udh, int slot,
1069                    int which_adc, int *value)
1070 {
1071   *value = 0;
1072   int   which_codec;
1073
1074   if (!slot_to_codec (slot, &which_codec))
1075     return false;
1076
1077   if (!(0 <= which_codec && which_codec < 2)){
1078     fprintf (stderr, "usrp_read_aux_adc: invalid adc = %d\n", which_adc);
1079     return false;
1080   }
1081
1082   unsigned char aux_adc_control =
1083     AUX_ADC_CTRL_REFSEL_A               // on chip reference
1084     | AUX_ADC_CTRL_REFSEL_B;            // on chip reference
1085
1086   int   rd_reg = 26;    // base address of two regs to read for result
1087
1088   // program the ADC mux bits
1089   if (tx_slot_p (slot))
1090     aux_adc_control |= AUX_ADC_CTRL_SELECT_A2 | AUX_ADC_CTRL_SELECT_B2;
1091   else {
1092     rd_reg += 2;
1093     aux_adc_control |= AUX_ADC_CTRL_SELECT_A1 | AUX_ADC_CTRL_SELECT_B1;
1094   }
1095
1096   // I'm not sure if we can set the mux and issue a start conversion
1097   // in the same cycle, so let's do them one at a time.
1098
1099   usrp_9862_write (udh, which_codec, 34, aux_adc_control);
1100
1101   if (which_adc == 0)
1102     aux_adc_control |= AUX_ADC_CTRL_START_A;
1103   else {
1104     rd_reg += 4;
1105     aux_adc_control |= AUX_ADC_CTRL_START_B;
1106   }
1107
1108   // start the conversion
1109   usrp_9862_write (udh, which_codec, 34, aux_adc_control);
1110
1111   // read the 10-bit result back
1112   unsigned char v_lo = 0;
1113   unsigned char v_hi = 0;
1114   bool r = usrp_9862_read (udh, which_codec, rd_reg, &v_lo);
1115   r &= usrp_9862_read (udh, which_codec, rd_reg + 1, &v_hi);
1116
1117   if (r)
1118     *value = ((v_hi << 2) | ((v_lo >> 6) & 0x3)) << 2;  // format as 12-bit
1119
1120   return r;
1121 }
1122
1123 // ----------------------------------------------------------------
1124
1125 static int slot_to_i2c_addr (int slot)
1126 {
1127   switch (slot){
1128   case SLOT_TX_A:       return I2C_ADDR_TX_A;
1129   case SLOT_RX_A:       return I2C_ADDR_RX_A;
1130   case SLOT_TX_B:       return I2C_ADDR_TX_B;
1131   case SLOT_RX_B:       return I2C_ADDR_RX_B;
1132   default:              return -1;
1133   }
1134 }
1135
1136 static void
1137 set_chksum (unsigned char *buf)
1138 {
1139   int sum = 0;
1140   unsigned int i;
1141   for (i = 0; i < DB_EEPROM_CLEN - 1; i++)
1142     sum += buf[i];
1143   buf[i] = -sum;
1144 }
1145
1146 static usrp_dbeeprom_status_t
1147 read_dboard_eeprom (libusb_device_handle *udh,
1148                     int slot_id, unsigned char *buf)
1149 {
1150   int i2c_addr = slot_to_i2c_addr (slot_id);
1151   if (i2c_addr == -1)
1152     return UDBE_BAD_SLOT;
1153
1154   if (!usrp_eeprom_read (udh, i2c_addr, 0, buf, DB_EEPROM_CLEN))
1155     return UDBE_NO_EEPROM;
1156
1157   if (buf[DB_EEPROM_MAGIC] != DB_EEPROM_MAGIC_VALUE)
1158     return UDBE_INVALID_EEPROM;
1159
1160   int sum = 0;
1161   for (unsigned int i = 0; i < DB_EEPROM_CLEN; i++)
1162     sum += buf[i];
1163
1164   if ((sum & 0xff) != 0)
1165     return UDBE_INVALID_EEPROM;
1166
1167   return UDBE_OK;
1168 }
1169
1170 usrp_dbeeprom_status_t
1171 usrp_read_dboard_eeprom (libusb_device_handle *udh,
1172                          int slot_id, usrp_dboard_eeprom *eeprom)
1173 {
1174   unsigned char buf[DB_EEPROM_CLEN];
1175
1176   memset (eeprom, 0, sizeof (*eeprom));
1177
1178   usrp_dbeeprom_status_t s = read_dboard_eeprom (udh, slot_id, buf);
1179   if (s != UDBE_OK)
1180     return s;
1181
1182   eeprom->id = (buf[DB_EEPROM_ID_MSB] << 8) | buf[DB_EEPROM_ID_LSB];
1183   eeprom->oe = (buf[DB_EEPROM_OE_MSB] << 8) | buf[DB_EEPROM_OE_LSB];
1184   eeprom->offset[0] = (buf[DB_EEPROM_OFFSET_0_MSB] << 8) | buf[DB_EEPROM_OFFSET_0_LSB];
1185   eeprom->offset[1] = (buf[DB_EEPROM_OFFSET_1_MSB] << 8) | buf[DB_EEPROM_OFFSET_1_LSB];
1186
1187   return UDBE_OK;
1188 }
1189
1190 bool
1191 usrp_write_dboard_offsets (libusb_device_handle *udh, int slot_id,
1192                            short offset0, short offset1)
1193 {
1194   unsigned char buf[DB_EEPROM_CLEN];
1195
1196   usrp_dbeeprom_status_t s = read_dboard_eeprom (udh, slot_id, buf);
1197   if (s != UDBE_OK)
1198     return false;
1199
1200   buf[DB_EEPROM_OFFSET_0_LSB] = (offset0 >> 0) & 0xff;
1201   buf[DB_EEPROM_OFFSET_0_MSB] = (offset0 >> 8) & 0xff;
1202   buf[DB_EEPROM_OFFSET_1_LSB] = (offset1 >> 0) & 0xff;
1203   buf[DB_EEPROM_OFFSET_1_MSB] = (offset1 >> 8) & 0xff;
1204   set_chksum (buf);
1205
1206   return usrp_eeprom_write (udh, slot_to_i2c_addr (slot_id),
1207                             0, buf, sizeof (buf));
1208 }
1209
1210 // ----------------------------------------------------------------
1211
1212 std::string
1213 usrp_serial_number(libusb_device_handle *udh)
1214 {
1215   libusb_device_descriptor desc =
1216     _get_usb_device_descriptor (_get_usb_device (udh));
1217
1218   unsigned char iserial = desc.iSerialNumber;
1219   if (iserial == 0)
1220     return "";
1221
1222   unsigned char buf[1024];
1223   if (_get_usb_string_descriptor (udh, iserial, buf, sizeof(buf)) < 0)
1224     return "";
1225
1226   return (char*) buf;
1227 }
1228
1229
1230
1231