3d030432429c42d270743697840161552f4db43f
[debian/gnuradio] / usrp2 / host / lib / usrp2_impl.cc
1 /* -*- c++ -*- */
2 /*
3  * Copyright 2008,2009 Free Software Foundation, Inc.
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation, either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
17  */
18
19 #ifdef HAVE_CONFIG_H
20 #include <config.h>
21 #endif
22
23 #include <usrp2/usrp2.h>
24 #include <usrp2/tune_result.h>
25 #include <usrp2/copiers.h>
26 #include <gruel/inet.h>
27 #include <usrp2_types.h>
28 #include "usrp2_impl.h"
29 #include "usrp2_thread.h"
30 #include "eth_buffer.h"
31 #include "pktfilter.h"
32 #include "control.h"
33 #include "ring.h"
34 #include <stdexcept>
35 #include <iostream>
36 #include <stdio.h>
37 #include <stddef.h>
38 #include <assert.h>
39 #include <string.h>
40
41 #define USRP2_IMPL_DEBUG 0
42 #if USRP2_IMPL_DEBUG
43 #define DEBUG_LOG(x) ::write(2, x, 1)
44 #else
45 #define DEBUG_LOG(x)
46 #endif
47
48 static const int DEFAULT_RX_SCALE = 1024;
49
50 namespace usrp2 {
51
52   static const double DEF_CMD_TIMEOUT = 0.1;
53
54   std::string
55   opcode_to_string(int opcode)
56   {
57     switch(opcode){
58     case OP_EOP: return "OP_EOP";
59     case OP_ID: return "OP_ID";
60     case OP_ID_REPLY: return "OP_ID_REPLY";
61     case OP_BURN_MAC_ADDR: return "OP_BURN_MAC_ADDR";
62     case OP_READ_TIME: return "OP_READ_TIME";
63     case OP_READ_TIME_REPLY: return "OP_READ_TIME_REPLY";
64     case OP_CONFIG_RX_V2: return "OP_CONFIG_RX_V2";
65     case OP_CONFIG_RX_REPLY_V2: return "OP_CONFIG_RX_REPLY_V2";
66     case OP_CONFIG_TX_V2: return "OP_CONFIG_TX_V2";
67     case OP_CONFIG_TX_REPLY_V2: return "OP_CONFIG_TX_REPLY_V2";
68     case OP_START_RX_STREAMING: return "OP_START_RX_STREAMING";
69     case OP_STOP_RX: return "OP_STOP_RX";
70     case OP_CONFIG_MIMO: return "OP_CONFIG_MIMO";
71     case OP_DBOARD_INFO: return "OP_DBOARD_INFO";
72     case OP_DBOARD_INFO_REPLY: return "OP_DBOARD_INFO_REPLY";
73     case OP_SYNC_TO_PPS: return "OP_SYNC_TO_PPS";
74     case OP_PEEK: return "OP_PEEK";
75     case OP_PEEK_REPLY: return "OP_PEEK_REPLY";
76     case OP_SET_TX_LO_OFFSET: return "OP_SET_TX_LO_OFFSET";
77     case OP_SET_TX_LO_OFFSET_REPLY: return "OP_SET_TX_LO_OFFSET_REPLY";
78     case OP_SET_RX_LO_OFFSET: return "OP_SET_RX_LO_OFFSET";
79     case OP_SET_RX_LO_OFFSET_REPLY: return "OP_SET_RX_LO_OFFSET_REPLY";
80     case OP_SYNC_EVERY_PPS: return "OP_SYNC_EVERY_PPS";
81     case OP_SYNC_EVERY_PPS_REPLY: return "OP_SYNC_EVERY_PPS_REPLY";
82
83     default:
84       char buf[64];
85       snprintf(buf, sizeof(buf), "<unknown opcode: %d>", opcode);
86       return buf;
87     }
88   }
89
90
91   /*!
92    * \param p points to fixed header
93    * \param payload_len_in_bytes is length of the fixed hdr and the payload
94    * \param[out] items is set to point to the first uint32 item in the payload
95    * \param[out] nitems is set to the number of uint32 items in the payload
96    * \param[out] md is filled in with the parsed metadata from the frame.
97    */
98   static bool
99   parse_rx_metadata(void *p, size_t payload_len_in_bytes,
100                     uint32_t **items, size_t *nitems_in_uint32s, rx_metadata *md)
101   {
102     if (payload_len_in_bytes < sizeof(u2_fixed_hdr_t))  // invalid format
103       return false;
104
105     // FIXME deal with the fact that (p % 4) == 2
106     //assert((((uintptr_t) p) % 4) == 0);               // must be 4-byte aligned
107
108     u2_fixed_hdr_t *fh = static_cast<u2_fixed_hdr_t *>(p);
109     
110     // FIXME unaligned loads!
111     md->word0 = u2p_word0(fh);
112     md->timestamp = u2p_timestamp(fh);
113
114     // FIXME when we've got more info
115     // md->start_of_burst = (md->word0 & XXX) != 0;
116     // md->end_of_burst =   (md->word0 & XXX) != 0;
117     // md->rx_overrun =     (md->word0 & XXX) != 0;
118     md->start_of_burst = 0;
119     md->end_of_burst =   0;
120     md->rx_overrun =     0;
121
122     *items = (uint32_t *)(&fh[1]);
123     size_t nbytes = payload_len_in_bytes - sizeof(u2_fixed_hdr_t);
124     assert((nbytes % sizeof(uint32_t)) == 0);
125     *nitems_in_uint32s = nbytes / sizeof(uint32_t);
126
127     return true;
128   }
129
130
131   usrp2::impl::impl(const std::string &ifc, props *p, size_t rx_bufsize)
132     : d_eth_buf(new eth_buffer(rx_bufsize)), d_interface_name(ifc), d_pf(0), d_bg_thread(0),
133       d_bg_running(false), d_rx_seqno(-1), d_tx_seqno(0), d_next_rid(0),
134       d_num_rx_frames(0), d_num_rx_missing(0), d_num_rx_overruns(0), d_num_rx_bytes(0), 
135       d_num_enqueued(0), d_enqueued_mutex(), d_bg_pending_cond(&d_enqueued_mutex),
136       d_channel_rings(NCHANS), d_tx_interp(0), d_rx_decim(0), d_dont_enqueue(true)
137   {
138     if (!d_eth_buf->open(ifc, htons(U2_ETHERTYPE)))
139       throw std::runtime_error("Unable to register USRP2 protocol");
140     
141     d_addr = p->addr;
142
143     // Create a packet filter for U2_ETHERTYPE packets sourced from target USRP2
144     u2_mac_addr_t usrp_mac;
145     parse_mac_addr(d_addr, &usrp_mac);
146     d_pf = pktfilter::make_ethertype_inbound_target(U2_ETHERTYPE, (const unsigned char*)&(usrp_mac.addr));
147     if (!d_pf || !d_eth_buf->attach_pktfilter(d_pf))
148       throw std::runtime_error("Unable to attach packet filter.");
149     
150     if (USRP2_IMPL_DEBUG)
151       std::cerr << "usrp2 constructor: using USRP2 at " << d_addr << std::endl;
152
153     memset(d_pending_replies, 0, sizeof(d_pending_replies));
154
155     d_bg_thread = new usrp2_thread(this);
156     d_bg_thread->start();
157
158     // In case the USRP2 was left streaming RX
159     // FIXME: only one channel right now
160     stop_rx_streaming(0);
161
162     if (!dboard_info())         // we're hosed
163       throw std::runtime_error("Unable to retrieve daughterboard info");
164
165     if (0){
166       int dbid;
167
168       tx_daughterboard_id(&dbid);
169       fprintf(stderr, "Tx dboard 0x%x\n", dbid);
170       fprintf(stderr, "  freq_min = %g\n", tx_freq_min());
171       fprintf(stderr, "  freq_max = %g\n", tx_freq_max());
172       fprintf(stderr, "  gain_min = %g\n", tx_gain_min());
173       fprintf(stderr, "  gain_max = %g\n", tx_gain_max());
174       fprintf(stderr, "  gain_db_per_step = %g\n", tx_gain_db_per_step());
175
176       rx_daughterboard_id(&dbid);
177       fprintf(stderr, "Rx dboard 0x%x\n", dbid);
178       fprintf(stderr, "  freq_min = %g\n", rx_freq_min());
179       fprintf(stderr, "  freq_max = %g\n", rx_freq_max());
180       fprintf(stderr, "  gain_min = %g\n", rx_gain_min());
181       fprintf(stderr, "  gain_max = %g\n", rx_gain_max());
182       fprintf(stderr, "  gain_db_per_step = %g\n", rx_gain_db_per_step());
183     }
184
185     // Ensure any custom values in hardware are cleared
186     if (!reset_db())
187       std::cerr << "usrp2::ctor reset_db failed\n";
188
189     // default gains to mid point
190     if (!set_tx_gain((tx_gain_min() + tx_gain_max()) / 2))
191       std::cerr << "usrp2::ctor set_tx_gain failed\n";
192
193     if (!set_rx_gain((rx_gain_min() + rx_gain_max()) / 2))
194       std::cerr << "usrp2::ctor set_rx_gain failed\n";
195
196     // default interp and decim
197     if (!set_tx_interp(12))
198       std::cerr << "usrp2::ctor set_tx_interp failed\n";
199
200     if (!set_rx_decim(12))
201       std::cerr << "usrp2::ctor set_rx_decim failed\n";
202       
203     // set workable defaults for scaling
204     if (!set_rx_scale_iq(DEFAULT_RX_SCALE, DEFAULT_RX_SCALE))
205       std::cerr << "usrp2::ctor set_rx_scale_iq failed\n";
206   }
207   
208   usrp2::impl::~impl()
209   {
210     stop_bg();
211     d_bg_thread = 0; // thread class deletes itself
212     delete d_pf;
213     d_eth_buf->close();
214     delete d_eth_buf;
215     
216     if (USRP2_IMPL_DEBUG) {
217       std::cerr << std::endl
218                 << "usrp2 destructor: received " << d_num_rx_frames 
219                 << " frames, with " << d_num_rx_missing << " lost ("
220                 << (d_num_rx_frames == 0 ? 0 : (int)(100.0*d_num_rx_missing/d_num_rx_frames))
221                 << "%), totaling " << d_num_rx_bytes
222                 << " bytes" << std::endl;
223     }
224   }
225   
226   bool
227   usrp2::impl::parse_mac_addr(const std::string &s, u2_mac_addr_t *p)
228   {
229     p->addr[0] = 0x00;          // Matt's IAB
230     p->addr[1] = 0x50;
231     p->addr[2] = 0xC2;
232     p->addr[3] = 0x85;
233     p->addr[4] = 0x30;
234     p->addr[5] = 0x00;
235     
236     int len = s.size();
237     
238     switch (len){
239       
240     case 5:
241       return sscanf(s.c_str(), "%hhx:%hhx", &p->addr[4], &p->addr[5]) == 2;
242       
243     case 17:
244       return sscanf(s.c_str(), "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx",
245                     &p->addr[0], &p->addr[1], &p->addr[2],
246                     &p->addr[3], &p->addr[4], &p->addr[5]) == 6;
247     default:
248       return false;
249     }
250   }
251   
252   void
253   usrp2::impl::init_et_hdrs(u2_eth_packet_t *p, const std::string &dst)
254   {
255     p->ehdr.ethertype = htons(U2_ETHERTYPE);
256     parse_mac_addr(dst, &p->ehdr.dst); 
257     memcpy(&p->ehdr.src, d_eth_buf->mac(), 6);
258     p->thdr.flags = 0; // FIXME transport header values?
259     p->thdr.seqno = d_tx_seqno++;
260     p->thdr.ack = 0;
261   }
262   
263   void 
264   usrp2::impl::init_etf_hdrs(u2_eth_packet_t *p, const std::string &dst,
265                              int word0_flags, int chan, uint32_t timestamp)
266   {
267     init_et_hdrs(p, dst);
268     u2p_set_word0(&p->fixed, word0_flags, chan);
269     u2p_set_timestamp(&p->fixed, timestamp);
270     
271     if (chan == CONTROL_CHAN) { // no sequence numbers, back it out
272       p->thdr.seqno = 0;
273       d_tx_seqno--;
274     }
275   }
276   
277   void
278   usrp2::impl::init_config_rx_v2_cmd(op_config_rx_v2_cmd *cmd)
279   {
280     memset(cmd, 0, sizeof(*cmd)); 
281     init_etf_hdrs(&cmd->h, d_addr, 0, CONTROL_CHAN, -1);
282     cmd->op.opcode = OP_CONFIG_RX_V2;
283     cmd->op.len = sizeof(cmd->op);
284     cmd->op.rid = d_next_rid++;
285     cmd->eop.opcode = OP_EOP;
286     cmd->eop.len = sizeof(cmd->eop);
287   }
288
289   void
290   usrp2::impl::init_config_tx_v2_cmd(op_config_tx_v2_cmd *cmd)
291   {
292     memset(cmd, 0, sizeof(*cmd)); 
293     init_etf_hdrs(&cmd->h, d_addr, 0, CONTROL_CHAN, -1);
294     cmd->op.opcode = OP_CONFIG_TX_V2;
295     cmd->op.len = sizeof(cmd->op);
296     cmd->op.rid = d_next_rid++;
297     cmd->eop.opcode = OP_EOP;
298     cmd->eop.len = sizeof(cmd->eop);
299   }
300
301
302   bool
303   usrp2::impl::transmit_cmd(void *cmd_, size_t len_)
304   {
305     const void *cmd = cmd_;
306     int len = len_;
307     unsigned char tmp[64];
308
309     if (len_ < 64){             // pad to minimum ethernet frame size
310       memset(tmp, 0, sizeof(tmp));
311       memcpy(tmp, cmd_, len_);
312       cmd = tmp;
313       len = sizeof(tmp);
314     }
315
316     return d_eth_buf->tx_frame(cmd, len) == eth_buffer::EB_OK;
317   }
318
319   bool
320   usrp2::impl::transmit_cmd_and_wait(void *cmd, size_t len, pending_reply *p, double secs)
321   {
322     d_pending_replies[p->rid()] = p;
323     
324     if (!transmit_cmd(cmd, len)){
325       d_pending_replies[p->rid()] = 0;
326       return false;
327     }
328
329     int res = p->wait_for_completion(secs);
330     d_pending_replies[p->rid()] = 0;
331     return res == 1;
332   }
333
334   // ----------------------------------------------------------------
335   //        Background loop: received packet demuxing
336   // ----------------------------------------------------------------
337
338   void
339   usrp2::impl::stop_bg()
340   {
341     d_bg_running = false;
342     d_bg_pending_cond.signal();
343     
344     void *dummy_status;
345     d_bg_thread->join(&dummy_status);  
346   }
347   
348   void
349   usrp2::impl::bg_loop()
350   {
351     d_bg_running = true;
352     while(d_bg_running) {
353       DEBUG_LOG(":");
354       // Receive available frames from ethernet buffer.  Handler will
355       // process control frames, enqueue data packets in channel
356       // rings, and signal blocked API threads
357       int res = d_eth_buf->rx_frames(this, 100); // FIXME magic timeout
358       if (res == eth_buffer::EB_ERROR)
359         break;  
360
361       // Wait for user API thread(s) to process all enqueued packets.
362       // The channel ring thread that decrements d_num_enqueued to zero 
363       // will signal this thread to continue.
364       {
365         omni_mutex_lock l(d_enqueued_mutex);
366         while(d_num_enqueued > 0 && d_bg_running)
367           d_bg_pending_cond.wait();
368       }
369     }
370     d_bg_running = false;
371   }
372   
373   //
374   // passed to eth_buffer::rx_frames
375   //
376   data_handler::result
377   usrp2::impl::operator()(const void *base, size_t len)
378   {
379     u2_eth_samples_t *pkt = (u2_eth_samples_t *)base;
380
381     // FIXME unaligned load!
382     int chan = u2p_chan(&pkt->hdrs.fixed);
383
384     if (chan == CONTROL_CHAN) {         // control packets
385       DEBUG_LOG("c");
386       return handle_control_packet(base, len);
387     }
388     else {                              // data packets
389
390       if (d_dont_enqueue)               // toss packet
391         return data_handler::RELEASE;
392
393       return handle_data_packet(base, len);
394     }
395
396     // not reached
397   }
398
399   data_handler::result
400   usrp2::impl::handle_control_packet(const void *base, size_t len)
401   {
402     // point to beginning of payload (subpackets)
403     unsigned char *p = (unsigned char *)base + sizeof(u2_eth_packet_t);
404     
405     // FIXME (p % 4) == 2.  Not good.  Must watch for unaligned loads.
406
407     // FIXME iterate over payload, handling more than a single subpacket.
408     
409     int opcode = p[0];
410     unsigned int oplen = p[1];
411     unsigned int rid = p[2];
412
413     pending_reply *rp = d_pending_replies[rid];
414     if (rp) {
415       unsigned int buflen = rp->len();
416       if (oplen != buflen) {
417         std::cerr << "usrp2: mismatched command reply length (expected: "
418                   << buflen << " got: " << oplen << "). "
419                   << "op = " << opcode_to_string(opcode) << std::endl;
420       }     
421     
422       // Copy reply into caller's buffer
423       memcpy(rp->buffer(), p, std::min(oplen, buflen));
424       rp->notify_completion();
425       d_pending_replies[rid] = 0;
426       return data_handler::RELEASE;
427     }
428
429     // TODO: handle unsolicited, USRP2 initiated, or late replies
430     DEBUG_LOG("l");
431     return data_handler::RELEASE;
432   }
433   
434   data_handler::result
435   usrp2::impl::handle_data_packet(const void *base, size_t len)
436   {
437     u2_eth_samples_t *pkt = (u2_eth_samples_t *)base;
438     d_num_rx_frames++;
439     d_num_rx_bytes += len;
440     
441     /* --- FIXME start of fake transport layer handler --- */
442
443     if (d_rx_seqno != -1) {
444       int expected_seqno = (d_rx_seqno + 1) & 0xFF;
445       int seqno = pkt->hdrs.thdr.seqno; 
446       
447       if (seqno != expected_seqno) {
448         ::write(2, "S", 1); // missing sequence number
449         int missing = seqno - expected_seqno;
450         if (missing < 0)
451           missing += 256;
452         
453         d_num_rx_overruns++;
454         d_num_rx_missing += missing;
455       }
456     }
457
458     d_rx_seqno = pkt->hdrs.thdr.seqno;
459
460     /* --- end of fake transport layer handler --- */
461
462     // FIXME unaligned load!
463     unsigned int chan = u2p_chan(&pkt->hdrs.fixed);
464
465     {
466       omni_mutex_lock l(d_channel_rings_mutex);
467
468       if (!d_channel_rings[chan]) {
469         DEBUG_LOG("!");
470         return data_handler::RELEASE;   // discard packet, no channel handler
471       }
472       
473       // Strip off ethernet header and transport header and enqueue the rest
474       
475       size_t offset = offsetof(u2_eth_samples_t, hdrs.fixed);
476       if (d_channel_rings[chan]->enqueue(&pkt->hdrs.fixed, len-offset)) {
477         inc_enqueued();
478         DEBUG_LOG("+");
479         return data_handler::KEEP;      // channel ring runner will mark frame done
480       }
481       else {
482         DEBUG_LOG("!");
483         return data_handler::RELEASE;   // discard, no room in channel ring
484       }         
485       return data_handler::RELEASE;
486     }
487   }
488
489
490   // ----------------------------------------------------------------
491   //                           Receive
492   // ----------------------------------------------------------------
493
494   bool 
495   usrp2::impl::set_rx_gain(double gain)
496   {
497     op_config_rx_v2_cmd cmd;
498     op_config_rx_reply_v2_t reply;
499
500     init_config_rx_v2_cmd(&cmd);
501     cmd.op.valid = htons(CFGV_GAIN);
502     cmd.op.gain = htons(u2_double_to_fxpt_gain(gain));
503     
504     pending_reply p(cmd.op.rid, &reply, sizeof(reply));
505     if (!transmit_cmd_and_wait(&cmd, sizeof(cmd), &p, DEF_CMD_TIMEOUT))
506       return false;
507
508     bool success = (ntohx(reply.ok) == 1);
509     return success;
510   }
511   
512   bool
513   usrp2::impl::set_rx_lo_offset(double frequency)
514   {
515     op_freq_cmd cmd;
516     op_generic_t reply;
517
518     memset(&cmd, 0, sizeof(cmd));
519     init_etf_hdrs(&cmd.h, d_addr, 0, CONTROL_CHAN, -1);
520     cmd.op.opcode = OP_SET_RX_LO_OFFSET;
521     cmd.op.len = sizeof(cmd.op);
522     cmd.op.rid = d_next_rid++;
523
524     u2_fxpt_freq_t fxpt = u2_double_to_fxpt_freq(frequency);
525     cmd.op.freq_hi = htonl(u2_fxpt_freq_hi(fxpt));
526     cmd.op.freq_lo = htonl(u2_fxpt_freq_lo(fxpt));
527
528     cmd.eop.opcode = OP_EOP;
529     cmd.eop.len = sizeof(cmd.eop);
530     
531     pending_reply p(cmd.op.rid, &reply, sizeof(reply));
532     if (!transmit_cmd_and_wait(&cmd, sizeof(cmd), &p, DEF_CMD_TIMEOUT))
533       return false;
534
535     bool success = (ntohx(reply.ok) == 1);
536     return success;
537   }
538
539   bool
540   usrp2::impl::set_rx_center_freq(double frequency, tune_result *result)
541   {
542     op_config_rx_v2_cmd cmd;
543     op_config_rx_reply_v2_t reply;
544
545     init_config_rx_v2_cmd(&cmd);
546     cmd.op.valid = htons(CFGV_FREQ);
547     u2_fxpt_freq_t fxpt = u2_double_to_fxpt_freq(frequency);
548     cmd.op.freq_hi = htonl(u2_fxpt_freq_hi(fxpt));
549     cmd.op.freq_lo = htonl(u2_fxpt_freq_lo(fxpt));
550     
551     pending_reply p(cmd.op.rid, &reply, sizeof(reply));
552     if (!transmit_cmd_and_wait(&cmd, sizeof(cmd), &p, DEF_CMD_TIMEOUT))
553       return false;
554
555     bool success = (ntohx(reply.ok) == 1);
556     if (result && success) {
557       result->baseband_freq =
558         u2_fxpt_freq_to_double( 
559           u2_fxpt_freq_from_hilo(ntohl(reply.baseband_freq_hi), 
560                                  ntohl(reply.baseband_freq_lo)));
561
562       result->dxc_freq =
563         u2_fxpt_freq_to_double( 
564           u2_fxpt_freq_from_hilo(ntohl(reply.ddc_freq_hi), 
565                                  ntohl(reply.ddc_freq_lo)));
566
567       result->residual_freq =
568         u2_fxpt_freq_to_double( 
569          u2_fxpt_freq_from_hilo(ntohl(reply.residual_freq_hi), 
570                                 ntohl(reply.residual_freq_lo)));
571
572       result->spectrum_inverted = (bool)(ntohx(reply.inverted) == 1);
573     }
574
575     return success;
576   }
577   
578   bool
579   usrp2::impl::set_rx_decim(int decimation_factor)
580   {
581     op_config_rx_v2_cmd cmd;
582     op_config_rx_reply_v2_t reply;
583
584     init_config_rx_v2_cmd(&cmd);
585     cmd.op.valid = htons(CFGV_INTERP_DECIM);
586     cmd.op.decim = htonl(decimation_factor);
587     
588     pending_reply p(cmd.op.rid, &reply, sizeof(reply));
589     if (!transmit_cmd_and_wait(&cmd, sizeof(cmd), &p, DEF_CMD_TIMEOUT))
590       return false;
591
592     bool success = (ntohx(reply.ok) == 1);
593     if (success)
594       d_rx_decim = decimation_factor;
595     return success;
596   }
597   
598   bool
599   usrp2::impl::set_rx_scale_iq(int scale_i, int scale_q)
600   {
601     op_config_rx_v2_cmd cmd;
602     op_config_rx_reply_v2_t reply;
603
604     init_config_rx_v2_cmd(&cmd);
605     cmd.op.valid = htons(CFGV_SCALE_IQ);
606     cmd.op.scale_iq = htonl(((scale_i & 0xffff) << 16) | (scale_q & 0xffff));
607     
608     pending_reply p(cmd.op.rid, &reply, sizeof(reply));
609     if (!transmit_cmd_and_wait(&cmd, sizeof(cmd), &p, DEF_CMD_TIMEOUT))
610       return false;
611
612     bool success = (ntohx(reply.ok) == 1);
613     return success;
614   }
615   
616   bool
617   usrp2::impl::start_rx_streaming(unsigned int channel, unsigned int items_per_frame)
618   {
619     if (channel > MAX_CHAN) {
620       std::cerr << "usrp2: invalid channel number (" << channel
621                 << ")" << std::endl;
622       return false;
623     }
624
625     if (channel > 0) { // until firmware supports multiple streams
626       std::cerr << "usrp2: channel " << channel
627                 << " not implemented" << std::endl;
628       return false;
629     }
630
631     {
632       omni_mutex_lock l(d_channel_rings_mutex);
633       if (d_channel_rings[channel]) {
634         std::cerr << "usrp2: channel " << channel
635                   << " already streaming" << std::endl;
636         return false;
637       }
638       
639       if (items_per_frame == 0)
640         items_per_frame = U2_MAX_SAMPLES;               // minimize overhead
641       
642       op_start_rx_streaming_cmd cmd;
643       op_generic_t reply;
644
645       memset(&cmd, 0, sizeof(cmd));
646       init_etf_hdrs(&cmd.h, d_addr, 0, CONTROL_CHAN, -1);
647       cmd.op.opcode = OP_START_RX_STREAMING;
648       cmd.op.len = sizeof(cmd.op);
649       cmd.op.rid = d_next_rid++;
650       cmd.op.items_per_frame = htonl(items_per_frame);
651       cmd.eop.opcode = OP_EOP;
652       cmd.eop.len = sizeof(cmd.eop);
653     
654       d_dont_enqueue = false;
655       bool success = false;
656       pending_reply p(cmd.op.rid, &reply, sizeof(reply));
657       success = transmit_cmd_and_wait(&cmd, sizeof(cmd), &p, DEF_CMD_TIMEOUT);
658       success = success && (ntohx(reply.ok) == 1);
659       
660       if (success)
661         d_channel_rings[channel] = ring_sptr(new ring(d_eth_buf->max_frames()));
662       else
663         d_dont_enqueue = true;
664
665       //fprintf(stderr, "usrp2::start_rx_streaming: success = %d\n", success);
666       return success;
667     }
668   }
669   
670   bool
671   usrp2::impl::stop_rx_streaming(unsigned int channel)
672   {
673     if (channel > MAX_CHAN) {
674       std::cerr << "usrp2: invalid channel number (" << channel
675                 << ")" << std::endl;
676       return false;
677     }
678
679     if (channel > 0) { // until firmware supports multiple streams
680       std::cerr << "usrp2: channel " << channel
681                 << " not implemented" << std::endl;
682       return false;
683     }
684
685     d_dont_enqueue = true;      // no new samples
686     flush_rx_samples(channel);  // dump any we may already have
687
688     op_stop_rx_cmd cmd;
689     op_generic_t reply;
690
691     {
692       omni_mutex_lock l(d_channel_rings_mutex);
693
694       memset(&cmd, 0, sizeof(cmd));
695       init_etf_hdrs(&cmd.h, d_addr, 0, CONTROL_CHAN, -1);
696       cmd.op.opcode = OP_STOP_RX;
697       cmd.op.len = sizeof(cmd.op);
698       cmd.op.rid = d_next_rid++;
699       cmd.eop.opcode = OP_EOP;
700       cmd.eop.len = sizeof(cmd.eop);
701     
702       bool success = false;
703       pending_reply p(cmd.op.rid, &reply, sizeof(reply));
704       success = transmit_cmd_and_wait(&cmd, sizeof(cmd), &p, DEF_CMD_TIMEOUT);
705       success = success && (ntohx(reply.ok) == 1);
706       d_channel_rings[channel].reset();
707       //fprintf(stderr, "usrp2::stop_rx_streaming:  success = %d\n", success);
708       return success;
709     }
710   }
711
712   bool
713   usrp2::impl::rx_samples(unsigned int channel, rx_sample_handler *handler)
714   {
715     if (channel > MAX_CHAN) {
716       std::cerr << "usrp2: invalid channel (" << channel
717                 << " )" << std::endl;
718       return false;
719     }
720     
721     if (channel > 0) {
722       std::cerr << "usrp2: channel " << channel
723                 << " not implemented" << std::endl;
724       return false;
725     }
726     
727     ring_sptr rp = d_channel_rings[channel];
728     if (!rp){
729       std::cerr << "usrp2: channel " << channel
730                 << " not receiving" << std::endl;
731       return false;
732     }
733     
734     // Wait for frames available in channel ring
735     DEBUG_LOG("W");
736     rp->wait_for_not_empty();
737     DEBUG_LOG("s");
738     
739     // Iterate through frames and present to user
740     void *p;
741     size_t frame_len_in_bytes;
742     while (rp->dequeue(&p, &frame_len_in_bytes)) {
743       uint32_t         *items;                  // points to beginning of data items
744       size_t            nitems_in_uint32s;
745       rx_metadata       md;
746       if (!parse_rx_metadata(p, frame_len_in_bytes, &items, &nitems_in_uint32s, &md))
747         return false;
748
749       bool want_more = (*handler)(items, nitems_in_uint32s, &md);
750       d_eth_buf->release_frame(p);
751       DEBUG_LOG("-");
752       dec_enqueued();
753
754       if (!want_more)
755         break;
756     }
757     return true;
758   }
759
760   bool
761   usrp2::impl::flush_rx_samples(unsigned int channel)
762   {
763     if (channel > MAX_CHAN) {
764       std::cerr << "usrp2: invalid channel (" << channel
765                 << " )" << std::endl;
766       return false;
767     }
768
769     if (channel > 0) {
770       std::cerr << "usrp2: channel " << channel
771                 << " not implemented" << std::endl;
772       return false;
773     }
774
775     ring_sptr rp = d_channel_rings[channel];
776     if (!rp){
777       return false;
778     }
779
780     // Iterate through frames and drop them
781     void *p;
782     size_t frame_len_in_bytes;
783     while (rp->dequeue(&p, &frame_len_in_bytes)) {
784       d_eth_buf->release_frame(p);
785       dec_enqueued();
786     }
787     return true;
788   }
789
790   // ----------------------------------------------------------------
791   //                            Transmit
792   // ----------------------------------------------------------------
793
794   bool 
795   usrp2::impl::set_tx_gain(double gain)
796   {
797     op_config_tx_v2_cmd cmd;
798     op_config_tx_reply_v2_t reply;
799
800     init_config_tx_v2_cmd(&cmd);
801     cmd.op.valid = htons(CFGV_GAIN);
802     cmd.op.gain = htons(u2_double_to_fxpt_gain(gain));
803     
804     pending_reply p(cmd.op.rid, &reply, sizeof(reply));
805     if (!transmit_cmd_and_wait(&cmd, sizeof(cmd), &p, DEF_CMD_TIMEOUT))
806       return false;
807
808     bool success = (ntohx(reply.ok) == 1);
809     return success;
810   }
811   
812   bool
813   usrp2::impl::set_tx_lo_offset(double frequency)
814   {
815     op_freq_cmd cmd;
816     op_generic_t reply;
817
818     memset(&cmd, 0, sizeof(cmd));
819     init_etf_hdrs(&cmd.h, d_addr, 0, CONTROL_CHAN, -1);
820     cmd.op.opcode = OP_SET_TX_LO_OFFSET;
821     cmd.op.len = sizeof(cmd.op);
822     cmd.op.rid = d_next_rid++;
823
824     u2_fxpt_freq_t fxpt = u2_double_to_fxpt_freq(frequency);
825     cmd.op.freq_hi = htonl(u2_fxpt_freq_hi(fxpt));
826     cmd.op.freq_lo = htonl(u2_fxpt_freq_lo(fxpt));
827
828     cmd.eop.opcode = OP_EOP;
829     cmd.eop.len = sizeof(cmd.eop);
830     
831     pending_reply p(cmd.op.rid, &reply, sizeof(reply));
832     if (!transmit_cmd_and_wait(&cmd, sizeof(cmd), &p, DEF_CMD_TIMEOUT))
833       return false;
834
835     bool success = (ntohx(reply.ok) == 1);
836     return success;
837   }
838
839   bool
840   usrp2::impl::set_tx_center_freq(double frequency, tune_result *result)
841   {
842     op_config_tx_v2_cmd cmd;
843     op_config_tx_reply_v2_t reply;
844
845     init_config_tx_v2_cmd(&cmd);
846     cmd.op.valid = htons(CFGV_FREQ);
847     u2_fxpt_freq_t fxpt = u2_double_to_fxpt_freq(frequency);
848     cmd.op.freq_hi = htonl(u2_fxpt_freq_hi(fxpt));
849     cmd.op.freq_lo = htonl(u2_fxpt_freq_lo(fxpt));
850     
851     pending_reply p(cmd.op.rid, &reply, sizeof(reply));
852     if (!transmit_cmd_and_wait(&cmd, sizeof(cmd), &p, DEF_CMD_TIMEOUT))
853       return false;
854
855     bool success = (ntohx(reply.ok) == 1);
856     if (result && success) {
857       result->baseband_freq =
858         u2_fxpt_freq_to_double( 
859           u2_fxpt_freq_from_hilo(ntohl(reply.baseband_freq_hi), 
860                                  ntohl(reply.baseband_freq_lo)));
861
862       result->dxc_freq =
863         u2_fxpt_freq_to_double( 
864           u2_fxpt_freq_from_hilo(ntohl(reply.duc_freq_hi), 
865                                  ntohl(reply.duc_freq_lo)));
866
867       result->residual_freq =
868         u2_fxpt_freq_to_double( 
869          u2_fxpt_freq_from_hilo(ntohl(reply.residual_freq_hi), 
870                                 ntohl(reply.residual_freq_lo)));
871
872       result->spectrum_inverted = (bool)(ntohx(reply.inverted) == 1);
873     }
874
875     return success;
876   }
877   
878   bool
879   usrp2::impl::set_tx_interp(int interpolation_factor)
880   {
881     op_config_tx_v2_cmd cmd;
882     op_config_tx_reply_v2_t reply;
883
884     init_config_tx_v2_cmd(&cmd);
885     cmd.op.valid = htons(CFGV_INTERP_DECIM);
886     cmd.op.interp = htonl(interpolation_factor);
887     
888     pending_reply p(cmd.op.rid, &reply, sizeof(reply));
889     if (!transmit_cmd_and_wait(&cmd, sizeof(cmd), &p, DEF_CMD_TIMEOUT))
890       return false;
891
892     bool success = (ntohx(reply.ok) == 1);
893     if (success) {
894       d_tx_interp = interpolation_factor;
895
896       // Auto-set TX scaling based on interpolation rate
897       int scale_i, scale_q;
898       default_tx_scale_iq(d_tx_interp, &scale_i, &scale_q);
899       return set_tx_scale_iq(scale_i, scale_q);
900     }
901
902     return success;
903   }
904   
905   void
906   usrp2::impl::default_tx_scale_iq(int interpolation_factor, int *scale_i, int *scale_q)
907   {
908     // Calculate CIC interpolation (i.e., without halfband interpolators)
909     int i = interpolation_factor;
910     if (i > 128)
911       i = i >> 1;
912     if (i > 128)
913       i = i >> 1;
914
915     // Calculate dsp_core_tx gain absent scale multipliers
916     float gain = (1.65*i*i*i)/(4096*pow(2, ceil(log2(i*i*i))));
917     
918     // Calculate closest multiplier constant to reverse gain
919     int scale = (int)rint(1.0/gain);
920     // fprintf(stderr, "if=%i i=%i gain=%f scale=%i\n", interpolation_factor, i, gain, scale);
921
922     // Both I and Q are identical in this case
923     if (scale_i)
924       *scale_i = scale;
925     if (scale_q)
926       *scale_q = scale;
927   }
928
929   bool
930   usrp2::impl::set_tx_scale_iq(int scale_i, int scale_q)
931   {
932     op_config_tx_v2_cmd cmd;
933     op_config_tx_reply_v2_t reply;
934
935     init_config_tx_v2_cmd(&cmd);
936     cmd.op.valid = htons(CFGV_SCALE_IQ);
937     cmd.op.scale_iq = htonl(((scale_i & 0xffff) << 16) | (scale_q & 0xffff));
938     
939     pending_reply p(cmd.op.rid, &reply, sizeof(reply));
940     if (!transmit_cmd_and_wait(&cmd, sizeof(cmd), &p, DEF_CMD_TIMEOUT))
941       return false;
942
943     bool success = (ntohx(reply.ok) == 1);
944     return success;
945   }
946
947   bool
948   usrp2::impl::tx_32fc(unsigned int channel,
949                        const std::complex<float> *samples,
950                        size_t nsamples,
951                        const tx_metadata *metadata)
952   {
953     uint32_t items[nsamples];
954     copy_host_32fc_to_u2_16sc(nsamples, samples, items);
955     return tx_raw(channel, items, nsamples, metadata);
956   }
957
958   bool
959   usrp2::impl::tx_16sc(unsigned int channel,
960                        const std::complex<int16_t> *samples,
961                        size_t nsamples,
962                        const tx_metadata *metadata)
963   {
964 #ifdef WORDS_BIGENDIAN
965
966     // Already binary equivalent to 16-bit I/Q on the wire.
967     // No conversion required.
968
969     assert(sizeof(samples[0]) == sizeof(uint32_t));
970     return tx_raw(channel, (const uint32_t *) samples, nsamples, metadata);
971
972 #else
973
974     uint32_t items[nsamples];
975     copy_host_16sc_to_u2_16sc(nsamples, samples, items);
976     return tx_raw(channel, items, nsamples, metadata);
977
978 #endif
979   }
980
981   bool
982   usrp2::impl::tx_raw(unsigned int channel,
983                       const uint32_t *items,
984                       size_t nitems,
985                       const tx_metadata *metadata)
986   {
987     if (nitems == 0)
988       return true;
989
990     // FIXME can't deal with nitems < U2_MIN_SAMPLES (will be fixed in VRT)
991     // FIXME need to check the MTU instead of assuming 1500 bytes
992
993     // fragment as necessary then fire away
994
995     size_t nframes = (nitems + U2_MAX_SAMPLES - 1) / U2_MAX_SAMPLES;
996     size_t last_frame = nframes - 1;
997     u2_eth_packet_t     hdrs;
998
999     size_t n = 0;
1000     for (size_t fn = 0; fn < nframes; fn++){
1001       uint32_t timestamp = 0;
1002       uint32_t flags = 0;
1003
1004       if (fn == 0){
1005         timestamp = metadata->timestamp;
1006         if (metadata->send_now)
1007           flags |= U2P_TX_IMMEDIATE;
1008         if (metadata->start_of_burst)
1009           flags |= U2P_TX_START_OF_BURST;
1010       }
1011       if (fn > 0){
1012         flags |= U2P_TX_IMMEDIATE;
1013       }
1014       if (fn == last_frame){
1015         if (metadata->end_of_burst)
1016           flags |= U2P_TX_END_OF_BURST;
1017       }
1018
1019       init_etf_hdrs(&hdrs, d_addr, flags, channel, timestamp);
1020
1021       // Avoid short packet by splitting last two packets if reqd
1022       size_t i;
1023       if ((nitems - n) > U2_MAX_SAMPLES && (nitems - n) < (U2_MAX_SAMPLES + U2_MIN_SAMPLES))
1024         i = (nitems - n) / 2;
1025       else
1026         i = std::min((size_t) U2_MAX_SAMPLES, nitems - n);
1027
1028       eth_iovec iov[2];
1029       iov[0].iov_base = &hdrs;
1030       iov[0].iov_len = sizeof(hdrs);
1031       iov[1].iov_base = const_cast<uint32_t *>(&items[n]);
1032       iov[1].iov_len = i * sizeof(uint32_t);
1033
1034       size_t total = iov[0].iov_len + iov[1].iov_len;
1035       if (total < 64)
1036         fprintf(stderr, "usrp2::tx_raw: FIXME: short packet: %zd items (%zd bytes)\n", i, total);
1037
1038       if (d_eth_buf->tx_framev(iov, 2) != eth_buffer::EB_OK){
1039         return false;
1040       }
1041
1042       n += i;
1043     }
1044
1045     return true;
1046   }
1047
1048   // ----------------------------------------------------------------
1049   //                       misc commands
1050   // ----------------------------------------------------------------
1051
1052   bool
1053   usrp2::impl::config_mimo(int flags)
1054   {
1055     op_config_mimo_cmd cmd;
1056     op_generic_t reply;
1057
1058     memset(&cmd, 0, sizeof(cmd));
1059     init_etf_hdrs(&cmd.h, d_addr, 0, CONTROL_CHAN, -1);
1060     cmd.op.opcode = OP_CONFIG_MIMO;
1061     cmd.op.len = sizeof(cmd.op);
1062     cmd.op.rid = d_next_rid++;
1063     cmd.op.flags = flags;
1064     cmd.eop.opcode = OP_EOP;
1065     cmd.eop.len = sizeof(cmd.eop);
1066     
1067     pending_reply p(cmd.op.rid, &reply, sizeof(reply));
1068     if (!transmit_cmd_and_wait(&cmd, sizeof(cmd), &p, DEF_CMD_TIMEOUT))
1069       return false;
1070
1071     return ntohx(reply.ok) == 1;
1072   }
1073
1074   bool
1075   usrp2::impl::fpga_master_clock_freq(long *freq)
1076   {
1077     *freq = 100000000L;         // 100 MHz
1078     return true;
1079   }
1080
1081   bool
1082   usrp2::impl::adc_rate(long *rate)
1083   {
1084     return fpga_master_clock_freq(rate);
1085   }
1086
1087   bool
1088   usrp2::impl::dac_rate(long *rate)
1089   {
1090     return fpga_master_clock_freq(rate);
1091   }
1092
1093   bool
1094   usrp2::impl::tx_daughterboard_id(int *dbid)
1095   {
1096     *dbid = d_tx_db_info.dbid;
1097     return true;
1098   }
1099
1100   bool
1101   usrp2::impl::rx_daughterboard_id(int *dbid)
1102   {
1103     *dbid = d_rx_db_info.dbid;
1104     return true;
1105   }
1106
1107
1108   // ----------------------------------------------------------------
1109   //                    low-level commands
1110   // ----------------------------------------------------------------
1111
1112   bool
1113   usrp2::impl::burn_mac_addr(const std::string &new_addr)
1114   {
1115     op_burn_mac_addr_cmd cmd;
1116     op_generic_t reply;
1117
1118     memset(&cmd, 0, sizeof(cmd));
1119     init_etf_hdrs(&cmd.h, d_addr, 0, CONTROL_CHAN, -1);
1120     cmd.op.opcode = OP_BURN_MAC_ADDR;
1121     cmd.op.len = sizeof(cmd.op);
1122     cmd.op.rid = d_next_rid++;
1123     if (!parse_mac_addr(new_addr, &cmd.op.addr))
1124       return false;
1125
1126     pending_reply p(cmd.op.rid, &reply, sizeof(reply));
1127     if (!transmit_cmd_and_wait(&cmd, sizeof(cmd), &p, 4*DEF_CMD_TIMEOUT))
1128       return false;
1129
1130     bool success = (ntohx(reply.ok) == 1);
1131     return success;
1132   }
1133
1134   static void
1135   fill_dboard_info(db_info *dst, const u2_db_info_t *src)
1136   {
1137     dst->dbid = ntohl(src->dbid);
1138
1139     dst->freq_min =
1140       u2_fxpt_freq_to_double(u2_fxpt_freq_from_hilo(ntohl(src->freq_min_hi), 
1141                                                     ntohl(src->freq_min_lo)));
1142     dst->freq_max =
1143       u2_fxpt_freq_to_double(u2_fxpt_freq_from_hilo(ntohl(src->freq_max_hi), 
1144                                                     ntohl(src->freq_max_lo)));
1145
1146     dst->gain_min = u2_fxpt_gain_to_double(ntohs(src->gain_min));
1147     dst->gain_max = u2_fxpt_gain_to_double(ntohs(src->gain_max));
1148     dst->gain_step_size = u2_fxpt_gain_to_double(ntohs(src->gain_step_size));
1149   }
1150
1151   bool
1152   usrp2::impl::dboard_info()
1153   {
1154     op_dboard_info_cmd          cmd;
1155     op_dboard_info_reply_t      reply;
1156
1157     memset(&cmd, 0, sizeof(cmd));
1158     init_etf_hdrs(&cmd.h, d_addr, 0, CONTROL_CHAN, -1);
1159     cmd.op.opcode = OP_DBOARD_INFO;
1160     cmd.op.len = sizeof(cmd.op);
1161     cmd.op.rid = d_next_rid++;
1162     cmd.eop.opcode = OP_EOP;
1163     cmd.eop.len = sizeof(cmd.eop);
1164     
1165     pending_reply p(cmd.op.rid, &reply, sizeof(reply));
1166     if (!transmit_cmd_and_wait(&cmd, sizeof(cmd), &p, DEF_CMD_TIMEOUT))
1167       return false;
1168
1169     bool success = (ntohx(reply.ok) == 1);
1170     if (success){
1171       fill_dboard_info(&d_tx_db_info, &reply.tx_db_info);
1172       fill_dboard_info(&d_rx_db_info, &reply.rx_db_info);
1173     }
1174     return success;
1175   }
1176
1177
1178   bool
1179   usrp2::impl::sync_to_pps()
1180   {
1181     op_generic_cmd cmd;
1182     op_generic_t   reply;
1183
1184     memset(&cmd, 0, sizeof(cmd));
1185     init_etf_hdrs(&cmd.h, d_addr, 0, CONTROL_CHAN, -1);
1186     cmd.op.opcode = OP_SYNC_TO_PPS;
1187     cmd.op.len = sizeof(cmd.op);
1188     cmd.op.rid = d_next_rid++;
1189     cmd.eop.opcode = OP_EOP;
1190     cmd.eop.len = sizeof(cmd.eop);
1191     
1192     pending_reply p(cmd.op.rid, &reply, sizeof(reply));
1193     if (!transmit_cmd_and_wait(&cmd, sizeof(cmd), &p, DEF_CMD_TIMEOUT))
1194       return false;
1195
1196     return ntohx(reply.ok) == 1;
1197   }
1198
1199   bool
1200   usrp2::impl::sync_every_pps(bool enable)
1201   {
1202     op_generic_cmd cmd;
1203     op_generic_t   reply;
1204
1205     memset(&cmd, 0, sizeof(cmd));
1206     init_etf_hdrs(&cmd.h, d_addr, 0, CONTROL_CHAN, -1);
1207     cmd.op.opcode = OP_SYNC_EVERY_PPS;
1208     cmd.op.len = sizeof(cmd.op);
1209     cmd.op.rid = d_next_rid++;
1210     cmd.op.ok = enable ? 1 : 0;
1211     cmd.eop.opcode = OP_EOP;
1212     cmd.eop.len = sizeof(cmd.eop);
1213     
1214     pending_reply p(cmd.op.rid, &reply, sizeof(reply));
1215     if (!transmit_cmd_and_wait(&cmd, sizeof(cmd), &p, DEF_CMD_TIMEOUT))
1216       return false;
1217
1218     return ntohx(reply.ok) == 1;
1219   }
1220
1221   std::vector<uint32_t>
1222   usrp2::impl::peek32(uint32_t addr, uint32_t words)
1223   {
1224     std::vector<uint32_t> result; // zero sized on error return
1225     // fprintf(stderr, "usrp2::peek: addr=%08X words=%u\n", addr, words);
1226
1227     if (addr % 4 != 0) {
1228       fprintf(stderr, "usrp2::peek: addr (=%08X) must be 32-bit word aligned\n", addr); 
1229       return result;
1230     }
1231
1232     if (words == 0)
1233       return result;
1234
1235     op_peek_cmd   cmd;
1236     op_generic_t *reply;
1237
1238     int wlen = sizeof(uint32_t);
1239     int rlen = sizeof(op_generic_t);
1240     size_t bytes = words*wlen;
1241
1242     memset(&cmd, 0, sizeof(cmd));
1243     init_etf_hdrs(&cmd.h, d_addr, 0, CONTROL_CHAN, -1);
1244     cmd.op.opcode = OP_PEEK;
1245     cmd.op.len = sizeof(cmd.op);
1246     cmd.op.rid = d_next_rid++;
1247     cmd.eop.opcode = OP_EOP;
1248     cmd.eop.len = sizeof(cmd.eop);
1249
1250     cmd.op.addr = htonl(addr);
1251     cmd.op.bytes = htonl(bytes);
1252
1253     reply = (op_generic_t *)malloc(rlen+bytes);
1254     pending_reply p(cmd.op.rid, reply, rlen+bytes);
1255     if (transmit_cmd_and_wait(&cmd, sizeof(cmd), &p, DEF_CMD_TIMEOUT)) {
1256       uint32_t nwords = (reply->len-rlen)/sizeof(uint32_t);
1257       uint32_t *data = (uint32_t *)(reply+rlen/wlen);
1258       for (unsigned int i = 0; i < nwords; i++)
1259         result.push_back(ntohl(data[i]));
1260     }
1261
1262     free(reply);
1263     return result;
1264   }
1265
1266   bool
1267   usrp2::impl::poke32(uint32_t addr, const std::vector<uint32_t> &data)
1268   {
1269     if (addr % 4 != 0) {
1270       fprintf(stderr, "usrp2::poke32: addr (=%08X) must be 32-bit word aligned\n", addr); 
1271       return false;
1272     }
1273
1274     int plen = sizeof(op_poke_cmd);
1275     int wlen = sizeof(uint32_t);
1276     int max_words = (MAX_SUBPKT_LEN-plen)/wlen;
1277     int words = data.size();
1278
1279     if (words > max_words) {
1280       fprintf(stderr, "usrp2::poke32: write size (=%u) exceeds maximum of %u words\n",
1281               words, max_words);
1282       return false;
1283     }
1284
1285     //fprintf(stderr, "usrp2::poke32: addr=%08X words=%u\n", addr, words);
1286
1287     if (words == 0)
1288       return true; // NOP
1289
1290     op_poke_cmd  *cmd;
1291     op_generic_t *eop;
1292
1293     // Allocate, clear, and initialize command packet
1294     int bytes = words*wlen;
1295     int l = plen+bytes+sizeof(*eop); // op_poke_cmd+data+eop
1296     cmd = (op_poke_cmd *)malloc(l);
1297     //fprintf(stderr, "cmd=%p l=%i\n", cmd, l);
1298     memset(cmd, 0, l);
1299     init_etf_hdrs(&cmd->h, d_addr, 0, CONTROL_CHAN, -1);
1300     cmd->op.opcode = OP_POKE;
1301     cmd->op.len = sizeof(cmd->op)+bytes;
1302     cmd->op.rid = d_next_rid++;
1303     cmd->op.addr = htonl(addr);
1304
1305     // Copy data from vector into packet space
1306     uint32_t *dest = (uint32_t *)((uint8_t *)cmd+plen);
1307     for (int i = 0; i < words; i++) {
1308       //fprintf(stderr, "%03i@%p\n", i, dest);
1309       *dest++ = htonl(data[i]);
1310     }
1311
1312     // Write end-of-packet subpacket
1313     eop = (op_generic_t *)dest;
1314     eop->opcode = OP_EOP;
1315     eop->len = sizeof(*eop);
1316     //fprintf(stderr, "eop=%p len=%i\n", eop, eop->len);
1317
1318     // Send command to device and retrieve reply
1319     bool ok = false;
1320     op_generic_t reply;
1321     pending_reply p(cmd->op.rid, &reply, sizeof(reply));
1322     if (transmit_cmd_and_wait(cmd, l, &p, DEF_CMD_TIMEOUT))
1323       ok = (ntohx(reply.ok) == 1);
1324
1325     free(cmd);
1326     return ok;
1327   }
1328
1329   bool
1330   usrp2::impl::reset_db()
1331   {
1332     op_generic_cmd cmd;
1333     op_generic_t reply;
1334
1335     memset(&cmd, 0, sizeof(cmd));
1336     init_etf_hdrs(&cmd.h, d_addr, 0, CONTROL_CHAN, -1);
1337     cmd.op.opcode = OP_RESET_DB;
1338     cmd.op.len = sizeof(cmd.op);
1339     cmd.op.rid = d_next_rid++;
1340     cmd.eop.opcode = OP_EOP;
1341     cmd.eop.len = sizeof(cmd.eop);
1342     
1343     pending_reply p(cmd.op.rid, &reply, sizeof(reply));
1344     if (!transmit_cmd_and_wait(&cmd, sizeof(cmd), &p, DEF_CMD_TIMEOUT))
1345       return false;
1346
1347     bool success = (ntohx(reply.ok) == 1);
1348     return success;
1349   }
1350
1351   bool usrp2::impl::set_gpio_ddr(int bank, uint16_t value, uint16_t mask)
1352   {
1353     if (bank != GPIO_TX_BANK && bank != GPIO_RX_BANK) {
1354       fprintf(stderr, "set_gpio_ddr: bank must be one of GPIO_RX_BANK or GPIO_TX_BANK\n");
1355       return false;
1356     }
1357
1358     op_gpio_cmd cmd;
1359     op_generic_t reply;
1360
1361     memset(&cmd, 0, sizeof(cmd));
1362     init_etf_hdrs(&cmd.h, d_addr, 0, CONTROL_CHAN, -1);
1363     cmd.op.opcode = OP_GPIO_SET_DDR;
1364     cmd.op.len = sizeof(cmd.op);
1365     cmd.op.rid = d_next_rid++;
1366     cmd.op.bank = static_cast<uint8_t>(bank);
1367     cmd.op.value = htons(value);
1368     cmd.op.mask = htons(mask);
1369     cmd.eop.opcode = OP_EOP;
1370     cmd.eop.len = sizeof(cmd.eop);
1371     
1372     pending_reply p(cmd.op.rid, &reply, sizeof(reply));
1373     if (!transmit_cmd_and_wait(&cmd, sizeof(cmd), &p, DEF_CMD_TIMEOUT))
1374       return false;
1375
1376     bool success = (ntohx(reply.ok) == 1);
1377     return success;
1378   }
1379
1380   bool usrp2::impl::set_gpio_sels(int bank, std::string sels)
1381   {
1382     if (bank != GPIO_TX_BANK && bank != GPIO_RX_BANK) {
1383       fprintf(stderr, "set_gpio_ddr: bank must be one of GPIO_RX_BANK or GPIO_TX_BANK\n");
1384       return false;
1385     }
1386
1387     if (sels.size() != 16) {
1388       fprintf(stderr, "set_gpio_sels: sels must be exactly 16 bytes\n");
1389       return false;
1390     }
1391
1392     op_gpio_set_sels_cmd cmd;
1393     op_generic_t reply;
1394
1395     memset(&cmd, 0, sizeof(cmd));
1396     init_etf_hdrs(&cmd.h, d_addr, 0, CONTROL_CHAN, -1);
1397     cmd.op.opcode = OP_GPIO_SET_SELS;
1398     cmd.op.len = sizeof(cmd.op);
1399     cmd.op.rid = d_next_rid++;
1400     cmd.op.bank = static_cast<uint8_t>(bank);
1401     memcpy(&cmd.op.sels, sels.c_str(), 16);
1402     cmd.eop.opcode = OP_EOP;
1403     cmd.eop.len = sizeof(cmd.eop);
1404     
1405     pending_reply p(cmd.op.rid, &reply, sizeof(reply));
1406     if (!transmit_cmd_and_wait(&cmd, sizeof(cmd), &p, DEF_CMD_TIMEOUT))
1407       return false;
1408
1409     bool success = (ntohx(reply.ok) == 1);
1410     return success;
1411   }
1412
1413   bool usrp2::impl::write_gpio(int bank, uint16_t value, uint16_t mask)
1414   {
1415     if (bank != GPIO_TX_BANK && bank != GPIO_RX_BANK) {
1416       fprintf(stderr, "set_gpio_ddr: bank must be one of GPIO_RX_BANK or GPIO_TX_BANK\n");
1417       return false;
1418     }
1419
1420     op_gpio_cmd cmd;
1421     op_generic_t reply;
1422
1423     memset(&cmd, 0, sizeof(cmd));
1424     init_etf_hdrs(&cmd.h, d_addr, 0, CONTROL_CHAN, -1);
1425     cmd.op.opcode = OP_GPIO_WRITE;
1426     cmd.op.len = sizeof(cmd.op);
1427     cmd.op.rid = d_next_rid++;
1428     cmd.op.bank = static_cast<uint8_t>(bank);
1429     cmd.op.value = htons(value);
1430     cmd.op.mask = htons(mask);
1431     cmd.eop.opcode = OP_EOP;
1432     cmd.eop.len = sizeof(cmd.eop);
1433     
1434     pending_reply p(cmd.op.rid, &reply, sizeof(reply));
1435     if (!transmit_cmd_and_wait(&cmd, sizeof(cmd), &p, DEF_CMD_TIMEOUT))
1436       return false;
1437
1438     bool success = (ntohx(reply.ok) == 1);
1439     return success;
1440   }
1441
1442   bool usrp2::impl::read_gpio(int bank, uint16_t *value)
1443   {
1444     if (bank != GPIO_TX_BANK && bank != GPIO_RX_BANK) {
1445       fprintf(stderr, "set_gpio_ddr: bank must be one of GPIO_RX_BANK or GPIO_TX_BANK\n");
1446       return false;
1447     }
1448
1449     op_gpio_cmd cmd;
1450     op_gpio_read_reply_t reply;
1451
1452     memset(&cmd, 0, sizeof(cmd));
1453     init_etf_hdrs(&cmd.h, d_addr, 0, CONTROL_CHAN, -1);
1454     cmd.op.opcode = OP_GPIO_READ;
1455     cmd.op.len = sizeof(cmd.op);
1456     cmd.op.rid = d_next_rid++;
1457     cmd.op.bank = static_cast<uint8_t>(bank);
1458     cmd.op.value = 0; // not used
1459     cmd.op.mask = 0;  // not used
1460     cmd.eop.opcode = OP_EOP;
1461     cmd.eop.len = sizeof(cmd.eop);
1462     
1463     pending_reply p(cmd.op.rid, &reply, sizeof(reply));
1464     if (!transmit_cmd_and_wait(&cmd, sizeof(cmd), &p, DEF_CMD_TIMEOUT))
1465       return false;
1466
1467     bool success = (ntohx(reply.ok) == 1);
1468     if (success && (value != NULL))
1469       *value = ntohs(reply.value);
1470
1471     return success;
1472   }
1473
1474   bool usrp2::impl::enable_gpio_streaming(int bank, int enable)
1475   {
1476     if (bank != GPIO_RX_BANK) {
1477       fprintf(stderr, "enable_gpio_streaming: only RX streaming is currently implemented\n");
1478       return false;
1479     }
1480
1481     if ((enable & ~0x03) != 0) {
1482       fprintf(stderr, "enable_gpio_streaming: invalid enable format\n");
1483       return false;
1484     }
1485
1486     op_gpio_cmd cmd;
1487     op_generic_t reply;
1488
1489     memset(&cmd, 0, sizeof(cmd));
1490     init_etf_hdrs(&cmd.h, d_addr, 0, CONTROL_CHAN, -1);
1491     cmd.op.opcode = OP_GPIO_STREAM;
1492     cmd.op.len = sizeof(cmd.op);
1493     cmd.op.rid = d_next_rid++;
1494     cmd.op.bank = static_cast<uint8_t>(bank);
1495     cmd.op.value = htons((uint16_t)enable);
1496     cmd.op.mask = 0;  // not used
1497     cmd.eop.opcode = OP_EOP;
1498     cmd.eop.len = sizeof(cmd.eop);
1499     
1500     pending_reply p(cmd.op.rid, &reply, sizeof(reply));
1501     if (!transmit_cmd_and_wait(&cmd, sizeof(cmd), &p, DEF_CMD_TIMEOUT))
1502       return false;
1503
1504     bool success = (ntohx(reply.ok) == 1);
1505     return success;
1506   }
1507
1508 } // namespace usrp2