summaryrefslogtreecommitdiff
path: root/usrp/host/lib/usrp_standard.cc
blob: fe5afabdb5357c4ee22ab87fe9f406fe81387b68 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
/* -*- c++ -*- */
/*
 * Copyright 2004,2008,2009 Free Software Foundation, Inc.
 * 
 * This file is part of GNU Radio
 * 
 * GNU Radio is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3, or (at your option)
 * any later version.
 * 
 * GNU Radio is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with GNU Radio; see the file COPYING.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street,
 * Boston, MA 02110-1301, USA.
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <usrp/usrp_standard.h>

#include "usrp/usrp_prims.h"
#include "fpga_regs_common.h"
#include "fpga_regs_standard.h"
#include <stdexcept>
#include <assert.h>
#include <math.h>
#include <ad9862.h>
#include <cstdio>


static const int OLD_CAPS_VAL = 0xaa55ff77;
static const int DEFAULT_CAPS_VAL = ((2 << bmFR_RB_CAPS_NDUC_SHIFT)
				     | (2 << bmFR_RB_CAPS_NDDC_SHIFT)
				     | bmFR_RB_CAPS_RX_HAS_HALFBAND);

// #define USE_FPGA_TX_CORDIC


using namespace ad9862;

#define NELEM(x) (sizeof (x) / sizeof (x[0]))


void
usrp_standard_common::calc_dxc_freq(double target_freq, double baseband_freq, double fs,
				    double *dxc_freq, bool *inverted)
{
  /*
    Calculate the frequency to use for setting the digital up or down converter.
    
    @param target_freq: desired RF frequency (Hz)
    @param baseband_freq: the RF frequency that corresponds to DC in the IF.
    @param fs: converter sample rate
    
    @returns: 2-tuple (ddc_freq, inverted) where ddc_freq is the value
      for the ddc and inverted is True if we're operating in an inverted
      Nyquist zone.
  */

#if 0
    printf("calc_dxc_freq:\n");
    printf("  target   = %f\n", target_freq);
    printf("  baseband = %f\n", baseband_freq);
    printf("  fs       = %f\n", fs);
#endif

  double delta = target_freq - baseband_freq;
    
  if(delta >= 0) {
    while(delta > fs) {
      delta -= fs;
    }
    if(delta <= fs/2) {		// non-inverted region
      *dxc_freq = -delta;	
      *inverted = false;
    }
    else {     			// inverted region
      *dxc_freq = delta - fs;
      *inverted = true;
    }
  }
  else {
    while(delta < -fs) {
      delta += fs;
    }
    if(delta >= -fs/2) {
      *dxc_freq = -delta;	// non-inverted region
      *inverted = false;
    }
    else {			// inverted region
      *dxc_freq = delta + fs;
      *inverted = true;
    }
  }

#if 0
    printf("  dxc_freq  = %f\n", *dxc_freq);
    printf("  inverted  = %s\n", *inverted ? "true" : "false");
#endif
}


/* 
 * Real lambda expressions would be _so_ much easier...
 */
class dxc_control {
public:
  virtual bool is_tx() = 0;
  virtual bool set_dxc_freq(double dxc_freq) = 0;
  virtual double dxc_freq() = 0;
};

class ddc_control : public dxc_control {
  usrp_standard_rx     *d_u;
  int			d_chan;

public:
  ddc_control(usrp_standard_rx *u, int chan)
    : d_u(u), d_chan(chan) {}
  
  bool is_tx(){ return false; }
  bool set_dxc_freq(double dxc_freq){ return d_u->set_rx_freq(d_chan, dxc_freq); }
  double dxc_freq(){ return d_u->rx_freq(d_chan); }
};

class duc_control : public dxc_control {
  usrp_standard_tx     *d_u;
  int			d_chan;

public:
  duc_control(usrp_standard_tx *u, int chan)
    : d_u(u), d_chan(chan) {}
  
  bool is_tx(){ return true; }
  bool set_dxc_freq(double dxc_freq){ return d_u->set_tx_freq(d_chan, dxc_freq); }
  double dxc_freq() { return d_u->tx_freq(d_chan); }
};


/*!
 * \brief Tune such that target_frequency ends up at DC in the complex baseband
 *
 * \param db		the daughterboard to use
 * \param target_freq	the center frequency we want at baseband (DC)
 * \param fs 		the sample rate
 * \param dxc		DDC or DUC access and control object
 * \param[out] result	details of what we did
 *
 * \returns true iff operation was successful
 *
 * Tuning is a two step process.  First we ask the front-end to
 * tune as close to the desired frequency as it can.  Then we use
 * the result of that operation and our target_frequency to
 * determine the value for the digital down converter.
 */
