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
|
/*
* Copyright (c) 2015 ARM Limited
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Gabor Dozsa
*/
/* @file
* The interface class for multi gem5 simulations.
*/
#include "dev/multi_iface.hh"
#include <queue>
#include <thread>
#include "base/random.hh"
#include "base/trace.hh"
#include "debug/MultiEthernet.hh"
#include "debug/MultiEthernetPkt.hh"
#include "dev/etherpkt.hh"
#include "sim/sim_exit.hh"
#include "sim/sim_object.hh"
MultiIface::Sync *MultiIface::sync = nullptr;
MultiIface::SyncEvent *MultiIface::syncEvent = nullptr;
unsigned MultiIface::recvThreadsNum = 0;
MultiIface *MultiIface::master = nullptr;
bool
MultiIface::Sync::run(SyncTrigger t, Tick sync_tick)
{
std::unique_lock<std::mutex> sync_lock(lock);
trigger = t;
if (trigger != SyncTrigger::periodic) {
DPRINTF(MultiEthernet,"MultiIface::Sync::run() trigger:%d\n",
(unsigned)trigger);
}
switch (state) {
case SyncState::asyncCkpt:
switch (trigger) {
case SyncTrigger::ckpt:
assert(MultiIface::syncEvent->interrupted == false);
state = SyncState::busy;
break;
case SyncTrigger::periodic:
if (waitNum == 0) {
// So all recv threads got an async checkpoint request already
// and a simExit is scheduled at the end of the current tick
// (i.e. it is a periodic sync scheduled at the same tick as
// the simExit).
state = SyncState::idle;
DPRINTF(MultiEthernet,"MultiIface::Sync::run() interrupted "
"due to async ckpt scheduled\n");
return false;
} else {
// we still need to wait for some receiver thread to get the
// aysnc ckpt request. We are going to proceed as 'interrupted'
// periodic sync.
state = SyncState::interrupted;
DPRINTF(MultiEthernet,"MultiIface::Sync::run() interrupted "
"due to ckpt request is coming in\n");
}
break;
case SyncTrigger::atomic:
assert(trigger != SyncTrigger::atomic);
}
break;
case SyncState::idle:
state = SyncState::busy;
break;
// Only one sync can be active at any time
case SyncState::interrupted:
case SyncState::busy:
assert(state != SyncState::interrupted);
assert(state != SyncState::busy);
break;
}
// Kick-off the sync unless we are in the middle of an interrupted
// periodic sync
if (state != SyncState::interrupted) {
assert(waitNum == 0);
waitNum = MultiIface::recvThreadsNum;
// initiate the global synchronisation
assert(MultiIface::master != nullptr);
MultiIface::master->syncRaw(triggerToMsg[(unsigned)trigger], sync_tick);
}
// now wait until all receiver threads complete the synchronisation
auto lf = [this]{ return waitNum == 0; };
cv.wait(sync_lock, lf);
// we are done
assert(state == SyncState::busy || state == SyncState::interrupted);
bool ret = (state != SyncState::interrupted);
state = SyncState::idle;
return ret;
}
void
MultiIface::Sync::progress(MsgType msg)
{
std::unique_lock<std::mutex> sync_lock(lock);
switch (msg) {
case MsgType::cmdAtomicSyncAck:
assert(state == SyncState::busy && trigger == SyncTrigger::atomic);
break;
case MsgType::cmdPeriodicSyncAck:
assert(state == SyncState::busy && trigger == SyncTrigger::periodic);
break;
case MsgType::cmdCkptSyncAck:
assert(state == SyncState::busy && trigger == SyncTrigger::ckpt);
break;
case MsgType::cmdCkptSyncReq:
switch (state) {
case SyncState::busy:
if (trigger == SyncTrigger::ckpt) {
// We are already in a checkpoint sync but got another ckpt
// sync request. This may happen if two (or more) peer gem5
// processes try to start a ckpt nearly at the same time.
// Incrementing waitNum here (before decrementing it below)
// effectively results in ignoring this new ckpt sync request.
waitNum++;
break;
}
assert (waitNum == recvThreadsNum);
state = SyncState::interrupted;
// we need to fall over here to handle "recvThreadsNum == 1" case
case SyncState::interrupted:
assert(trigger == SyncTrigger::periodic);
assert(waitNum >= 1);
if (waitNum == 1) {
exitSimLoop("checkpoint");
}
break;
case SyncState::idle:
// There is no on-going sync so we got an async ckpt request. If we
// are the only receiver thread then we need to schedule the
// checkpoint. Otherwise, only change the state to 'asyncCkpt' and
// let the last receiver thread to schedule the checkpoint at the
// 'asyncCkpt' case.
// Note that a periodic or resume sync may start later and that can
// trigger a state change to 'interrupted' (so the checkpoint may
// get scheduled at 'interrupted' case finally).
assert(waitNum == 0);
state = SyncState::asyncCkpt;
waitNum = MultiIface::recvThreadsNum;
// we need to fall over here to handle "recvThreadsNum == 1" case
case SyncState::asyncCkpt:
assert(waitNum >= 1);
if (waitNum == 1)
exitSimLoop("checkpoint");
break;
default:
panic("Unexpected state for checkpoint request message");
break;
}
break;
default:
panic("Unknown msg type");
break;
}
waitNum--;
assert(state != SyncState::idle);
// Notify the simultaion thread if there is an on-going sync.
if (state != SyncState::asyncCkpt) {
sync_lock.unlock();
cv.notify_one();
}
}
void MultiIface::SyncEvent::start(Tick start, Tick interval)
{
assert(!scheduled());
if (interval == 0)
panic("Multi synchronisation period must be greater than zero");
repeat = interval;
schedule(start);
}
void
MultiIface::SyncEvent::adjust(Tick start_tick, Tick repeat_tick)
{
// The new multi interface may require earlier start of the
// synchronisation.
assert(scheduled() == true);
if (start_tick < when())
reschedule(start_tick);
// The new multi interface may require more frequent synchronisation.
if (repeat == 0)
panic("Multi synchronisation period must be greater than zero");
if (repeat < repeat_tick)
repeat = repeat_tick;
}
void
MultiIface::SyncEvent::process()
{
/*
* Note that this is a global event so this process method will be called
* by only exactly one thread.
*/
// if we are draining the system then we must not start a periodic sync (as
// it is not sure that all peer gem5 will reach this tick before taking
// the checkpoint).
if (isDraining == true) {
assert(interrupted == false);
interrupted = true;
DPRINTF(MultiEthernet,"MultiIface::SyncEvent::process() interrupted "
"due to draining\n");
return;
}
if (interrupted == false)
scheduledAt = curTick();
/*
* We hold the eventq lock at this point but the receiver thread may
* need the lock to schedule new recv events while waiting for the
* multi sync to complete.
* Note that the other simulation threads also release their eventq
* locks while waiting for us due to the global event semantics.
*/
curEventQueue()->unlock();
// we do a global sync here
interrupted = !MultiIface::sync->run(SyncTrigger::periodic, scheduledAt);
// Global sync completed or got interrupted.
// we are expected to exit with the eventq lock held
curEventQueue()->lock();
// schedule the next global sync event if this one completed. Otherwise
// (i.e. this one was interrupted by a checkpoint request), we will
// reschedule this one after the draining is complete.
if (!interrupted)
schedule(scheduledAt + repeat);
}
void MultiIface::SyncEvent::resume()
{
Tick sync_tick;
assert(!scheduled());
if (interrupted) {
assert(curTick() >= scheduledAt);
// We have to complete the interrupted periodic sync asap.
// Note that this sync might be interrupted now again with a checkpoint
// request from a peer gem5...
sync_tick = curTick();
schedule(sync_tick);
} else {
// So we completed the last periodic sync, let's find out the tick for
// next one
assert(curTick() > scheduledAt);
sync_tick = scheduledAt + repeat;
if (sync_tick < curTick())
panic("Cannot resume periodic synchronisation");
schedule(sync_tick);
}
DPRINTF(MultiEthernet,
"MultiIface::SyncEvent periodic sync resumed at %lld "
"(curTick:%lld)\n", sync_tick, curTick());
}
void MultiIface::SyncEvent::serialize(const std::string &base,
CheckpointOut &cp) const
{
// Save the periodic multi sync schedule information
paramOut(cp, base + ".periodicSyncRepeat", repeat);
paramOut(cp, base + ".periodicSyncInterrupted", interrupted);
paramOut(cp, base + ".periodicSyncAt", scheduledAt);
}
void MultiIface::SyncEvent::unserialize(const std::string &base,
CheckpointIn &cp)
{
paramIn(cp, base + ".periodicSyncRepeat", repeat);
paramIn(cp, base + ".periodicSyncInterrupted", interrupted);
paramIn(cp, base + ".periodicSyncAt", scheduledAt);
}
MultiIface::MultiIface(unsigned multi_rank,
Tick sync_start,
Tick sync_repeat,
EventManager *em) :
syncStart(sync_start), syncRepeat(sync_repeat),
recvThread(nullptr), eventManager(em), recvDone(nullptr),
scheduledRecvPacket(nullptr), linkDelay(0), rank(multi_rank)
{
DPRINTF(MultiEthernet, "MultiIface() ctor rank:%d\n",multi_rank);
if (master == nullptr) {
assert(sync == nullptr);
assert(syncEvent == nullptr);
sync = new Sync();
syncEvent = new SyncEvent();
master = this;
}
}
MultiIface::~MultiIface()
{
assert(recvThread);
delete recvThread;
if (this == master) {
assert(syncEvent);
delete syncEvent;
assert(sync);
delete sync;
}
}
void
MultiIface::packetOut(EthPacketPtr pkt, Tick send_delay)
{
MultiHeaderPkt::Header header_pkt;
unsigned address_length = MultiHeaderPkt::maxAddressLength();
// Prepare a multi header packet for the Ethernet packet we want to
// send out.
header_pkt.msgType = MsgType::dataDescriptor;
header_pkt.sendTick = curTick();
header_pkt.sendDelay = send_delay;
// Store also the source and destination addresses.
pkt->packAddress(header_pkt.srcAddress, header_pkt.dstAddress,
address_length);
header_pkt.dataPacketLength = pkt->size();
// Send out the multi hedare packet followed by the Ethernet packet.
sendRaw(&header_pkt, sizeof(header_pkt), header_pkt.dstAddress);
sendRaw(pkt->data, pkt->size(), header_pkt.dstAddress);
DPRINTF(MultiEthernetPkt,
"MultiIface::sendDataPacket() done size:%d send_delay:%llu "
"src:0x%02x%02x%02x%02x%02x%02x "
"dst:0x%02x%02x%02x%02x%02x%02x\n",
pkt->size(), send_delay,
header_pkt.srcAddress[0], header_pkt.srcAddress[1],
header_pkt.srcAddress[2], header_pkt.srcAddress[3],
header_pkt.srcAddress[4], header_pkt.srcAddress[5],
header_pkt.dstAddress[0], header_pkt.dstAddress[1],
header_pkt.dstAddress[2], header_pkt.dstAddress[3],
header_pkt.dstAddress[4], header_pkt.dstAddress[5]);
}
bool
MultiIface::recvHeader(MultiHeaderPkt::Header &header_pkt)
{
// Blocking receive of an incoming multi header packet.
return recvRaw((void *)&header_pkt, sizeof(header_pkt));
}
void
MultiIface::recvData(const MultiHeaderPkt::Header &header_pkt)
{
// We are here beacuse a header packet has been received implying
// that an Ethernet (data) packet is coming in next.
assert(header_pkt.msgType == MsgType::dataDescriptor);
// Allocate storage for the incoming Ethernet packet.
EthPacketPtr new_packet(new EthPacketData(header_pkt.dataPacketLength));
// Now execute the blocking receive and store the incoming data directly
// in the new EthPacketData object.
if (! recvRaw((void *)(new_packet->data), header_pkt.dataPacketLength))
panic("Missing data packet");
new_packet->length = header_pkt.dataPacketLength;
// Grab the event queue lock to schedule a new receive event for the
// data packet.
curEventQueue()->lock();
// Compute the receive tick. It includes the send delay and the
// simulated link delay.
Tick recv_tick = header_pkt.sendTick + header_pkt.sendDelay + linkDelay;
DPRINTF(MultiEthernetPkt, "MultiIface::recvThread() packet receive, "
"send_tick:%llu send_delay:%llu link_delay:%llu recv_tick:%llu\n",
header_pkt.sendTick, header_pkt.sendDelay, linkDelay, recv_tick);
if (recv_tick <= curTick()) {
panic("Simulators out of sync - missed packet receive by %llu ticks",
curTick() - recv_tick);
}
// Now we are about to schedule a recvDone event for the new data packet.
// We use the same recvDone object for all incoming data packets. If
// that is already scheduled - i.e. a receive event for a previous
// data packet is already pending - then we have to check whether the
// receive tick for the new packet is earlier than that of the currently
// pending event. Packets may arrive out-of-order with respect to
// simulated receive time. If that is the case, we need to re-schedule the
// recvDone event for the new packet. Otherwise, we save the packet
// pointer and the recv tick for the new packet in the recvQueue. See
// the implementation of the packetIn() method for comments on how this
// information is retrieved from the recvQueue by the simulation thread.
if (!recvDone->scheduled()) {
assert(recvQueue.size() == 0);
assert(scheduledRecvPacket == nullptr);
scheduledRecvPacket = new_packet;
eventManager->schedule(recvDone, recv_tick);
} else if (recvDone->when() > recv_tick) {
recvQueue.emplace(scheduledRecvPacket, recvDone->when());
eventManager->reschedule(recvDone, recv_tick);
scheduledRecvPacket = new_packet;
} else {
recvQueue.emplace(new_packet, recv_tick);
}
curEventQueue()->unlock();
}
void
MultiIface::recvThreadFunc()
{
EthPacketPtr new_packet;
MultiHeaderPkt::Header header;
// The new receiver thread shares the event queue with the simulation
// thread (associated with the simulated Ethernet link).
curEventQueue(eventManager->eventQueue());
// Main loop to wait for and process any incoming message.
for (;;) {
// recvHeader() blocks until the next multi header packet comes in.
if (!recvHeader(header)) {
// We lost connection to the peer gem5 processes most likely
// because one of them called m5 exit. So we stop here.
exit_message("info", 0, "Message server closed connection, "
"simulation is exiting");
}
// We got a valid multi header packet, let's process it
if (header.msgType == MsgType::dataDescriptor) {
recvData(header);
} else {
// everything else must be synchronisation related command
sync->progress(header.msgType);
}
}
}
EthPacketPtr
MultiIface::packetIn()
{
// We are called within the process() method of the recvDone event. We
// return the packet that triggered the current receive event.
// If there is further packets in the recvQueue, we also have to schedule
// the recvEvent for the next packet with the smallest receive tick.
// The priority queue container ensures that smallest receive tick is
// always on the top of the queue.
assert(scheduledRecvPacket != nullptr);
EthPacketPtr next_packet = scheduledRecvPacket;
if (! recvQueue.empty()) {
eventManager->schedule(recvDone, recvQueue.top().second);
scheduledRecvPacket = recvQueue.top().first;
recvQueue.pop();
} else {
scheduledRecvPacket = nullptr;
}
return next_packet;
}
void
MultiIface::spawnRecvThread(Event *recv_done, Tick link_delay)
{
assert(recvThread == nullptr);
// all receive thread must be spawned before simulation starts
assert(eventManager->eventQueue()->getCurTick() == 0);
recvDone = recv_done;
linkDelay = link_delay;
recvThread = new std::thread(&MultiIface::recvThreadFunc, this);
recvThreadsNum++;
}
DrainState
MultiIface::drain()
{
DPRINTF(MultiEthernet,"MultiIFace::drain() called\n");
// This can be called multiple times in the same drain cycle.
if (master == this) {
syncEvent->isDraining = true;
}
return DrainState::Drained;
}
void MultiIface::drainDone() {
if (master == this) {
assert(syncEvent->isDraining == true);
syncEvent->isDraining = false;
// We need to resume the interrupted periodic sync here now that the
// draining is done. If the last periodic sync completed before the
// checkpoint then the next one is already scheduled.
if (syncEvent->interrupted)
syncEvent->resume();
}
}
void MultiIface::serialize(const std::string &base, CheckpointOut &cp) const
{
// Drain the multi interface before the checkpoint is taken. We cannot call
// this as part of the normal drain cycle because this multi sync has to be
// called exactly once after the system is fully drained.
// Note that every peer will take a checkpoint but they may take it at
// different ticks.
// This sync request may interrupt an on-going periodic sync in some peers.
sync->run(SyncTrigger::ckpt, curTick());
// Save the periodic multi sync status
syncEvent->serialize(base, cp);
unsigned n_rx_packets = recvQueue.size();
if (scheduledRecvPacket != nullptr)
n_rx_packets++;
paramOut(cp, base + ".nRxPackets", n_rx_packets);
if (n_rx_packets > 0) {
assert(recvDone->scheduled());
scheduledRecvPacket->serialize(base + ".rxPacket[0]", cp);
}
for (unsigned i=1; i < n_rx_packets; i++) {
const RecvInfo recv_info = recvQueue.impl().at(i-1);
recv_info.first->serialize(base + csprintf(".rxPacket[%d]", i), cp);
Tick rx_tick = recv_info.second;
paramOut(cp, base + csprintf(".rxTick[%d]", i), rx_tick);
}
}
void MultiIface::unserialize(const std::string &base, CheckpointIn &cp)
{
assert(recvQueue.size() == 0);
assert(scheduledRecvPacket == nullptr);
assert(recvDone->scheduled() == false);
// restore periodic sync info
syncEvent->unserialize(base, cp);
unsigned n_rx_packets;
paramIn(cp, base + ".nRxPackets", n_rx_packets);
if (n_rx_packets > 0) {
scheduledRecvPacket = std::make_shared<EthPacketData>(16384);
scheduledRecvPacket->unserialize(base + ".rxPacket[0]", cp);
// Note: receive event will be scheduled when the link is unserialized
}
for (unsigned i=1; i < n_rx_packets; i++) {
EthPacketPtr rx_packet = std::make_shared<EthPacketData>(16384);
rx_packet->unserialize(base + csprintf(".rxPacket[%d]", i), cp);
Tick rx_tick = 0;
paramIn(cp, base + csprintf(".rxTick[%d]", i), rx_tick);
assert(rx_tick > 0);
recvQueue.emplace(rx_packet,rx_tick);
}
}
void MultiIface::initRandom()
{
// Initialize the seed for random generator to avoid the same sequence
// in all gem5 peer processes
assert(master != nullptr);
if (this == master)
random_mt.init(5489 * (rank+1) + 257);
}
void MultiIface::startPeriodicSync()
{
DPRINTF(MultiEthernet, "MultiIface:::initPeriodicSync started\n");
// Do a global sync here to ensure that peer gem5 processes are around
// (actually this may not be needed...)
sync->run(SyncTrigger::atomic, curTick());
// Start the periodic sync if it is a fresh simulation from scratch
if (curTick() == 0) {
if (this == master) {
syncEvent->start(syncStart, syncRepeat);
inform("Multi synchronisation activated: start at %lld, "
"repeat at every %lld ticks.\n",
syncStart, syncRepeat);
} else {
// In case another multiIface object requires different schedule
// for periodic sync than the master does.
syncEvent->adjust(syncStart, syncRepeat);
}
} else {
// Schedule the next periodic sync if resuming from a checkpoint
if (this == master)
syncEvent->resume();
}
DPRINTF(MultiEthernet, "MultiIface::initPeriodicSync done\n");
}
|