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