static bool
tune_a_helper(db_base_sptr db, double target_freq, double fs,
	      dxc_control &dxc, usrp_tune_result *result)
{
  bool inverted = false;
  double dxc_freq;
  double actual_dxc_freq;

  // Ask the d'board to tune as closely as it can to target_freq
#if 0
  bool ok = db->set_freq(target_freq, &result->baseband_freq);
#else
  bool ok;
  {
    freq_result_t fr = db->set_freq(target_freq);
    ok = fr.ok;
    result->baseband_freq = fr.baseband_freq;
  }
#endif

  // Calculate the DDC setting that will downconvert the baseband from the
  // daughterboard to our target frequency.
  usrp_standard_common::calc_dxc_freq(target_freq, result->baseband_freq, fs,
				      &dxc_freq, &inverted);

  // If the spectrum is inverted, and the daughterboard doesn't do
  // quadrature downconversion, we can fix the inversion by flipping the
  // sign of the dxc_freq...  (This only happens using the basic_rx board)
  
  if(db->spectrum_inverted())
    inverted = !inverted;
  
  if(inverted && !db->is_quadrature()){
    dxc_freq = -dxc_freq;
    inverted = !inverted;
  }
  
  if (dxc.is_tx() && !db->i_and_q_swapped())		// down conversion versus up conversion
    dxc_freq = -dxc_freq;

  ok &= dxc.set_dxc_freq(dxc_freq);
  actual_dxc_freq = dxc.dxc_freq();
  
  result->dxc_freq = dxc_freq;
  result->residual_freq = dxc_freq - actual_dxc_freq;
  result->inverted = inverted;
  return ok;
}


static unsigned int
compute_freq_control_word_fpga (double master_freq, double target_freq,
				double *actual_freq, bool verbose)
{
  static const int NBITS = 14;
  
  int	v = (int) rint (target_freq / master_freq * pow (2.0, 32.0));

  if (0)
    v = (v >> (32 - NBITS)) << (32 - NBITS);	// keep only top NBITS

  *actual_freq = v * master_freq / pow (2.0, 32.0);

  if (verbose)
    fprintf (stderr,
	     "compute_freq_control_word_fpga: target = %g  actual = %g  delta = %g\n",
	     target_freq, *actual_freq, *actual_freq - target_freq);

  return (unsigned int) v;
}

// The 9862 uses an unsigned 24-bit frequency tuning word and 
// a separate register to control the sign.

static unsigned int
compute_freq_control_word_9862 (double master_freq, double target_freq,
				double *actual_freq, bool verbose)
{
  double sign = 1.0;

  if (target_freq < 0)
    sign = -1.0;

  int	v = (int) rint (fabs (target_freq) / master_freq * pow (2.0, 24.0));
  *actual_freq = v * master_freq / pow (2.0, 24.0) * sign;

  if (verbose)
    fprintf (stderr,
     "compute_freq_control_word_9862: target = %g  actual = %g  delta = %g  v = %8d\n",
     target_freq, *actual_freq, *actual_freq - target_freq, v);

  return (unsigned int) v;
}

// ----------------------------------------------------------------

usrp_standard_common::usrp_standard_common(usrp_basic *parent)
{
  // read new FPGA capability register
  if (!parent->_read_fpga_reg(FR_RB_CAPS, &d_fpga_caps)){
    fprintf (stderr, "usrp_standard_common: failed to read FPGA cap register.\n");
    throw std::runtime_error ("usrp_standard_common::ctor");
  }
  // If we don't have the cap register, set the value to what it would
  // have had if we did have one ;)
  if (d_fpga_caps == OLD_CAPS_VAL)
    d_fpga_caps = DEFAULT_CAPS_VAL;

  if (0){
    fprintf(stdout, "has_rx_halfband = %d\n", has_rx_halfband());
    fprintf(stdout, "nddcs           = %d\n", nddcs());
    fprintf(stdout, "has_tx_halfband = %d\n", has_tx_halfband());
    fprintf(stdout, "nducs           = %d\n", nducs());
  }
}

bool
usrp_standard_common::has_rx_halfband() const
{
  return (d_fpga_caps & bmFR_RB_CAPS_RX_HAS_HALFBAND) ? true : false;
}

int
usrp_standard_common::nddcs() const
{
  return (d_fpga_caps & bmFR_RB_CAPS_NDDC_MASK) >> bmFR_RB_CAPS_NDDC_SHIFT;
}

bool
usrp_standard_common::has_tx_halfband() const
{
  return (d_fpga_caps & bmFR_RB_CAPS_TX_HAS_HALFBAND) ? true : false;
}

int
usrp_standard_common::nducs() const
{
  return (d_fpga_caps & bmFR_RB_CAPS_NDUC_MASK) >> bmFR_RB_CAPS_NDUC_SHIFT;
}

