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