-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMain.cc
2364 lines (2079 loc) · 78.6 KB
/
Main.cc
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
#define _BSD_SOURCE 1
#include <cstdio>
#include <fcntl.h>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <cinttypes>
#include <cassert>
#include <deque>
#include <atomic>
#include <time.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <infiniband/verbs.h>
#include <netdb.h>
#include <sys/socket.h>
#include <thread>
#include <mutex>
#include <iostream>
#include <map>
#include <algorithm>
#include <unordered_map>
#include "docopt.h"
#include "Tub.h"
#include "IpAddress.h"
#include "LargeBlockOfMemory.h"
#include "CycleCounter.h"
#include "SpinLock.h"
#include <fstream>
#include <iterator>
#define ZIPFIAN_SETUP 1
static const int PORT = 12240;
static const uint32_t MAX_INLINE_DATA = 0;
static const uint32_t MAX_SHARED_RX_QUEUE_DEPTH = 32;
// Since we always use at most 1 SGE per receive request, there is no need
// to set this parameter any higher. In fact, larger values for this
// parameter result in increased descriptor size, which means that the
// Infiniband controller needs to fetch more data from host memory,
// which results in a higher number of on-controller cache misses.
static const uint32_t MAX_SHARED_RX_SGE_COUNT = 1;
static const uint32_t MAX_TX_QUEUE_DEPTH = 128;
static const uint32_t MAX_TX_QUEUE_DEPTH_PER_THREAD = 4;
// Storing a vector of 10 million Zipfian skewed start addresses so as to
// not take a perf hit while generating them in critical path
// Change the theta value here to adjust skew
static const double THETA = 0.50;
static const uint32_t MAX_ZIPFIAN_ADDRESSES = 10000000;
void write_vector_to_file(std::vector<uint32_t> *v, const char *path) {
std::ofstream output_file(path);
std::ostream_iterator<uint32_t> output_iterator(output_file, "\n");
std::copy(v->begin(), v->end(), output_iterator);
}
// With 64 KB seglets 1 MB is fractured into 16 or 17 pieces, plus we
// need an entry for the headers.
// 31 seems to be the limit on this. Not sure why, because the qp's are
// initialized with a max sge limit of 1 anyway.
const uint32_t MAX_TX_SGE_COUNT = 32;
const uint32_t MIN_CHUNK_ZERO_COPY_LEN = 0;
static const uint32_t QP_EXCHANGE_MAX_TIMEOUTS = 10;
#define HTONS(x) \
static_cast<uint16_t>((((x) >> 8) & 0xff) | (((x) & 0xff) << 8))
#define NTOHS HTONS
#define check_error_null(x, s) \
do { \
if ((x) == NULL) { \
LOG(ERROR, "%s", s); \
exit(-1); \
} \
} while (0)
ibv_srq* serverSrq; // shared receive work queue for server
ibv_srq* clientSrq; // shared receive work queue for client
ibv_cq* serverRxCq; // completion queue for incoming requests
ibv_cq* clientRxCq; // completion queue for client wait
ibv_cq* commonTxCq; // common completion queue for all transmits
int ibPhysicalPort = 1;
int lid; // local id for this HCA and physical port
int serverSetupSocket; // UDP socket for incoming setup requests;
// -1 means we're not a server
int clientSetupSocket; // UDP socket for outgoing setup requests
int clientPort; // Port number associated with
static const size_t logSize = 4lu * 1024 * 1024 * 1024;
struct ThreadMetrics {
ThreadMetrics()
: postSendCycles{}
, getTransmitCycles{}
, memCpyCycles{}
, addingGECycles{}
, setupWRCycles{}
, miscCycles{}
, chunksTransmitted{}
, chunksTransmittedZeroCopy{}
, transmissions{}
, transmittedBytes{}
{}
void reset() { new (this) ThreadMetrics{}; }
static void dumpHeader() {
printf("copied server chunksPerMessage chunkSize "
"deltasPerMessage deltaSize "
"seconds warmupSeconds "
"totalSecs totalNSecs "
"sendNSecs getTxNSecs memcpyNSecs addingGENSecs setupWRNSecs "
"miscCycles "
"chunksTx chunksTxZeroCopy transmissions transmittedBytes mbs\n");
}
void dump(bool copied,
const char* server,
uint64_t cycles,
int chunksPerMessage,
size_t chunkSize,
int deltasPerMessage,
size_t deltaSize,
double seconds,
double warmupSeconds)
{
const double mbs =
chunkSize * chunksTransmitted / seconds / (1024 * 1024);
printf("%d %s %d %lu %d %lu %f %f %f %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %f\n",
copied,
server,
chunksPerMessage,
chunkSize,
deltasPerMessage,
deltaSize,
seconds,
warmupSeconds,
Cycles::toSeconds(cycles),
Cycles::toNanoseconds(cycles),
Cycles::toNanoseconds(postSendCycles),
Cycles::toNanoseconds(getTransmitCycles),
Cycles::toNanoseconds(memCpyCycles),
Cycles::toNanoseconds(addingGECycles),
Cycles::toNanoseconds(setupWRCycles),
Cycles::toNanoseconds(miscCycles),
chunksTransmitted,
chunksTransmittedZeroCopy,
transmissions,
transmittedBytes,
mbs);
fflush(stdout);
}
uint64_t postSendCycles; // Cycles for post send calls per client;
uint64_t getTransmitCycles; // Cycles for getting transmit buffers per client;
uint64_t memCpyCycles; // Cycles for mem copying objects in copied=1 mode;
uint64_t addingGECycles; // Cycles adding gather list entries for zero-copy;
uint64_t setupWRCycles; // Cycles to create the WR sent to post_send;
uint64_t miscCycles; // Cycle counter for perf debugging.
uint64_t chunksTransmitted;
uint64_t chunksTransmittedZeroCopy;
uint64_t transmissions;
uint64_t transmittedBytes;
};
thread_local ThreadMetrics threadMetrics{};
ibv_context* ctxt; // device context of the HCA to use
ibv_pd* pd;
struct BufferDescriptor {
char * buffer; // buf of ``bytes'' length
uint32_t bytes; // length of buffer in bytes
uint32_t messageBytes; // byte length of message in the buffer
ibv_mr * mr; // memory region of the buffer
size_t threadNum; // The thread using this buffer (client)
BufferDescriptor(char *buffer, uint32_t bytes, ibv_mr *mr, size_t threadNum)
: buffer(buffer), bytes(bytes), messageBytes(0), mr(mr),
threadNum(threadNum) {}
BufferDescriptor()
: buffer(NULL), bytes(0), messageBytes(0), mr(NULL), threadNum(0) {}
};
void* rxBase;
BufferDescriptor rxDescriptors[MAX_SHARED_RX_QUEUE_DEPTH * 2];
void* txBase;
BufferDescriptor txDescriptors[MAX_TX_QUEUE_DEPTH];
std::vector<std::vector<BufferDescriptor*>> freeTxBuffers{};
std::vector<RAMCloud::UnnamedSpinLock> freeTxBufferMutex;
std::vector<std::vector<uint32_t>> zipfianChunkAddresses;
std::vector<std::vector<uint32_t>> zipfianDeltaAddresses;
uintptr_t logMemoryBase = 0;
size_t logMemoryBytes = 0;
ibv_mr* logMemoryRegion;
uint64_t remoteLogVA = 0;
uint32_t remoteLogRkey = 0;
/**
* Pin all current and future memory pages in memory so that the OS does not
* swap them to disk. All RAMCloud server main files should call this.
*
* Note that future mapping operations (e.g. mmap, stack expansion, etc)
* may fail if their memory cannot be pinned due to resource limits. Thus the
* check below may not capture all possible failures up front. It's probably
* best to call this at the end of initialisation (after most large allocations
* have been made). This is also a good idea because pinning slows down mmap
* probing in #LargeBlockOfMemory.
*/
void pinAllMemory() {
int r = mlockall(MCL_CURRENT | MCL_FUTURE);
if (r != 0) {
LOG(WARNING, "Could not lock all memory pages (%s), so the OS might "
"swap memory later. Check your user's \"ulimit -l\" and "
"adjust /etc/security/limits.conf as necessary.",
strerror(errno));
}
}
// Lobotomized and injected with custom PRNG from RAMCloud/src/ClusterPerf.cc
class ZipfianGenerator {
public:
/**
* Construct a generator. This may be expensive if n is large.
*
* \param n
* The generator will output random numbers between 0 and n-1.
* \param theta
* The zipfian parameter where 0 < theta < 1 defines the skew; the
* smaller the value the more skewed the distribution will be. Default
* value of 0.99 comes from the YCSB default value.
*/
explicit ZipfianGenerator(uint32_t n, double theta = 0.99, size_t seed = 1)
: n(n)
, theta(theta)
, alpha(1 / (1 - theta))
, zetan(zeta(n, theta))
, eta((1 - pow(2.0 / static_cast<double>(n), 1 - theta)) /
(1 - zeta(2, theta) / zetan))
, seed(seed)
, prng{seed}
{}
/**
* Return the zipfian distributed random number between 0 and n-1.
*/
uint32_t nextNumber()
{
uint32_t random;
random = prng.generate();
double u = static_cast<double>(random) /
static_cast<double>(~0U);
double uz = u * zetan;
if (uz < 1)
return 0;
if (uz < 1 + std::pow(0.5, theta))
return 1;
return 0 + static_cast<uint32_t>(static_cast<double>(n) *
std::pow(eta*u - eta + 1.0, alpha));
}
private:
const uint32_t n; // Range of numbers to be generated.
const double theta; // Parameter of the zipfian distribution.
const double alpha; // Special intermediate result used for generation.
const double zetan; // Special intermediate result used for generation.
const double eta; // Special intermediate result used for generation.
const size_t seed; // Seed for random number generator
PRNG prng;
/**
* Returns the nth harmonic number with parameter theta; e.g. H_{n,theta}.
*/
static double zeta(uint32_t n, double theta)
{
double sum = 0;
for (uint32_t i = 0; i < n; i++) {
sum = sum + 1.0/(std::pow(i+1, theta));
}
return sum;
}
};
// XXX Lobotomized for now.
class Address {
int physicalPort; // physical port number on local device
uint16_t lid; // local id (address)
uint32_t qpn; // queue pair number
mutable ibv_ah* ah; // address handle, may be NULL
};
class QueuePairTuple {
public:
QueuePairTuple() : logVA{}, rkey{}, qpn(0), psn(0), lid(0), nonce(0)
{
static_assert(sizeof(QueuePairTuple) == 80,
"QueuePairTuple has unexpected size");
}
QueuePairTuple(uint64_t logVA, uint32_t rkey,
uint16_t lid, uint32_t qpn, uint32_t psn,
uint64_t nonce, const char* peerName = "?unknown?")
: logVA{logVA}, rkey{rkey},
qpn(qpn), psn(psn), lid(lid), nonce(nonce)
{
snprintf(this->peerName, sizeof(this->peerName), "%s",
peerName);
}
uint64_t getLogVA() const { return logVA; }
uint32_t getRkey() const { return rkey; }
uint16_t getLid() const { return lid; }
uint32_t getQpn() const { return qpn; }
uint32_t getPsn() const { return psn; }
uint64_t getNonce() const { return nonce; }
const char* getPeerName() const { return peerName; }
private:
uint64_t logVA; // Virtual address of start of remote log.
uint32_t rkey; // rkey of remote log for RDMA.
uint32_t qpn; // queue pair number
uint32_t psn; // initial packet sequence number
uint16_t lid; // infiniband address: "local id"
uint64_t nonce; // random nonce used to confirm replies are
// for received requests
char peerName[50]; // Optional name for the sender (intended for
// use in error messages); null-terminated.
} __attribute__((packed));
class QueuePair {
public:
QueuePair(ibv_qp_type type,
ibv_srq *srq,
ibv_cq *txcq,
ibv_cq *rxcq,
uint32_t maxSendWr,
uint32_t maxRecvWr,
uint32_t QKey = 0);
// exists solely as superclass constructor for MockQueuePair derivative
explicit QueuePair()
: type(0),
srq(NULL), qp(NULL), txcq(NULL), rxcq(NULL),
initialPsn(-1), handshakeSin() {}
~QueuePair();
uint32_t getInitialPsn() const;
uint32_t getLocalQpNumber() const;
uint32_t getRemoteQpNumber() const;
uint16_t getRemoteLid() const;
int getState() const;
bool isError() const;
void plumb(QueuePairTuple *qpt);
void setPeerName(const char *peerName);
const char* getPeerName() const;
void activate();
//private:
int type; // QP type (IBV_QPT_RC, etc.)
ibv_srq* srq; // shared receive queue
ibv_qp* qp; // infiniband verbs QP handle
ibv_cq* txcq; // transmit completion queue
ibv_cq* rxcq; // receive completion queue
uint32_t initialPsn; // initial packet sequence number
sockaddr_in handshakeSin; // UDP address of the remote end used to
// handshake when using RC queue pairs.
char peerName[50]; // Optional name for the sender
// (intended for use in error messages);
// null-terminated.
};
/**
* Construct a QueuePair. This object hides some of the ugly
* initialisation of Infiniband "queue pairs", which are single-side
* transmit and receive queues. This object can represent both reliable
* connected (RC) and unreliable datagram (UD) queue pairs. Not all
* methods are valid to all queue pair types.
*
* Somewhat confusingly, each communicating end has a QueuePair, which are
* bound (one might say "paired", but that's even more confusing). This
* object is somewhat analogous to a TCB in TCP.
*
* After this method completes, the QueuePair will be in the INIT state.
* A later call to #plumb() will transition it into the RTS state for
* regular use with RC queue pairs.
*
* \param infiniband
* The #Infiniband object to associate this QueuePair with.
* \param type
* The type of QueuePair to create. Currently valid values are
* IBV_QPT_RC for reliable QueuePairs and IBV_QPT_UD for
* unreliable ones.
* \param ibPhysicalPort
* The physical port on the HCA we will use this QueuePair on.
* The default is 1, though some devices have multiple ports.
* \param srq
* The Verbs shared receive queue to associate this QueuePair
* with. All writes received will use WQEs placed on the
* shared queue. If NULL, do not use a shared receive queue.
* \param txcq
* The Verbs completion queue to be used for transmissions on
* this QueuePair.
* \param rxcq
* The Verbs completion queue to be used for receives on this
* QueuePair.
* \param maxSendWr
* Maximum number of outstanding send work requests allowed on
* this QueuePair.
* \param maxRecvWr
* Maximum number of outstanding receive work requests allowed on
* this QueuePair.
* \param QKey
* UD Queue Pairs only. The QKey for this pair.
*/
QueuePair::QueuePair(ibv_qp_type type,
ibv_srq *srq, ibv_cq *txcq, ibv_cq *rxcq,
uint32_t maxSendWr, uint32_t maxRecvWr, uint32_t QKey)
: type(type),
srq(srq),
qp(NULL),
txcq(txcq),
rxcq(rxcq),
initialPsn(rand() & 0xffffff),
handshakeSin()
{
snprintf(peerName, sizeof(peerName), "?unknown?");
if (type != IBV_QPT_RC && type != IBV_QPT_UD && type != IBV_QPT_RAW_ETH)
DIE("invalid queue pair type");
ibv_qp_init_attr qpia;
memset(&qpia, 0, sizeof(qpia));
qpia.send_cq = txcq;
qpia.recv_cq = rxcq;
qpia.srq = srq; // use the same shared receive queue
qpia.cap.max_send_wr = maxSendWr; // max outstanding send requests
qpia.cap.max_recv_wr = maxRecvWr; // max outstanding recv requests
qpia.cap.max_send_sge = 32; // max send scatter-gather elements
qpia.cap.max_recv_sge = 1; // max recv scatter-gather elements
qpia.cap.max_inline_data = // max bytes of immediate data on send q
MAX_INLINE_DATA;
qpia.qp_type = type; // RC, UC, UD, or XRC
qpia.sq_sig_all = 0; // only generate CQEs on requested WQEs
qp = ibv_create_qp(pd, &qpia);
if (qp == NULL) {
DIE("failed to create queue pair");
}
// move from RESET to INIT state
ibv_qp_attr qpa;
memset(&qpa, 0, sizeof(qpa));
qpa.qp_state = IBV_QPS_INIT;
qpa.pkey_index = 0;
qpa.port_num = uint8_t(ibPhysicalPort);
qpa.qp_access_flags = IBV_ACCESS_REMOTE_WRITE |
IBV_ACCESS_REMOTE_READ |
IBV_ACCESS_LOCAL_WRITE;
qpa.qkey = QKey;
int mask = IBV_QP_STATE | IBV_QP_PORT;
switch (type) {
case IBV_QPT_RC:
mask |= IBV_QP_ACCESS_FLAGS;
mask |= IBV_QP_PKEY_INDEX;
break;
case IBV_QPT_UD:
mask |= IBV_QP_QKEY;
mask |= IBV_QP_PKEY_INDEX;
break;
case IBV_QPT_RAW_ETH:
break;
default:
assert(0);
}
int ret = ibv_modify_qp(qp, &qpa, mask);
if (ret) {
ibv_destroy_qp(qp);
DIE("failed to transition to INIT state errno %d", errno);
}
}
/**
* Destroy the QueuePair by freeing the Verbs resources allocated.
*/
QueuePair::~QueuePair()
{
ibv_destroy_qp(qp);
}
/**
* Bring an newly created RC QueuePair into the RTS state, enabling
* regular bidirectional communication. This is necessary before
* the QueuePair may be used. Note that this only applies to
* RC QueuePairs.
*
* \param qpt
* QueuePairTuple representing the remote QueuePair. The Verbs
* interface requires us to exchange handshaking information
* manually. This includes initial sequence numbers, queue pair
* numbers, and the HCA infiniband addresses.
*
* \throw TransportException
* An exception is thrown if this method is called on a QueuePair
* that is not of type IBV_QPT_RC, or if the QueuePair is not
* in the INIT state.
*/
void
QueuePair::plumb(QueuePairTuple *qpt)
{
ibv_qp_attr qpa;
int r;
if (type != IBV_QPT_RC)
DIE("plumb() called on wrong qp type");
if (getState() != IBV_QPS_INIT) {
DIE("plumb() on qp in state %d", getState());
}
// now connect up the qps and switch to RTR
memset(&qpa, 0, sizeof(qpa));
qpa.qp_state = IBV_QPS_RTR;
qpa.path_mtu = IBV_MTU_1024;
qpa.dest_qp_num = qpt->getQpn();
qpa.rq_psn = qpt->getPsn();
qpa.max_dest_rd_atomic = 1;
qpa.min_rnr_timer = 12;
qpa.ah_attr.is_global = 0;
qpa.ah_attr.dlid = qpt->getLid();
qpa.ah_attr.sl = 0;
qpa.ah_attr.src_path_bits = 0;
qpa.ah_attr.port_num = uint8_t(ibPhysicalPort);
r = ibv_modify_qp(qp, &qpa, IBV_QP_STATE |
IBV_QP_AV |
IBV_QP_PATH_MTU |
IBV_QP_DEST_QPN |
IBV_QP_RQ_PSN |
IBV_QP_MIN_RNR_TIMER |
IBV_QP_MAX_DEST_RD_ATOMIC);
if (r) {
DIE("failed to transition to RTR state");
}
// now move to RTS
qpa.qp_state = IBV_QPS_RTS;
// How long to wait before retrying if packet lost or server dead.
// Supposedly the timeout is 4.096us*2^timeout. However, the actual
// timeout appears to be 4.096us*2^(timeout+1), so the setting
// below creates a 135ms timeout.
qpa.timeout = 14;
// How many times to retry after timeouts before giving up.
qpa.retry_cnt = 7;
// How many times to retry after RNR (receiver not ready) condition
// before giving up. Occurs when the remote side has not yet posted
// a receive request.
qpa.rnr_retry = 7; // 7 is infinite retry.
qpa.sq_psn = initialPsn;
qpa.max_rd_atomic = 1;
r = ibv_modify_qp(qp, &qpa, IBV_QP_STATE |
IBV_QP_TIMEOUT |
IBV_QP_RETRY_CNT |
IBV_QP_RNR_RETRY |
IBV_QP_SQ_PSN |
IBV_QP_MAX_QP_RD_ATOMIC);
if (r) {
DIE("failed to transition to RTS state");
}
// the queue pair should be ready to use once the client has finished
// setting up their end.
}
void
QueuePair::activate()
{
ibv_qp_attr qpa;
if (type != IBV_QPT_UD && type != IBV_QPT_RAW_ETH)
DIE("activate() called on wrong qp type");
if (getState() != IBV_QPS_INIT) {
DIE("activate() on qp in state %d", getState());
}
// now switch to RTR
memset(&qpa, 0, sizeof(qpa));
qpa.qp_state = IBV_QPS_RTR;
int ret = ibv_modify_qp(qp, &qpa, IBV_QP_STATE);
if (ret) {
DIE("failed to transition to RTR state");
}
// now move to RTS state
qpa.qp_state = IBV_QPS_RTS;
int flags = IBV_QP_STATE;
if (type != IBV_QPT_RAW_ETH) {
qpa.sq_psn = initialPsn;
flags |= IBV_QP_SQ_PSN;
}
ret = ibv_modify_qp(qp, &qpa, flags);
if (ret) {
DIE("failed to transition to RTS state");
}
}
/**
* Get the initial packet sequence number for this QueuePair.
* This is randomly generated on creation. It should not be confused
* with the remote side's PSN, which is set in #plumb().
*/
uint32_t
QueuePair::getInitialPsn() const
{
return initialPsn;
}
/**
* Get the local queue pair number for this QueuePair.
* QPNs are analogous to UDP/TCP port numbers.
*/
uint32_t
QueuePair::getLocalQpNumber() const
{
return qp->qp_num;
}
/**
* Get the remote queue pair number for this QueuePair, as set in #plumb().
* QPNs are analogous to UDP/TCP port numbers.
*
* \throw
* TransportException is thrown if querying the queue pair
* fails.
*/
uint32_t
QueuePair::getRemoteQpNumber() const
{
ibv_qp_attr qpa;
ibv_qp_init_attr qpia;
int r = ibv_query_qp(qp, &qpa, IBV_QP_DEST_QPN, &qpia);
if (r) {
// We should probably log something here.
DIE("Bad things! %d", r);
}
return qpa.dest_qp_num;
}
/**
* Get the remote infiniband address for this QueuePair, as set in #plumb().
* LIDs are "local IDs" in infiniband terminology. They are short, locally
* routable addresses.
*
* \throw
* TransportException is thrown if querying the queue pair
* fails.
*/
uint16_t
QueuePair::getRemoteLid() const
{
ibv_qp_attr qpa;
ibv_qp_init_attr qpia;
int r = ibv_query_qp(qp, &qpa, IBV_QP_AV, &qpia);
if (r) {
// We should probably log something here.
DIE("Bad things! %d", r);
}
return qpa.ah_attr.dlid;
}
/**
* Get the state of a QueuePair.
*
* \throw
* TransportException is thrown if querying the queue pair
* fails.
*/
int
QueuePair::getState() const
{
ibv_qp_attr qpa;
ibv_qp_init_attr qpia;
int r = ibv_query_qp(qp, &qpa, IBV_QP_STATE, &qpia);
if (r) {
// We should probably log something here.
DIE("Bad things! %d", r);
}
return qpa.qp_state;
}
/**
* Return true if the queue pair is in an error state, false otherwise.
*
* \throw
* TransportException is thrown if querying the queue pair
* fails.
*/
bool
QueuePair::isError() const
{
ibv_qp_attr qpa;
ibv_qp_init_attr qpia;
int r = ibv_query_qp(qp, &qpa, -1, &qpia);
if (r) {
// We should probably log something here.
DIE("Bad things! %d", r);
}
return qpa.cur_qp_state == IBV_QPS_ERR;
}
/**
* Provide information that can be used in log messages to identify the
* other end of this connection.
*
* \param name
* Human-readable name for the application or machine at the other
* end of this connection.
*/
void
QueuePair::setPeerName(const char* name)
{
snprintf(peerName, sizeof(peerName), "%s", name);
}
const char*
QueuePair::getPeerName() const
{
return peerName;
}
class DeviceList {
public:
DeviceList()
: devices(ibv_get_device_list(NULL))
{
if (devices == NULL) {
DIE("Could not open infiniband device list: %d", errno);
}
}
~DeviceList() {
ibv_free_device_list(devices);
}
ibv_device*
lookup(const char* name) {
if (name == NULL)
return devices[0];
for (int i = 0; devices[i] != NULL; i++) {
printf("%s\n", devices[i]->name);
if (strcmp(devices[i]->name, name) == 0)
return devices[i];
}
return NULL;
}
private:
ibv_device** const devices;
};
Tub<DeviceList> deviceList{};
void*
xmemalign(size_t alignment, size_t len)
{
void *p;
int r;
// alignment must be a power of two
if ((alignment & (alignment - 1)) != 0) {
DIE("xmemalign alignment (%lu) must be a power of two", alignment);
}
// alignment must be a multiple of sizeof(void*)
if (alignment % sizeof(void*) != 0) { // NOLINT
DIE("xmemalign alignment (%lu) must be a multiple of sizeof(void*)",
alignment);
}
r = posix_memalign(&p, alignment, len > 0 ? len : 1);
if (r != 0) {
DIE("posix_memalign(%lu, %lu) failed", alignment, len);
}
return p;
}
bool getIpAddress(const char* hostName, uint16_t port, sockaddr* address)
{
hostent host;
hostent* result;
char buffer[4096];
int error;
sockaddr_in* addr = (sockaddr_in*)(address);
addr->sin_family = AF_INET;
// Warning! The return value from getthostbyname_r is advertised
// as being the same as what is returned at error, but it is not;
// don't use it.
gethostbyname_r(hostName, &host, buffer, sizeof(buffer),
&result, &error);
if (result == 0) {
// If buffer is too small, an error value of ERANGE is supposed
// to be returned, but in fact it appears that error is -1 in
// the situation; check for both.
if ((error == ERANGE) || (error == -1)) {
DIE("IpAddress::IpAddress called gethostbyname_r"
" with too small a buffer");
}
DIE("couldn't find host %s", hostName);
}
memcpy(&addr->sin_addr, host.h_addr, sizeof(addr->sin_addr));
addr->sin_port = htons(port);
return true;
}
bool devSetup() {
deviceList.construct();
const char* name = NULL; // means match any it seems.
ibv_device* dev = deviceList->lookup(name);
if (dev == NULL) {
DIE("failed to find infiniband device: %s",
name == NULL ? "any" : name);
}
ctxt = ibv_open_device(dev);
if (ctxt == NULL) {
DIE("failed to open infiniband device: %s",
name == NULL ? "any" : name);
}
pd = ibv_alloc_pd(ctxt);
if (pd == NULL) {
DIE("failed to allocate infiniband protection domain: %d", errno);
}
return true;
}
void devDestroy() {
int rc = ibv_dealloc_pd(pd);
if (rc != 0) {
LOG(WARNING, "ibv_dealloc_pd failed");
}
rc = ibv_close_device(ctxt);
if (rc != 0)
LOG(WARNING, "ibv_close_device failed");
}
int
getLid(int port)
{
ibv_port_attr ipa;
int ret = ibv_query_port(ctxt, (uint8_t)(port), &ipa);
if (ret) {
DIE("ibv_query_port failed on port %u\n", port);
}
return ipa.lid;
}
ibv_srq*
createSharedReceiveQueue(uint32_t maxWr, uint32_t maxSge)
{
ibv_srq_init_attr sia;
memset(&sia, 0, sizeof(sia));
sia.srq_context = ctxt;
sia.attr.max_wr = maxWr;
sia.attr.max_sge = maxSge;
return ibv_create_srq(pd, &sia);
}
bool
setNonBlocking(int fd)
{
int flags = fcntl(fd, F_GETFL);
if (flags == -1) {
return false;
}
if (fcntl(fd, F_SETFL, flags | O_NONBLOCK)) {
return false;
}
return true;
}
void
createBuffers(void** ppBase,
BufferDescriptor descriptors[],
uint32_t bufferSize,
uint32_t bufferCount,
size_t threadNum)
{
const size_t bytes = bufferSize * bufferCount;
*ppBase = xmemalign(4096, bytes);
ibv_mr *mr = ibv_reg_mr(pd, *ppBase, bytes,
IBV_ACCESS_REMOTE_WRITE |
IBV_ACCESS_REMOTE_READ |
IBV_ACCESS_LOCAL_WRITE);
if (mr == NULL) {
DIE("failed to register buffer: %d", errno);
}
char* buffer = static_cast<char*>(*ppBase);
for (uint32_t i = 0; i < bufferCount; ++i) {
new(&descriptors[i]) BufferDescriptor(buffer, bufferSize, mr,
threadNum);
buffer += bufferSize;
}
}
void
postSrqReceive(ibv_srq* srq, BufferDescriptor *bd)
{
ibv_sge isge = {
reinterpret_cast<uint64_t>(bd->buffer),
bd->bytes,
bd->mr->lkey
};
ibv_recv_wr rxWorkRequest;
memset(&rxWorkRequest, 0, sizeof(rxWorkRequest));
rxWorkRequest.wr_id = reinterpret_cast<uint64_t>(bd);// stash descriptor ptr
rxWorkRequest.next = NULL;
rxWorkRequest.sg_list = &isge;
rxWorkRequest.num_sge = 1;
ibv_recv_wr *badWorkRequest;
int ret = ibv_post_srq_recv(srq, &rxWorkRequest, &badWorkRequest);
if (ret) {
DIE("Failure on ibv_post_srq_recv %d", ret);
}
}
void
postSrqReceiveAndKickTransmit(ibv_srq* srq, BufferDescriptor *bd)
{
postSrqReceive(srq, bd);
// XXX
#if 0
// This condition is hacky. One idea is to wrap ibv_srq in an
// object and make this a virtual method instead.
if (srq == clientSrq) {
--numUsedClientSrqBuffers;
if (!clientSendQueue.empty()) {
ClientRpc& rpc = clientSendQueue.front();
clientSendQueue.pop_front();
rpc.sendOrQueue();
double waitTime = Cycles::toSeconds(Cycles::rdtsc()
- rpc.waitStart);
if (waitTime > 1e-03) {
LOG(WARNING, "Outgoing %s RPC delayed for %.2f ms because "
"of insufficient receive buffers",
WireFormat::opcodeSymbol(rpc.request),
waitTime*1e03);
}
}
} else {
++numFreeServerSrqBuffers;
}
#endif
}
void
handleFileEvent()
{
sockaddr_in sin;
socklen_t sinlen = sizeof(sin);
QueuePairTuple incomingQpt;
ssize_t len = recvfrom(serverSetupSocket, &incomingQpt,
sizeof(incomingQpt), 0, reinterpret_cast<sockaddr *>(&sin), &sinlen);
if (len <= -1) {
if (errno == EAGAIN)