// ----------------------------------------------------------------

static int 
real_rx_mux_value (int mux, int nchan)
{
  if (mux != -1)
    return mux;

  return 0x32103210;
}

usrp_standard_rx::usrp_standard_rx (int which_board,
				    unsigned int decim_rate,
				    int nchan, int mux, int mode,
				    int fusb_block_size, int fusb_nblocks,
				    const std::string fpga_filename,
				    const std::string firmware_filename
				    )
  : usrp_basic_rx (which_board, fusb_block_size, fusb_nblocks,
		   fpga_filename, firmware_filename),
    usrp_standard_common(this),
    d_nchan (1), d_sw_mux (0x0), d_hw_mux (0x0)
{
  if (!set_format(make_format())){
    fprintf (stderr, "usrp_standard_rx: set_format failed\n");
    throw std::runtime_error ("usrp_standard_rx::ctor");
  }
  if (!set_nchannels (nchan)){
    fprintf (stderr, "usrp_standard_rx: set_nchannels failed\n");
    throw std::runtime_error ("usrp_standard_rx::ctor");
  }
  if (!set_decim_rate (decim_rate)){
    fprintf (stderr, "usrp_standard_rx: set_decim_rate failed\n");
    throw std::runtime_error ("usrp_standard_rx::ctor");
  }
  if (!set_mux (real_rx_mux_value (mux, nchan))){
    fprintf (stderr, "usrp_standard_rx: set_mux failed\n");
    throw std::runtime_error ("usrp_standard_rx::ctor");
  }
  if (!set_fpga_mode (mode)){
    fprintf (stderr, "usrp_standard_rx: set_fpga_mode failed\n");
    throw std::runtime_error ("usrp_standard_rx::ctor");
  }

  for (int i = 0; i < MAX_CHAN; i++){
    set_rx_freq(i, 0);
    set_ddc_phase(i, 0);
  }
}

usrp_standard_rx::~usrp_standard_rx ()
{
  // fprintf(stderr, "\nusrp_standard_rx: dtor\n");
}

bool
usrp_standard_rx::start ()
{
  if (!usrp_basic_rx::start ())
    return false;

  // add our code here

  return true;
}

bool
usrp_standard_rx::stop ()
{
  bool ok = usrp_basic_rx::stop ();

  // add our code here

  return ok;
}

usrp_standard_rx_sptr
usrp_standard_rx::make (int which_board,
			unsigned int decim_rate,
			int nchan, int mux, int mode,
			int fusb_block_size, int fusb_nblocks,
			const std::string fpga_filename,
			const std::string firmware_filename
			)
{
  try {
    usrp_standard_rx_sptr u = 
      usrp_standard_rx_sptr(new usrp_standard_rx(which_board, decim_rate,
						 nchan, mux, mode,
						 fusb_block_size, fusb_nblocks,
						 fpga_filename, firmware_filename));
    u->init_db(u);
    return u;
  }
  catch (...){
    return usrp_standard_rx_sptr();
  }
}

bool
usrp_standard_rx::set_decim_rate(unsigned int rate)
{
  if (has_rx_halfband()){
    if ((rate & 0x1) || rate < 4 || rate > 256){
      fprintf (stderr, "usrp_standard_rx::set_decim_rate: rate must be EVEN and in [4, 256]\n");
      return false;
    }
  }
  else {
    if (rate < 4 || rate > 128){
      fprintf (stderr, "usrp_standard_rx::set_decim_rate: rate must be in [4, 128]\n");
      return false;
    }
  }

  d_decim_rate = rate;
  set_usb_data_rate ((adc_rate () / rate * nchannels ())
		     * (2 * sizeof (short)));

  bool s = disable_rx ();
  int v = has_rx_halfband() ? d_decim_rate/2 - 1 : d_decim_rate - 1;
  bool ok = _write_fpga_reg (FR_DECIM_RATE, v);
  restore_rx (s);
  return ok;
}

bool usrp_standard_rx::set_nchannels (int nchan)
{
  if (!(nchan == 1 || nchan == 2 || nchan == 4))
    return false;

  if (nchan > nddcs())
    return false;

  d_nchan = nchan;

  return write_hw_mux_reg ();
}


// map software mux value to hw mux value
//
// Software mux value:
//
//    3                   2                   1                       
//  1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
// +-------+-------+-------+-------+-------+-------+-------+-------+
// |   Q3  |   I3  |   Q2  |   I2  |   Q1  |   I1  |   Q0  |   I0  |
// +-------+-------+-------+-------+-------+-------+-------+-------+
//
// Each 4-bit I field is either 0,1,2,3
// Each 4-bit Q field is either 0,1,2,3 or 0xf (input is const zero)
// All Q's must be 0xf or none of them may be 0xf
//
//
// Hardware mux value:
//
//    3                   2                   1                       
//  1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
// +-----------------------+-------+-------+-------+-------+-+-----+
// |      must be zero     | Q3| I3| Q2| I2| Q1| I1| Q0| I0|Z| NCH |
// +-----------------------+-------+-------+-------+-------+-+-----+


