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