static bool
map_sw_mux_to_hw_mux (int sw_mux, int *hw_mux_ptr)
{
  // confirm that all I's are either 0,1,2,3 

  for (int i = 0; i < 8; i += 2){
    int t = (sw_mux >> (4 * i)) & 0xf;
    if (!(0 <= t && t <= 3))
      return false;
  }

  // confirm that all Q's are either 0,1,2,3 or 0xf

  for (int i = 1; i < 8; i += 2){
    int t = (sw_mux >> (4 * i)) & 0xf;
    if (!(t == 0xf || (0 <= t && t <= 3)))
      return false;
  }

  // confirm that all Q inputs are 0xf (const zero input),
  // or none of them are 0xf

  int q_and = 1;
  int q_or =  0;

  for (int i = 0; i < 4; i++){
    int qx_is_0xf = ((sw_mux >> (8 * i + 4)) & 0xf) == 0xf;
    q_and &= qx_is_0xf;
    q_or  |= qx_is_0xf;
  }

  if (q_and || !q_or){		// OK
    int hw_mux_value = 0;

    for (int i = 0; i < 8; i++){
      int t = (sw_mux >> (4 * i)) & 0x3;
      hw_mux_value |= t << (2 * i + 4);
    }

    if (q_and)
      hw_mux_value |= 0x8;	// all Q's zero

    *hw_mux_ptr = hw_mux_value;
    return true;
  }
  else
    return false;
}

bool
usrp_standard_rx::set_mux (int mux)
{
  if (!map_sw_mux_to_hw_mux (mux, &d_hw_mux))
    return false;

  // fprintf (stderr, "sw_mux = 0x%08x  hw_mux = 0x%08x\n", mux, d_hw_mux);

  d_sw_mux = mux;
  return write_hw_mux_reg ();
}

bool
usrp_standard_rx::write_hw_mux_reg ()
{
  bool s = disable_rx ();
  bool ok = _write_fpga_reg (FR_RX_MUX, d_hw_mux | d_nchan);
  restore_rx (s);
  return ok;
}

int
usrp_standard_rx::determine_rx_mux_value(const usrp_subdev_spec &ss)
{
  /*
    Determine appropriate Rx mux value as a function of the subdevice choosen and the
    characteristics of the respective daughterboard.
    
    @param u:           instance of USRP source
    @param subdev_spec: return value from subdev option parser.  
    @type  subdev_spec: (side, subdev), where side is 0 or 1 and subdev is 0 or 1
    @returns:           the Rx mux value
  
    Figure out which A/D's to connect to the DDC.
    
    Each daughterboard consists of 1 or 2 subdevices.  (At this time,
    all but the Basic Rx have a single subdevice.  The Basic Rx
    has two independent channels, treated as separate subdevices).
    subdevice 0 of a daughterboard may use 1 or 2 A/D's.  We determine this
    by checking the is_quadrature() method.  If subdevice 0 uses only a single
    A/D, it's possible that the daughterboard has a second subdevice, subdevice 1,
    and it uses the second A/D.
    
    If the card uses only a single A/D, we wire a zero into the DDC Q input.
    
    (side, 0) says connect only the A/D's used by subdevice 0 to the DDC.
    (side, 1) says connect only the A/D's used by subdevice 1 to the DDC.
  */

  struct truth_table_element
  {
    int          d_side;
    int 	 d_uses;
    bool         d_swap_iq;
    unsigned int d_mux_val;

    truth_table_element(int side, unsigned int uses, bool swap_iq, unsigned int mux_val=0)
      : d_side(side), d_uses(uses), d_swap_iq(swap_iq), d_mux_val(mux_val){}
      
    bool operator==(const truth_table_element &in)
    {
      return (d_side == in.d_side && d_uses == in.d_uses && d_swap_iq == in.d_swap_iq);
    }

    unsigned int mux_val() { return d_mux_val; }
  };


  if (!is_valid(ss))
    throw std::invalid_argument("subdev_spec");


  // This is a tuple of length 1 or 2 containing the subdevice
  // classes for the selected side.
  std::vector<db_base_sptr> db = this->db(ss.side);
  
  unsigned int uses;

  // compute bitmasks of used A/D's
  
  if(db[ss.subdev]->is_quadrature())
    uses = 0x3;               // uses A/D 0 and 1
  else if (ss.subdev == 0)
    uses = 0x1;               // uses A/D 0 only
  else if(ss.subdev == 1)
    uses = 0x2;               // uses A/D 1 only
  else
    uses = 0x0;               // uses no A/D (doesn't exist)
  
  if(uses == 0){
    throw std::runtime_error("Determine RX Mux Error");
  }
  
  bool swap_iq = db[ss.subdev]->i_and_q_swapped();
  
  truth_table_element truth_table[8] = {
    // (side, uses, swap_iq) : mux_val
    truth_table_element(0, 0x1, false, 0xf0f0f0f0),
    truth_table_element(0, 0x2, false, 0xf0f0f0f1),
    truth_table_element(0, 0x3, false, 0x00000010),
    truth_table_element(0, 0x3, true,  0x00000001),
    truth_table_element(1, 0x1, false, 0xf0f0f0f2),
    truth_table_element(1, 0x2, false, 0xf0f0f0f3),
    truth_table_element(1, 0x3, false, 0x00000032),
    truth_table_element(1, 0x3, true,  0x00000023)
  };
  size_t nelements = sizeof(truth_table)/sizeof(truth_table[0]);
  
  truth_table_element target(ss.side, uses, swap_iq, 0);
  
  size_t i;
  for(i = 0; i < nelements; i++){
    if (truth_table[i] == target)
      return truth_table[i].mux_val();
  }
  throw std::runtime_error("internal error");
}

int
usrp_standard_rx::determine_rx_mux_value(const usrp_subdev_spec &ss_a, const usrp_subdev_spec &ss_b)
{
  std::vector<db_base_sptr> db_a = this->db(ss_a.side);
  std::vector<db_base_sptr> db_b = this->db(ss_b.side);
  if (db_a[ss_a.subdev]->is_quadrature() != db_b[ss_b.subdev]->is_quadrature()){
    throw std::runtime_error("Cannot compute dual mux when mixing quadrature and non-quadrature subdevices");
  }
  int mux_a = determine_rx_mux_value(ss_a);
  int mux_b = determine_rx_mux_value(ss_b);
  //move the lower byte of the mux b into the second byte of the mux a
  return ((mux_b & 0xff) << 8) | (mux_a & 0xffff00ff);
}

bool
usrp_standard_rx::set_rx_freq (int channel, double freq)
{
  if (channel < 0 || channel > MAX_CHAN)
    return false;

  unsigned int v =
    compute_freq_control_word_fpga (adc_rate(),
				    freq, &d_rx_freq[channel],
				    d_verbose);

  return _write_fpga_reg (FR_RX_FREQ_0 + channel, v);
}

unsigned int
usrp_standard_rx::decim_rate () const { return d_decim_rate; }

int
usrp_standard_rx::nchannels () const { return d_nchan; }

int
usrp_standard_rx::mux () const { return d_sw_mux; }

double 
usrp_standard_rx::rx_freq (int channel) const
{
  if (channel < 0 || channel >= MAX_CHAN)
    return 0;

  return d_rx_freq[channel];
}

bool
usrp_standard_rx::set_fpga_mode (int mode)
{
  return _write_fpga_reg (FR_MODE, mode);
}

bool
usrp_standard_rx::set_ddc_phase(int channel, int phase)
{
  if (channel < 0 || channel >= MAX_CHAN)
    return false;

  return _write_fpga_reg(FR_RX_PHASE_0 + channel, phase);
}


// To avoid quiet failures, check for things that our code cares about.

static bool
rx_format_is_valid(unsigned int format)
{
  int width =  usrp_standard_rx::format_width(format);
  int want_q = usrp_standard_rx::format_want_q(format);

  if (!(width == 8 || width == 16))	// FIXME add other widths when valid
    return false;

  if (!want_q)		// FIXME remove check when the rest of the code can handle I only
    return false;

  return true;
}

bool
usrp_standard_rx::set_format(unsigned int format)
{
  if (!rx_format_is_valid(format))
    return false;

  return _write_fpga_reg(FR_RX_FORMAT, format);
}

unsigned int
usrp_standard_rx::format() const
{
  return d_fpga_shadows[FR_RX_FORMAT];
}

// ----------------------------------------------------------------

unsigned int 
usrp_standard_rx::make_format(int width, int shift, bool want_q, bool bypass_halfband)
{
  unsigned int format = 
    (((width << bmFR_RX_FORMAT_WIDTH_SHIFT) & bmFR_RX_FORMAT_WIDTH_MASK)
     | ((shift << bmFR_RX_FORMAT_SHIFT_SHIFT) & bmFR_RX_FORMAT_SHIFT_MASK));

  if (want_q)
    format |= bmFR_RX_FORMAT_WANT_Q;
  if (bypass_halfband)
    format |= bmFR_RX_FORMAT_BYPASS_HB;

  return format;
}

int
usrp_standard_rx::format_width(unsigned int format)
{
  return (format & bmFR_RX_FORMAT_WIDTH_MASK) >> bmFR_RX_FORMAT_WIDTH_SHIFT;
}

int
usrp_standard_rx::format_shift(unsigned int format)
{
  return (format & bmFR_RX_FORMAT_SHIFT_MASK) >> bmFR_RX_FORMAT_SHIFT_SHIFT;
}

bool
usrp_standard_rx::format_want_q(unsigned int format)
{
  return (format & bmFR_RX_FORMAT_WANT_Q) != 0;
}

bool
usrp_standard_rx::format_bypass_halfband(unsigned int format)
{
  return (format & bmFR_RX_FORMAT_BYPASS_HB) != 0;
}

bool
usrp_standard_rx::tune(int chan, db_base_sptr db, double target_freq, usrp_tune_result *result)
{
  ddc_control dxc(this, chan);
  return tune_a_helper(db, target_freq, converter_rate(), dxc, result);
}


//////////////////////////////////////////////////////////////////


// tx data is timed to CLKOUT1 (64 MHz)
// interpolate 4x
// fine modulator enabled


static unsigned char tx_regs_use_nco[] = {
  REG_TX_IF,		(TX_IF_USE_CLKOUT1
			 | TX_IF_I_FIRST
			 | TX_IF_2S_COMP
			 | TX_IF_INTERLEAVED),
  REG_TX_DIGITAL,	(TX_DIGITAL_2_DATA_PATHS
			 | TX_DIGITAL_INTERPOLATE_4X)
};


static int
real_tx_mux_value (int mux, int nchan)
{
  if (mux != -1)
    return mux;

  switch (nchan){
  case 1:
    return 0x0098;
  case 2:
    return 0xba98;
  default:
    assert (0);
  }
}

usrp_standard_tx::usrp_standard_tx (int which_board,
				    unsigned int interp_rate,
				    int nchan, int mux,
				    int fusb_block_size, int fusb_nblocks,
				    const std::string fpga_filename,
				    const std::string firmware_filename
				    )
  : usrp_basic_tx (which_board, fusb_block_size, fusb_nblocks, fpga_filename, firmware_filename),
    usrp_standard_common(this),
    d_sw_mux (0x8), d_hw_mux (0x81)
{
  if (!usrp_9862_write_many_all (d_udh, tx_regs_use_nco, sizeof (tx_regs_use_nco))){
    fprintf (stderr, "usrp_standard_tx: failed to init AD9862 TX regs\n");
    throw std::runtime_error ("usrp_standard_tx::ctor");
  }
  if (!set_nchannels (nchan)){
    fprintf (stderr, "usrp_standard_tx: set_nchannels failed\n");
    throw std::runtime_error ("usrp_standard_tx::ctor");
  }
  if (!set_interp_rate (interp_rate)){
    fprintf (stderr, "usrp_standard_tx: set_interp_rate failed\n");
    throw std::runtime_error ("usrp_standard_tx::ctor");
  }
  if (!set_mux (real_tx_mux_value (mux, nchan))){
    fprintf (stderr, "usrp_standard_tx: set_mux failed\n");
    throw std::runtime_error ("usrp_standard_tx::ctor");
  }

  for (int i = 0; i < MAX_CHAN; i++){
    d_tx_modulator_shadow[i] = (TX_MODULATOR_DISABLE_NCO
				| TX_MODULATOR_COARSE_MODULATION_NONE);
    d_coarse_mod[i] = CM_OFF;
    set_tx_freq (i, 0);
  }
}

usrp_standard_tx::~usrp_standard_tx ()
{
  // fprintf(stderr, "\nusrp_standard_tx: dtor\n");
}

bool
usrp_standard_tx::start ()
{
  if (!usrp_basic_tx::start ())
    return false;

  // add our code here

  return true;
}

bool
usrp_standard_tx::stop ()
{
  bool ok = usrp_basic_tx::stop ();

  // add our code here

  return ok;
}

usrp_standard_tx_sptr
usrp_standard_tx::make (int which_board,
			unsigned int interp_rate,
			int nchan, int mux,
			int fusb_block_size, int fusb_nblocks,
			const std::string fpga_filename,
			const std::string firmware_filename
			)
{
  try {
    usrp_standard_tx_sptr u  = 
      usrp_standard_tx_sptr(new usrp_standard_tx(which_board, interp_rate, nchan, mux,
						 fusb_block_size, fusb_nblocks,
						 fpga_filename, firmware_filename));
    u->init_db(u);
    return u;
  }
  catch (...){
    return usrp_standard_tx_sptr();
  }
}

bool
usrp_standard_tx::set_interp_rate (unsigned int rate)
{
  // fprintf (stderr, "usrp_standard_tx::set_interp_rate\n");

  if ((rate & 0x3) || rate < 4 || rate > 512){
    fprintf (stderr, "usrp_standard_tx::set_interp_rate: rate must be in [4, 512] and a multiple of 4.\n");
    return false;
  }

  d_interp_rate = rate;
  set_usb_data_rate ((dac_rate () / rate * nchannels ())
		     * (2 * sizeof (short)));

  // We're using the interp by 4 feature of the 9862 so that we can
  // use its fine modulator.  Thus, we reduce the FPGA's interpolation rate
  // by a factor of 4.

  bool s = disable_tx ();
  bool ok = _write_fpga_reg (FR_INTERP_RATE, d_interp_rate/4 - 1);
  restore_tx (s);
  return ok;
}

bool
usrp_standard_tx::set_nchannels (int nchan)
{
  if (!(nchan == 1 || nchan == 2))
    return false;

  if (nchan > nducs())
    return false;

  d_nchan = nchan;
  return write_hw_mux_reg ();
}

bool
usrp_standard_tx::set_mux (int mux)
{
  d_sw_mux = mux;
  d_hw_mux = mux << 4;
  return write_hw_mux_reg ();
}

bool
usrp_standard_tx::write_hw_mux_reg ()
{
  bool s = disable_tx ();
  bool ok = _write_fpga_reg (FR_TX_MUX, d_hw_mux | d_nchan);
  restore_tx (s);
  return ok;
}

int
usrp_standard_tx::determine_tx_mux_value(const usrp_subdev_spec &ss)
{
  /*
    Determine appropriate Tx mux value as a function of the subdevice choosen.

    @param u:           instance of USRP source
    @param subdev_spec: return value from subdev option parser.  
    @type  subdev_spec: (side, subdev), where side is 0 or 1 and subdev is 0
    @returns:           the Rx mux value
  
    This is simpler than the rx case.  Either you want to talk
    to side A or side B.  If you want to talk to both sides at once,
    determine the value manually.
  */

  if (!is_valid(ss))
    throw std::invalid_argument("subdev_spec");

  std::vector<db_base_sptr> db = this->db(ss.side);
  
  if(db[ss.subdev]->i_and_q_swapped()) {
    unsigned int mask[2] = {0x0089, 0x8900};
    return mask[ss.side];
  }
  else {
    unsigned int mask[2] = {0x0098, 0x9800};
    return mask[ss.side];
  }
}

int
usrp_standard_tx::determine_tx_mux_value(const usrp_subdev_spec &ss_a, const usrp_subdev_spec &ss_b)
{
  if (ss_a.side == ss_b.side && ss_a.subdev == ss_b.subdev){
    throw std::runtime_error("Cannot compute dual mux, repeated subdevice");
  }
  int mux_a = determine_tx_mux_value(ss_a);
  //Get the mux b:
  //	DAC0 becomes DAC2
  //	DAC1 becomes DAC3
  unsigned int mask[2] = {0x0022, 0x2200};
  int mux_b = determine_tx_mux_value(ss_b) + mask[ss_b.side];
  return mux_b | mux_a;
}

#ifdef USE_FPGA_TX_CORDIC

bool
usrp_standard_tx::set_tx_freq (int channel, double freq)
{
  if (channel < 0 || channel >= MAX_CHAN)
    return false;

  // This assumes we're running the 4x on-chip interpolator.

  unsigned int v =
    compute_freq_control_word_fpga (dac_rate () / 4,
				    freq, &d_tx_freq[channel],
				    d_verbose);

  return _write_fpga_reg (FR_TX_FREQ_0 + channel, v);
}


#else

bool
usrp_standard_tx::set_tx_freq (int channel, double freq)
{
  if (channel < 0 || channel >= MAX_CHAN)
    return false;

  // split freq into fine and coarse components

  coarse_mod_t	cm;
  double	coarse;

  double coarse_freq_1 = dac_rate () / 8; // First coarse frequency
  double coarse_freq_2 = dac_rate () / 4; // Second coarse frequency
  double coarse_limit_1 = coarse_freq_1 / 2; // Midpoint of [0 , freq1] range
  double coarse_limit_2 = (coarse_freq_1 + coarse_freq_2) / 2; // Midpoint of [freq1 , freq2] range
  double high_limit = (double)44e6/128e6*dac_rate (); // Highest meaningful frequency

  if (freq < -high_limit)		// too low
    return false;
  else if (freq < -coarse_limit_2){	// For 64MHz: [-44, -24)
    cm = CM_NEG_FDAC_OVER_4;
    coarse = -coarse_freq_2;
  }
  else if (freq < -coarse_limit_1){	// For 64MHz: [-24, -8)
    cm = CM_NEG_FDAC_OVER_8;
    coarse = -coarse_freq_1;
  }
  else if (freq < coarse_limit_1){		// For 64MHz: [-8, 8)
    cm = CM_OFF;
    coarse = 0;
  }
  else if (freq < coarse_limit_2){	// For 64MHz: [8, 24)
    cm = CM_POS_FDAC_OVER_8;
    coarse = coarse_freq_1;
  }
  else if (freq <= high_limit){	// For 64MHz: [24, 44]
    cm = CM_POS_FDAC_OVER_4;
    coarse = coarse_freq_2;
  }
  else				// too high
    return false;


  set_coarse_modulator (channel, cm);	// set bits in d_tx_modulator_shadow

  double fine = freq - coarse;


  // Compute fine tuning word...
  // This assumes we're running the 4x on-chip interpolator.
  // (This is required to use the fine modulator.)

  unsigned int v =
    compute_freq_control_word_9862 (dac_rate () / 4,
				    fine, &d_tx_freq[channel], d_verbose);

  d_tx_freq[channel] += coarse;		// adjust actual
  
  unsigned char high, mid, low;

  high = (v >> 16) & 0xff;
  mid =  (v >>  8) & 0xff;
  low =  (v >>  0) & 0xff;

  bool ok = true;

  // write the fine tuning word
  ok &= _write_9862 (channel, REG_TX_NCO_FTW_23_16, high);
  ok &= _write_9862 (channel, REG_TX_NCO_FTW_15_8,  mid);
  ok &= _write_9862 (channel, REG_TX_NCO_FTW_7_0,   low);


  d_tx_modulator_shadow[channel] |= TX_MODULATOR_ENABLE_NCO;

  if (fine < 0)
    d_tx_modulator_shadow[channel] |= TX_MODULATOR_NEG_FINE_TUNE;
  else
    d_tx_modulator_shadow[channel] &= ~TX_MODULATOR_NEG_FINE_TUNE;

  ok &=_write_9862 (channel, REG_TX_MODULATOR, d_tx_modulator_shadow[channel]);

  return ok;
}
#endif

bool
usrp_standard_tx::set_coarse_modulator (int channel, coarse_mod_t cm)
{
  if (channel < 0 || channel >= MAX_CHAN)
    return false;

  switch (cm){
  case CM_NEG_FDAC_OVER_4:
    d_tx_modulator_shadow[channel] &= ~TX_MODULATOR_CM_MASK;
    d_tx_modulator_shadow[channel] |= TX_MODULATOR_COARSE_MODULATION_F_OVER_4;
    d_tx_modulator_shadow[channel] |= TX_MODULATOR_NEG_COARSE_TUNE;
    break;

  case CM_NEG_FDAC_OVER_8:
    d_tx_modulator_shadow[channel] &= ~TX_MODULATOR_CM_MASK;
    d_tx_modulator_shadow[channel] |= TX_MODULATOR_COARSE_MODULATION_F_OVER_8;
    d_tx_modulator_shadow[channel] |= TX_MODULATOR_NEG_COARSE_TUNE;
    break;

  case CM_OFF:
    d_tx_modulator_shadow[channel] &= ~TX_MODULATOR_CM_MASK;
    break;

  case CM_POS_FDAC_OVER_8:
    d_tx_modulator_shadow[channel] &= ~TX_MODULATOR_CM_MASK;
    d_tx_modulator_shadow[channel] |= TX_MODULATOR_COARSE_MODULATION_F_OVER_8;
    break;

  case CM_POS_FDAC_OVER_4:
    d_tx_modulator_shadow[channel] &= ~TX_MODULATOR_CM_MASK;
    d_tx_modulator_shadow[channel] |= TX_MODULATOR_COARSE_MODULATION_F_OVER_4;
    break;

  default:
    return false;
  }

  d_coarse_mod[channel] = cm;
  return true;
}

unsigned int
usrp_standard_tx::interp_rate () const { return d_interp_rate; }

int
usrp_standard_tx::nchannels () const { return d_nchan; }

int
usrp_standard_tx::mux () const { return d_sw_mux; }

double
usrp_standard_tx::tx_freq (int channel) const
{
  if (channel < 0 || channel >= MAX_CHAN)
    return 0;

  return d_tx_freq[channel];
}

usrp_standard_tx::coarse_mod_t
usrp_standard_tx::coarse_modulator (int channel) const
{
  if (channel < 0 || channel >= MAX_CHAN)
    return CM_OFF;

  return d_coarse_mod[channel];
}

bool
usrp_standard_tx::tune(int chan, db_base_sptr db, double target_freq, usrp_tune_result *result)
{
  duc_control dxc(this, chan);
  return tune_a_helper(db, target_freq, converter_rate(), dxc, result);
}