CMSDK 2.0.1
Cross-platform C++ base library and SDK for the Psyclone AIOS platform
Loading...
Searching...
No Matches
MemoryManager.cpp
Go to the documentation of this file.
1
9
10#include "MemoryManager.h"
11#include "PsyTime.h"
12#include "UnitTestFramework.h"
13
14namespace cmlabs {
15
17
18
19bool PsycloneIndex::GetStatus(uint16 port, uint8& status, uint64& heartbeat) {
21 if (!index) {
22 // LogPrint(0,0,0,"Couldn't open shared PsycloneIndex memory segment...");
23 return false;
24 }
25 // Closed again after reading: it used to stay mapped (one more mapping per call), because closing removed the
26 // shared index for every node on this machine.
27 PsycloneIndexEntry* e = (PsycloneIndexEntry*)(((char*)index)+sizeof(PsycloneIndexStruct));
28 for (uint32 n=0; n<PSYCLONE_INDEX_MAXCOUNT; n++, e++) {
29 if (e->port == port) {
30 status = e->status;
31 heartbeat = e->heartbeat;
33 return true;
34 }
35 }
37 //LogPrint(0,0,0,"Couldn't find Psyclone port %u in shared PsycloneIndex memory segment...", port);
38 status = PSYCLONE_STATUS_NONE;
39 heartbeat = 0;
40 return false;
41}
42
44 index = NULL;
45 entry = NULL;
46}
47
49 if (index)
51 entry = NULL;
53 index = NULL;
54}
55
56bool PsycloneIndex::init(uint16 port, uint64 instID) {
57 // The index is shared by every node on this machine, so no node removes its name when it ends (POSIX: the
58 // creator would, see CloseSharedMemorySegment); before, the first node to end took it away from the others.
60 if (!index) {
62 if (!index)
63 return false;
64 if (index->cid != PSYCLONEINDEXID) { // not if another node made it in the meantime
65 memset(index, 0, PSYCLONE_INDEX_SIZE);
66 index->size = PSYCLONE_INDEX_SIZE;
67 index->cid = PSYCLONEINDEXID;
68 }
69 }
71
72 // Entries now outlive their nodes, so a slot whose node ended, or stopped beating over a minute ago (crashed),
73 // is free for another port.
74 PsycloneIndexEntry* firstEmpty = NULL;
75 PsycloneIndexEntry* firstStale = NULL;
76 PsycloneIndexEntry* e = (PsycloneIndexEntry*)(((char*)index)+sizeof(PsycloneIndexStruct));
77 for (uint32 n=0; n<PSYCLONE_INDEX_MAXCOUNT; n++, e++) {
78 if (e->port == port) {
79 entry = e;
80 break;
81 }
82 else if (!firstEmpty && !e->port)
83 firstEmpty = e;
84 else if (!firstStale && e->port && ((e->status <= PSYCLONE_STATUS_ENDED) || (GetTimeAgeMS(e->heartbeat) > 60000)))
85 firstStale = e;
86 }
87 if (!entry) {
88 if (!firstEmpty)
89 firstEmpty = firstStale;
90 if (!firstEmpty)
91 return false;
92 entry = firstEmpty;
94 entry->heartbeat = 0;
95 entry->port = port;
96 entry->instanceID = instID;
97 }
98
99 return true;
100}
101
102bool PsycloneIndex::setStatus(uint8 status) {
103 if (!entry)
104 return false;
105 entry->status = status;
106 entry->heartbeat = GetTimeNow();
107 return true;
108}
109
110
111
113 mutex = NULL;
114 master = NULL;
115 port = 0;
116}
117
119 if (mutex)
120 mutex->enter(5000, __FUNCTION__);
122 master = NULL;
123 if (mutex)
124 mutex->leave();
125 delete(mutex);
126 mutex = NULL;
127}
128
130 mutex = new utils::Mutex(utils::StringFormat("PsycloneNodeMutex_%u", port).c_str(), true);
131 if (!mutex->enter(5000, __FUNCTION__)) {
132 return false;
133 }
134
135 //master = (MemoryMasterStruct*) utils::OpenSharedMemorySegment(utils::StringFormat("PsycloneNode_%u", port).c_str(), sizeof(MemoryMasterStruct));
136 //if (master) {
137 // utils::CloseSharedMemorySegment((char*)master, sizeof(MemoryMasterStruct));
138 // LogPrint(0,LOG_MEMORY,2,"MemoryManager removing stale shared memory (%u)...", port);
139 //}
140
141 master = (MemoryMasterStruct*) utils::CreateSharedMemorySegment(utils::StringFormat("PsycloneNode_%u", port).c_str(), sizeof(MemoryMasterStruct), true);
142 if (!master) {
143 mutex->leave();
144 return false;
145 }
146 memset(master, 0, sizeof(MemoryMasterStruct));
147 master->size = sizeof(MemoryMasterStruct);
148 master->cid = PSYCLONEMASTERID;
149 master->status = 1; // init
150 master->createdTime = GetTimeNow();
151 this->port = port;
152 mutex->leave();
153 return true;
154}
155
157 mutex = new utils::Mutex(utils::StringFormat("PsycloneNodeMutex_%u", port).c_str());
158 if (!mutex->enter(5000, __FUNCTION__))
159 return false;
160
161 master = (MemoryMasterStruct*) utils::OpenSharedMemorySegment(utils::StringFormat("PsycloneNode_%u", port).c_str(), sizeof(MemoryMasterStruct));
162 if (!master) {
163 mutex->leave();
164 return false;
165 }
166 if (master->cid != PSYCLONEMASTERID) {
168 mutex->leave();
169 return false;
170 }
171 this->port = port;
172 mutex->leave();
173 return true;
174}
175
176
178 if (!mutex || !master || !mutex->enter(5000, __FUNCTION__))
179 return 0;
180 uint16 res = master->nodeID;
181 mutex->leave();
182 return res;
183}
184
186 if (!mutex || !master || !mutex->enter(5000, __FUNCTION__))
187 return 0;
188 uint64 res = master->createdTime;
189 mutex->leave();
190 return res;
191}
192
193bool MasterMemory::setNodeID(uint16 id) {
194 if (!mutex || !master || !mutex->enter(5000, __FUNCTION__))
195 return 0;
196 master->nodeID = id;
197 mutex->leave();
198 return true;
199}
200
202 if (!mutex || !master || !mutex->enter(5000, __FUNCTION__))
203 return 0;
204 uint32 res = master->dynamicShmemSerial;
205 mutex->leave();
206 return res;
207}
208
210 if (!mutex || !master || !mutex->enter(5000, __FUNCTION__))
211 return 0;
212 uint32 res = master->processShmemSerial;
213 mutex->leave();
214 return res;
215}
216
218 if (!mutex || !master || !mutex->enter(5000, __FUNCTION__))
219 return 0;
220 uint32 res = master->componentShmemSerial;
221 mutex->leave();
222 return res;
223}
224
226 if (!mutex || !master || !mutex->enter(5000, __FUNCTION__))
227 return 0;
228 uint32 res = master->datamapsShmemSerial;
229 mutex->leave();
230 return res;
231}
232
233
234
236 if (!mutex || !master || !mutex->enter(5000, __FUNCTION__))
237 return 0;
238 uint32 res = ++master->dynamicShmemSerial;
239 mutex->leave();
240 return res;
241}
242
244 if (!mutex || !master || !mutex->enter(5000, __FUNCTION__))
245 return 0;
246 uint32 res = ++master->processShmemSerial;
247 mutex->leave();
248 return res;
249}
250
252 if (!mutex || !master || !mutex->enter(5000, __FUNCTION__))
253 return 0;
254 uint32 res = ++master->componentShmemSerial;
255 mutex->leave();
256 return res;
257}
258
260 if (!mutex || !master || !mutex->enter(5000, __FUNCTION__))
261 return 0;
262 uint32 res = ++master->datamapsShmemSerial;
263 mutex->leave();
264 return res;
265}
266
267
269 if (!mutex || !master || !mutex->enter(5000, __FUNCTION__))
270 return 0;
271 uint64 res = master->dynamicShmemSize;
272 mutex->leave();
273 return res;
274}
275
277 if (!mutex || !master || !mutex->enter(5000, __FUNCTION__))
278 return 0;
279 uint64 res = master->processShmemSize;
280 mutex->leave();
281 return res;
282}
283
285 if (!mutex || !master || !mutex->enter(5000, __FUNCTION__))
286 return 0;
287 uint64 res = master->componentShmemSize;
288 mutex->leave();
289 return res;
290}
291
293 if (!mutex || !master || !mutex->enter(5000, __FUNCTION__))
294 return 0;
295 uint64 res = master->datamapsShmemSize;
296 mutex->leave();
297 return res;
298}
299
301 if (!mutex || !master || !mutex->enter(5000, __FUNCTION__))
302 return false;
303 master->dynamicShmemSize = size;
304 mutex->leave();
305 return true;
306}
307
309 if (!mutex || !master || !mutex->enter(5000, __FUNCTION__))
310 return false;
311 master->processShmemSize = size;
312 mutex->leave();
313 return true;
314}
315
317 if (!mutex || !master || !mutex->enter(5000, __FUNCTION__))
318 return false;
319 master->componentShmemSize = size;
320 mutex->leave();
321 return true;
322}
323
325 if (!mutex || !master || !mutex->enter(5000, __FUNCTION__))
326 return false;
327 master->datamapsShmemSize = size;
328 mutex->leave();
329 return true;
330}
331
332bool MasterMemory::setID(uint16 id) {
333 port = id;
334 return true;
335}
336
338 return port;
339}
340
341
342
343
344
345
346
347
348
349
350// static
351//bool MemoryManager::GetMemoryUsage(uint32& total, uint32& usage, uint32& sysTotal, uint32& sysUsage, uint32& staticTotal, uint32& staticUsage, uint32& dynamicTotal, uint32& dynamicUsage) {
352// if (!MemoryManager::Singleton)
353// return false;
354// //if (!MemoryManager::Singleton->pageMasterMutex->enter())
355// // return false;
356// //sysTotal = MemoryManager::Singleton->pageMaster->dataSize[MP_SYSTEMPAGE];
357// //sysUsage = MemoryManager::Singleton->pageMaster->dataUsage[MP_SYSTEMPAGE];
358// //staticTotal = MemoryManager::Singleton->pageMaster->dataSize[MP_STATICPAGE];
359// //staticUsage = MemoryManager::Singleton->pageMaster->dataUsage[MP_STATICPAGE];
360// //dynamicTotal = MemoryManager::Singleton->pageMaster->dataSize[MP_DYNAMICPAGE];
361// //dynamicUsage = MemoryManager::Singleton->pageMaster->dataUsage[MP_DYNAMICPAGE];
362// //total = sysTotal + staticTotal + dynamicTotal;
363// //usage = sysUsage + staticUsage + dynamicUsage;
364// //MemoryManager::Singleton->pageMasterMutex->leave();
365// return true;
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
392 psycloneIndex = NULL;
393 masterMemory = NULL;
394 temporalMemory = NULL;
395 processMemory = NULL;
396 componentMemory = NULL;
397 dataMapsMemory = NULL;
398
399 shouldContinue = true;
400 isRunning = false;
401 isLocalMaster = false;
402 managementThreadID = 0;
403 thisInstance = 0;
404}
405
407// MemoryManager::Singleton = NULL;
408 shouldContinue = false;
409 uint32 c = 0;
410 while (isRunning) {
411 utils::Sleep(50);
412 if (c++ > 10)
413 break;
414 }
415 if (isLocalMaster) {
417 }
418 uint16 sweepPort = (isLocalMaster && masterMemory) ? masterMemory->port : 0;
419
420 delete(temporalMemory);
421 temporalMemory = NULL;
422 delete(processMemory);
423 processMemory = NULL;
424 delete(componentMemory);
425 componentMemory = NULL;
426 delete(dataMapsMemory);
427 dataMapsMemory = NULL;
428 delete(masterMemory);
429 masterMemory = NULL;
430 // The node removes every name of its port: segments that a resize made in any process and the queue
431 // semaphores belong to the node, and no other process removes them (see CloseSharedMemorySegment). Done while
432 // the index still says READY, so a new node on this port cannot start in between and lose its own.
433 if (sweepPort) {
434 uint32 removed = utils::RemovePortSharedSegments(sweepPort);
435 if (removed)
436 LogPrint(0, LOG_MEMORY, 3, "Removed %u shared name(s) of port %u at shutdown...", removed, sweepPort);
437 }
438 if (psycloneIndex)
439 psycloneIndex->setStatus(PSYCLONE_STATUS_ENDED);
440 delete(psycloneIndex);
441 psycloneIndex = NULL;
442}
443
444bool MemoryManager::getMemoryUsage(uint64& sysAlloc, uint64& sysUsage, uint64& dataAlloc, uint64& dataUsage) {
445 if (!masterMemory)
446 return false;
447
448 uint64 alloc = 0, usage = 0;
449 if (temporalMemory && temporalMemory->getMemoryUsage(alloc, usage)) {
450 dataAlloc = alloc;
451 dataUsage = usage;
452 }
453
454 sysAlloc = sysUsage = sizeof(MemoryMasterStruct);
455
456 if (processMemory && processMemory->getMemoryUsage(alloc, usage)) {
457 sysAlloc += alloc;
458 sysUsage += usage;
459 }
460 if (componentMemory && processMemory->getMemoryUsage(alloc, usage)) {
461 sysAlloc += alloc;
462 sysUsage += usage;
463 }
464 if (dataMapsMemory && dataMapsMemory->getMemoryUsage(alloc, usage)) {
465 sysAlloc += alloc;
466 sysUsage += usage;
467 }
468 return true;
469}
470
471
472uint8 MemoryManager::getNodeStatus(uint64& lastseen, uint64& createdTime) {
473 lastseen = 0;
474 if (!masterMemory)
476 uint8 status = 0;
477 PsycloneIndex::GetStatus(masterMemory->port, status, lastseen);
478 createdTime = masterMemory->getCreatedTime();
479 return status;
480}
481
482// Connect to existing PageMaster in shared memory
483bool MemoryManager::connect(uint16 port, bool isLocalMaster) {
484 uint8 status = 0;
485 uint64 heartbeat = 0;
486 if ((!PsycloneIndex::GetStatus(port, status, heartbeat)) || (status == PSYCLONE_STATUS_NONE) || (!heartbeat)) {
487 LogPrint(0,LOG_MEMORY,3,"Cannot find node running on port %u...", port);
488 return false;
489 }
490 else if (status <= PSYCLONE_STATUS_ENDED) {
491 LogPrint(0,LOG_MEMORY,3,"Node no longer running on port %u...", port);
492 return false;
493 }
494 else if (GetTimeAgeMS(heartbeat) > 5000) {
495 LogPrint(0,LOG_MEMORY,3,"Node on port %u is no longer responding...", port);
496 return false;
497 }
498 else if (status == PSYCLONE_STATUS_INIT) {
499 LogPrint(0,LOG_MEMORY,3,"Node starting up on port %u, please try again in a little while...", port);
500 return false;
501 }
502
503 this->isLocalMaster = isLocalMaster;
504 masterMemory = new MasterMemory();
505 if (!masterMemory->open(port)) {
506 LogPrint(0,LOG_MEMORY,0,"Cannot open MasterMemory on port %u...", port);
507 delete(masterMemory);
508 masterMemory = NULL;
509 return false;
510 }
511
512 temporalMemory = new TemporalMemory(masterMemory);
513 if (!temporalMemory->open()) {
514 LogPrint(0,LOG_MEMORY,0,"Cannot open TemporalMemory on port %u...", port);
515 delete(temporalMemory);
516 temporalMemory = NULL;
517 delete(masterMemory);
518 masterMemory = NULL;
519 return false;
520 }
521 temporalMemory->setNodeID(masterMemory->getNodeID());
522
523 componentMemory = new ComponentMemory(masterMemory);
524 if (!componentMemory->open()) {
525 LogPrint(0,LOG_MEMORY,0,"Cannot open ComponentMemory on port %u...", port);
526 delete(componentMemory);
527 componentMemory = NULL;
528 delete(masterMemory);
529 masterMemory = NULL;
530 return false;
531 }
532
533 dataMapsMemory = new DataMapsMemory(masterMemory);
534 if (!dataMapsMemory->open()) {
535 LogPrint(0,LOG_MEMORY,0,"Cannot open DataMapsMemory on port %u...", port);
536 delete(dataMapsMemory);
537 dataMapsMemory = NULL;
538 delete(masterMemory);
539 masterMemory = NULL;
540 return false;
541 }
542
543 processMemory = new ProcessMemory(masterMemory);
544 if (!processMemory->open()) {
545 LogPrint(0,LOG_MEMORY,0,"Cannot open ProcessMemory on port %u...", port);
546 delete(processMemory);
547 processMemory = NULL;
548 delete(masterMemory);
549 masterMemory = NULL;
550 return false;
551 }
552
553 if (!ThreadManager::CreateThread(MemoryManagement, this, managementThreadID)) {
554 return false;
555 }
556
557 return true;
558}
559
560// Create a new PageMaster in shared memory
561bool MemoryManager::create(uint16 sysID, uint32 slotCount, uint16 binCount, uint32 minBlockSize, uint32 maxBlockSize, uint64 initSize, uint64 maxSize, bool force) {
562
563 this->isLocalMaster = true;
564 uint8 status = 0;
565 uint64 heartbeat = 0;
566 if (PsycloneIndex::GetStatus(sysID, status, heartbeat) && (GetTimeAgeMS(heartbeat) < 500)) {
567 if (status == PSYCLONE_STATUS_INIT) {
568 LogPrint(0,LOG_MEMORY,0,"Another node is currently (%ums ago) starting up on port %u...", GetTimeAgeMS(heartbeat), sysID);
569 return false;
570 }
571 else if (status == PSYCLONE_STATUS_READY) {
572 LogPrint(0,LOG_MEMORY,0,"Another node is currently running or crashed %s ago on port %u...", PrintTimeDifString(GetTimeAge(heartbeat)).c_str(), sysID);
573 return false;
574 }
575 }
576
577 // No live node on this port (verified above): reclaim any stale OS segments
578 // (shmem + named semaphores) left by a previous crashed/killed node.
580
581 psycloneIndex = new PsycloneIndex();
582 if (!psycloneIndex->init(sysID, GetTimeNow())) {
583 LogPrint(0, LOG_MEMORY, 0, "Cannot init index memory on port %u...", sysID);
584 return false;
585 }
586
587 masterMemory = new MasterMemory();
588 if (!masterMemory->create(sysID)) {
589 LogPrint(0, LOG_MEMORY, 0, "Cannot create MasterMemory...");
590 return false;
591 }
592
593 temporalMemory = new TemporalMemory(masterMemory);
594 if (!temporalMemory->create(slotCount, binCount, minBlockSize, maxBlockSize, initSize, maxSize)) {
595 LogPrint(0, LOG_MEMORY, 0, "Cannot create TemporalMemory...");
596 return false;
597 }
598
599 componentMemory = new ComponentMemory(masterMemory);
600 // Create initial room for 1024 average components
601 // Will expand as needed
602 if (!componentMemory->create(1024)) {
603 LogPrint(0, LOG_MEMORY, 0, "Cannot create ComponentMemory...");
604 return false;
605 }
606
607 dataMapsMemory = new DataMapsMemory(masterMemory);
608 // Create initial room for 1024 typelevels, contextlevels, tags, cranks, requests
609 // Will expand as needed
610 if (!dataMapsMemory->create(1024, 1024, 1024, 1024, 1024)) {
611 LogPrint(0, LOG_MEMORY, 0, "Cannot create DataMapsMemory...");
612 return false;
613 }
614
615 processMemory = new ProcessMemory(masterMemory);
616 // Create initial room for 16 processes
617 // Will expand as needed
618 if (!processMemory->create(16)) {
619 LogPrint(0, LOG_MEMORY, 0, "Cannot create ProcessMemory...");
620 return false;
621 }
622
623 psycloneIndex->setStatus(PSYCLONE_STATUS_READY);
624
625 if (!ThreadManager::CreateThread(MemoryManagement, this, managementThreadID)) {
626 return false;
627 }
628
629 return true;
630}
631
633 return masterMemory->getNodeID();
634}
635
637 masterMemory->setNodeID(id);
638 temporalMemory->setNodeID(id);
639 return true;
640}
641
643 DataMessage* msg = new DataMessage();
644 if (!this->componentMemory->writeComponentNamesToMsg(msg)) {
645 delete msg;
646 return NULL;
647 }
648 if (!this->dataMapsMemory->writeIDsToMsg(msg)) {
649 delete msg;
650 return NULL;
651 }
652 return msg;
653}
654
655
656
657bool MemoryManager::getTimeSyncData(uint64& tmc, int64& adjust) {
658 tmc = masterMemory->master->currentTMC;
659 adjust = masterMemory->master->localSyncAdjustment;
660 return true;
661}
662
663bool MemoryManager::setTimeSyncData(uint64 tmc, int64 adjust) {
664 masterMemory->master->currentTMC = tmc;
665 masterMemory->master->localSyncAdjustment = adjust;
666 return true;
667}
668
669// Insert new block of memory and return full id
671 if (!temporalMemory)
672 return false;
673 return temporalMemory->insertMessage(msg, id);
674}
675
676// Get copy of block of memory
678 if (!temporalMemory)
679 return NULL;
680 return temporalMemory->getCopyOfMessage(id);
681}
682
684 if (!type[0])
685 return "NOTYPE";
686 if (type[0] == 1)
687 return utils::StringFormat("PsyControlMessage %u.%u", type[1], type[2]);
688 std::string str = subTypeToText(type[0]);
689 uint8 level = 0;
690 while (type[level+1])
691 str += std::string(".") + subTypeToText(type[++level]);
692 return str;
693}
694
695std::string MemoryManager::subTypeToText(uint16 subtype) {
696 if (!subtype)
697 return "-";
698 else if (subtype == 0xFFFF)
699 return "*";
700 std::string str;
701 char* data = new char[MAXKEYNAMELEN+1];
702 if (dataMapsMemory->getTypeLevelName(subtype, data, MAXKEYNAMELEN))
703 str = data;
704 delete [] data;
705 return str;
706}
707
709 if (!context[0])
710 return "NOCONTEXT";
711 std::string str = subContextToText(context[0]);
712 uint8 level = 0;
713 while (context[level+1])
714 str += std::string(".") + subContextToText(context[++level]);
715 return str;
716}
717
718std::string MemoryManager::subContextToText(uint16 subcontext) {
719 if (!subcontext)
720 return "-";
721 else if (subcontext == 0xFFFF)
722 return "*";
723 std::string str;
724 char* data = new char[MAXKEYNAMELEN+1];
725 if (dataMapsMemory->getContextLevelName(subcontext, data, MAXKEYNAMELEN))
726 str = data;
727 delete [] data;
728 return str;
729}
730
731std::string MemoryManager::getComponentName(uint32 compID) {
732 std::string str;
733 char* data = new char[MAXKEYNAMELEN+1];
734 if (componentMemory->getComponentName(compID, data, MAXKEYNAMELEN))
735 str = data;
736 delete [] data;
737 return str;
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
777
778// Continuous management of eol pages
779uint32 MemoryManager::runManager() {
780 //LogPrint(0, LOG_SYSTEM, 0, "Memory Management (%p) running...\n\n", this);
781 isRunning = true;
782 uint64 tmc;
783 int64 netTimeSync;
784
785 uint64 nextPageCheck = 0; //, now;
786
787 while (shouldContinue) {
788 if (isLocalMaster) {
789 if (GetCurrentTimeSyncData(tmc, netTimeSync))
790 setTimeSyncData(tmc, netTimeSync);
792 if (psycloneIndex)
793 psycloneIndex->setStatus(PSYCLONE_STATUS_READY);
794 }
795 else {
796 // Update Sync Time
797 if (getTimeSyncData(tmc, netTimeSync) )
798 SetCurrentTimeSyncData(tmc, netTimeSync);
799 }
800
801 utils::Sleep(100);
802 }
803
804 isRunning = false;
805 //LogPrint(0, LOG_SYSTEM, 0, "Memory Management (%p) stopped running...\n\n", this);
806 return 0;
807}
808
810
811 // Create and initialise the MemoryManager (static memory management)
812 unittest::progress(5, "create manager");
813 MemoryManager* manager = new MemoryManager();
814 uint32 maxPageCount = 15;
815 if (!manager->create(0)) {
816 unittest::fail("MemoryManager test: create() failed");
817 delete(manager);
818 return false;
819 }
820
821 uint64 eol = GetTimeNow() + 100000000; // +100sec
822 uint32 size = 4096;
823 char* data = new char[size];
824
825 // we should be able to add this many blocks
826 uint32 expectedCount = 100; // CalcBlockTableSize(size);
827 uint32 expectedMaxCount = (maxPageCount-10) * expectedCount;
828 uint32 count = expectedMaxCount;
829 uint64* ids = new uint64[count];
830
831 DataMessage* msg = new DataMessage();
832 msg->setData("data", data, size);
833 msg->setEOL(eol);
834 uint32 n;
835 uint64 id;
836
837 // Write phase
838 unittest::progress(20, "insert messages");
839 uint64 t1 = GetTimeNow();
840 for (n=0; n<count; n++) {
841 msg->setInt("Test", n);
842 if (!manager->insertMessage(msg, id)) {
843 unittest::fail("MemoryManager test: insert %u failed", n);
844 delete [] ids;
845 delete [] data;
846 delete(msg);
847 delete(manager);
848 return false;
849 }
850 ids[n] = id;
851 }
852 uint64 t2 = GetTimeNow();
853
854 // Read-back phase
855 unittest::progress(60, "read back messages");
856 DataMessage* msg2;
857 for (n=0; n<count; n++) {
858 msg2 = manager->getCopyOfMessage(ids[n]);
859 if (msg2 == NULL) {
860 unittest::fail("MemoryManager test: getCopyOfMessage %u failed", n);
861 delete [] ids;
862 delete [] data;
863 delete(msg);
864 delete(manager);
865 return false;
866 }
867 if (msg->getSize() != msg2->getSize()) {
868 unittest::fail("MemoryManager test: getCopyOfMessage wrong size (%u != %u)", msg->getSize(), msg2->getSize());
869 delete [] ids;
870 delete [] data;
871 delete(msg);
872 delete(msg2);
873 delete(manager);
874 return false;
875 }
876 int64 val64;
877 if ((!msg2->getInt("Test", val64)) || (val64 != n)) {
878 unittest::fail("MemoryManager test: getCopyOfMessage wrong data (%lld != %u)", val64, n);
879 delete [] ids;
880 delete [] data;
881 delete(msg);
882 delete(msg2);
883 delete(manager);
884 return false;
885 }
886 delete(msg2);
887 }
888 uint64 t3 = GetTimeNow();
889
890 unittest::progress(90, "record metrics");
891 double writeUs = (double)(t2 - t1);
892 double readUs = (double)(t3 - t2);
893 if (writeUs > 0.0) {
894 unittest::metric("write_throughput", (1.0*size*count)/writeUs, "MB/s", true);
895 unittest::metric("write_rate", (1000000.0*count)/writeUs, "msg/s", true);
896 unittest::metric("avg_write_latency", writeUs/count, "us", false);
897 }
898 if (readUs > 0.0) {
899 unittest::metric("read_throughput", (1.0*size*count)/readUs, "MB/s", true);
900 unittest::metric("read_rate", (1000000.0*count)/readUs, "msg/s", true);
901 unittest::metric("avg_read_latency", readUs/count, "us", false);
902 }
903 unittest::detail("Writing %u: %.3f MB/s / %.3f msg/s (%u us) [%u b]",
904 count, (1.0*size*count)/writeUs, (1000000.0*count)/writeUs, (uint32)writeUs, size);
905 unittest::detail("Reading %u: %.3f MB/s / %.3f msg/s (%u us) [%u b]",
906 count, (1.0*size*count)/readUs, (1000000.0*count)/readUs, (uint32)readUs, size);
907
908 delete [] ids;
909 delete [] data;
910 delete(msg);
911 delete(manager);
912
913 unittest::progress(100, "done");
914 return true;
915}
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935//bool MemoryManagerX::GetMemoryUsage(uint32& total, uint32& usage, uint32& sysTotal, uint32& sysUsage, uint32& staticTotal, uint32& staticUsage, uint32& dynamicTotal, uint32& dynamicUsage) {
936// if (!MemoryManagerX::Singleton)
937// return false;
938// if (!MemoryManagerX::Singleton->pageMasterMutex->enter())
939// return false;
940// sysTotal = MemoryManagerX::Singleton->pageMaster->dataSize[MP_SYSTEMPAGE];
941// sysUsage = MemoryManagerX::Singleton->pageMaster->dataUsage[MP_SYSTEMPAGE];
942// staticTotal = MemoryManagerX::Singleton->pageMaster->dataSize[MP_STATICPAGE];
943// staticUsage = MemoryManagerX::Singleton->pageMaster->dataUsage[MP_STATICPAGE];
944// dynamicTotal = MemoryManagerX::Singleton->pageMaster->dataSize[MP_DYNAMICPAGE];
945// dynamicUsage = MemoryManagerX::Singleton->pageMaster->dataUsage[MP_DYNAMICPAGE];
946// total = sysTotal + staticTotal + dynamicTotal;
947// usage = sysUsage + staticUsage + dynamicUsage;
948// MemoryManagerX::Singleton->pageMasterMutex->leave();
949// return true;
950//}
951//
952//
953//MemoryManagerX::MemoryManagerX() {
954// shouldContinue = true;
955// isRunning = false;
956// isMaster = false;
957// pageMaster = NULL;
958// pageMasterMutex = NULL;
959// pageCache = NULL;
960//
961//}
962//
963//MemoryManagerX::~MemoryManagerX() {
964// if (pageMaster == NULL)
965// return;
966// pageMasterMutex->enter();
967// MemoryManagerX::Singleton = NULL;
968// shouldContinue = false;
969// uint32 c = 0;
970// while (isRunning) {
971// utils::Sleep(50);
972// if (c++ > 10)
973// break;
974// }
975// ThreadManager::Shutdown();
976// destroyAllPages();
977//
978// utils::DestroySharedMemorySegment((char*)pageMaster, pageMaster->size);
979// pageMaster = NULL;
980// pageMasterMutex->leave();
981// delete(pageMasterMutex);
982// pageMaster = NULL;
983// pageMasterMutex = NULL;
984// free(pageCache);
985//}
986//
988//bool MemoryManagerX::connect(uint16 sysID) {
990// uint32 size = sizeof(MemoryPageMaster);
991// isMaster = false;
992//
993// utils::SetSharedSystemInstance(sysID);
994//
995// pageMasterMutex = new utils::Mutex("PageMaster");
996// if (!pageMasterMutex->enter())
997// return false;
998//
999// pageMaster = (MemoryPageMaster*) utils::OpenSharedMemorySegment("CMSysMemory", size);
1000// if (pageMaster == NULL) {
1001// fprintf(stderr, "MemoryManager could not open shared memory id '%u'\n", sysID);
1002// pageMasterMutex->leave();
1003// return false;
1004// }
1005//
1006// MemoryManagerX::Singleton = this;
1007//
1008// LocalSyncAdjustment = pageMaster->timesync;
1009//
1010// if (!ThreadManager::CreateThread(MemoryManagement, NULL, managementThreadID)) {
1011// pageMasterMutex->leave();
1012// return false;
1013// }
1014//
1015// // Unlock the Mutex
1016// pageMasterMutex->leave();
1017// return true;
1018//}
1019//
1021//bool MemoryManagerX::create(uint16 sysID, uint32 staticPageTableSize, uint32 slotCount, uint32 slotDuration, uint32 bufferSlots, uint32 pagesPerSlot, bool force) {
1022// isMaster = true;
1023//
1024// utils::SetSharedSystemInstance(sysID);
1025//
1026// uint32 size = sizeof(MemoryPageMaster);
1027//
1028// char* data;
1029// if (force) {
1030// // Destroy CMSysMemory first...
1031// if ( (data = utils::OpenSharedMemorySegment("CMSysMemory", size)) != NULL)
1032// utils::DestroySharedMemorySegment(data, size);
1033// }
1034//
1035// pageMasterMutex = new utils::Mutex("PageMaster");
1036// if (!pageMasterMutex->enter())
1037// return false;
1038//
1039// uint32 maxPageCount = staticPageTableSize + ( (slotCount+bufferSlots) * pagesPerSlot );
1040//
1042// // Add the bitfield size = max count / 32
1043// uint32 bitFieldSize = (uint32)ceil((double)maxPageCount / 8);
1044// // Add the table size
1045// uint32 datasize = maxPageCount * sizeof(MemoryPageEntry);
1046// size += bitFieldSize + datasize;
1047//
1048// pageMaster = (MemoryPageMaster*) utils::CreateSharedMemorySegment("CMSysMemory", size);
1049// if (pageMaster == NULL) {
1050// fprintf(stderr, "MemoryManager could not create shared memory\n");
1051// pageMasterMutex->leave();
1052// pageMasterMutex->destroy();
1053// return false;
1054// }
1055//
1056// // Initialise the PageMaster structure
1057// pageMaster->status = 1; // 10 means fully initialised
1059//
1060// pageMaster->size = size; // total size of PageMaster in bytes
1061// pageMaster->sysID = sysID; // global node id
1062// pageMaster->dataSize[MP_SYSTEMPAGE] = 0; // total size of data space in bytes
1063// pageMaster->dataSize[MP_STATICPAGE] = 0; // total size of data space in bytes
1064// pageMaster->dataSize[MP_DYNAMICPAGE] = 0; // total size of data space in bytes
1065// pageMaster->dataUsage[MP_SYSTEMPAGE] = 0; // current usage of all pages in bytes, for info only
1066// pageMaster->dataUsage[MP_STATICPAGE] = 0; // current usage of all pages in bytes, for info only
1067// pageMaster->dataUsage[MP_DYNAMICPAGE] = 0; // current usage of all pages in bytes, for info only
1068// pageMaster->count[MP_SYSTEMPAGE] = 0; // current number of pages in use, for info only
1069// pageMaster->count[MP_STATICPAGE] = 0; // current number of pages in use, for info only
1070// pageMaster->count[MP_DYNAMICPAGE] = 0; // current number of pages in use, for info only
1071// pageMaster->bitFieldSize = bitFieldSize; // number of bytes in the bitfield
1072// pageMaster->pageTableSize = maxPageCount; // maximum entries in page table and number of bits in bit field
1073// memset((void*)MP_GetBitFieldLoc(pageMaster), 255, bitFieldSize);
1074// memset((void*)MP_GetPageTableLoc(pageMaster), 0, datasize);
1075//
1076// MemoryManagerX::Singleton = this;
1077//
1078// pageMaster->status = 2; // 10 means fully initialised
1080//
1081// pageMaster->timesync = LocalSyncAdjustment;
1082//
1083// pageMaster->createdTime = GetTimeNow();
1084//
1085// pageMaster->status = 3; // 10 means fully initialised
1087//
1088// // Create and initialise the EOL Page
1089// if (!resizeEOLPage(slotCount, pagesPerSlot, slotDuration, bufferSlots)) {
1090// fprintf(stderr, "MemoryManager could not resize EOL page\n");
1091// pageMasterMutex->leave();
1092// return false;
1093// }
1094//
1095// pageMaster->status = 4; // 10 means fully initialised
1097//
1098// if (!createSystemPages()) {
1099// fprintf(stderr, "MemoryManager could not create system pages\n");
1100// pageMasterMutex->leave();
1101// return false;
1102// }
1103//
1104// pageMaster->status = 5; // 10 means fully initialised
1106//
1107// pageMaster->lastCreatedStaticPage = RESERVEDPAGECOUNT-1; // id of last created static page
1108// // printBitFieldAsString("Initial Bitfield");
1109//
1110// pageMaster->status = 6; // 10 means fully initialised
1112//
1113// if (!ThreadManager::CreateThread(MemoryManagement, NULL, managementThreadID)) {
1114// pageMasterMutex->leave();
1115// return false;
1116// }
1117//
1118// pageMaster->status = 7; // 10 means fully initialised
1120//
1121// pageMaster->status = 10; // 10 means fully initialised
1122// // Unlock the Mutex
1123// pageMasterMutex->leave();
1124// return true;
1125//}
1126//
1127//
1128//
1129//
1130//
1131//
1132//
1133//
1134//
1135//
1136//
1137//
1138//
1139//
1140//
1141//
1142//
1143//
1144//
1145//
1146//
1265//
1267//char* MemoryManagerX::createSystemPage(uint32 id, uint32 size, uint64& memID) {
1268//
1269// // Mutex is still locked from callar
1270// uint32 pageID = id;
1271// MemoryPage* page = createPage(size+sizeof(MemoryBlock), 1, 0, pageID);
1272// if (page == NULL)
1273// return NULL;
1274// if (pageID != id) {
1275// destroyPage(pageID);
1276// return NULL;
1277// }
1278//
1279// if (!insertMemoryBlockIntoPage(pageID, NULL, size, 0, memID))
1280// return NULL;
1281//
1282// return getSystemBlock(pageID, size);
1283//}
1284//
1285//
1287//char* MemoryManagerX::getSystemBlock(uint32 pageID, uint32& size) {
1288// char* data = NULL;
1289// // We assume manager already locked
1291// MemoryPage* page = getCachedPage(pageID);
1292// if (page == NULL)
1293// return NULL;
1294// MemoryBlock* block = (MemoryBlock*)MP_GetBlockDataStartLoc(page);
1295// if (block == NULL)
1296// return NULL;
1297// size = block->size - sizeof(MemoryBlock);
1298// return (char*)(block + sizeof(MemoryBlock));
1299//}
1300//
1301//
1302//
1303//
1305//char* MemoryManagerX::getAndLockSystemBlock(uint32 pageID, uint32& size) {
1306// // Lock Manager
1307// if (!pageMasterMutex->enter())
1308// return NULL;
1309// MemoryPageEntry* entry = (MemoryPageEntry*)MP_GetPageEntryLoc(pageMaster, pageID);
1310// if (!lockPage(entry)) {
1311// pageMasterMutex->leave();
1312// return NULL;
1313// }
1314//
1315// MemoryPage* page = getCachedPage(entry);
1316// if (page == NULL) {
1317// // Unlock Manager
1318// pageMasterMutex->leave();
1319// return NULL;
1320// }
1321// char* data = getLockedSystemBlock(page, size);
1322// pageMasterMutex->leave();
1323// return data;
1324//}
1325//
1326//char* MemoryManagerX::getLockedSystemBlock(uint32 pageID, uint32& size) {
1327// // Manager should be locked
1329// MemoryPage* page = getCachedPage(pageID);
1330// if (page == NULL)
1331// return NULL;
1332// return getLockedSystemBlock(page, size);
1333//}
1334//
1335//char* MemoryManagerX::getLockedSystemBlock(MemoryPage* page, uint32& size) {
1336// MemoryBlock* block = (MemoryBlock*)MP_GetBlockDataStartLoc(page);
1337// if (block == NULL)
1338// return NULL;
1339// size = block->size - sizeof(MemoryBlock);
1340// return (char*)(block + sizeof(MemoryBlock));
1341//}
1342//
1343//bool MemoryManagerX::unlockSystemBlock(uint32 pageID) {
1344// unlockPage(pageID);
1345// return true;
1346//}
1347//
1348//
1349//
1351//char* MemoryManagerX::createAndLockNewSystemPage(uint32 size, uint32& pageID) {
1352//
1353// // Lock Manager
1354// if (!pageMasterMutex->enter())
1355// return NULL;
1356// pageID = 0; // provide new id
1357// MemoryPage* page = createPage(size+sizeof(MemoryBlock), 1, 0, pageID);
1358// if (page == NULL) {
1359// pageMasterMutex->leave();
1360// return NULL;
1361// }
1362//
1363// // createPage now keeps the page locked
1364// //if (!lockPage(pageID)) {
1365// // pageMasterMutex->leave();
1366// // return NULL;
1367// //}
1368//
1369// uint64 memID; // not required for full page memory blocks, but required for function call
1370// if (!insertMemoryBlockIntoPage(pageID, NULL, size, 0, memID))
1371// return NULL;
1372//
1373// char* data = getLockedSystemBlock(pageID, size);
1374// // Unlock Manager
1375// pageMasterMutex->leave();
1376// return data;
1377//}
1378//
1380//char* MemoryManagerX::resizeSystemPage(uint32 pageID, uint32 newSize) {
1381//
1382// uint32 oldSize = 0;
1383// char* oldData = getAndLockSystemBlock(pageID, oldSize);
1384// if (oldData == NULL)
1385// return NULL;
1386//
1387// int32 difSize = newSize - oldSize;
1388// if (difSize <= 0) {
1389// // Unlock Manager
1390// pageMasterMutex->leave();
1391// return oldData;
1392// }
1393//
1394// char* tempData = new char[oldSize];
1395// memcpy(tempData, oldData, oldSize);
1396//
1397// UnlockSystemBlock(pageID);
1398// destroyPage(pageID);
1399//
1400// uint32 newPageID = pageID;
1401// char* newData = createAndLockNewSystemPage(newSize, newPageID);
1402// if (newData == NULL) {
1403// delete [] tempData;
1404// return NULL;
1405// }
1406//
1407// memcpy(newData, tempData, oldSize);
1408// delete [] tempData;
1409// return newData;
1410//}
1411//
1412//bool MemoryManagerX::InsertMemoryBlock(const char* data, uint32 size, uint64 eol, uint64& id) {
1413// if (!MemoryManagerX::Singleton)
1414// return 0;
1415// return MemoryManagerX::Singleton->insertMemoryBlock(data, size, eol, id);
1416//}
1417//
1418//bool MemoryManagerX::OverwriteMemoryBlock(uint64 id, const char* data, uint32 size, uint64 eol) {
1419// if (!MemoryManagerX::Singleton)
1420// return 0;
1421// return MemoryManagerX::Singleton->overwriteMemoryBlock(id, data, size, eol);
1422//}
1423//
1424//char* MemoryManagerX::GetAndLockMemoryBlock(uint64 id, uint32& size, uint64& eol) {
1425// if (!MemoryManagerX::Singleton)
1426// return 0;
1427// return MemoryManagerX::Singleton->getAndLockMemoryBlock(id, size, eol);
1428//}
1429//
1430//bool MemoryManagerX::UnlockMemoryBlock(uint64 id) {
1431// if (!MemoryManagerX::Singleton)
1432// return 0;
1433// return MemoryManagerX::Singleton->unlockMemoryBlock(id);
1434//}
1435//
1436//char* MemoryManagerX::GetCopyMemoryBlock(uint64 id, uint32& size, uint64& eol) {
1437// if (!MemoryManagerX::Singleton)
1438// return 0;
1439// return MemoryManagerX::Singleton->getCopyMemoryBlock(id, size, eol);
1440//}
1441//
1442//
1443//
1446//char* MemoryManagerX::GetAndLockSystemBlock(uint32 pageID, uint32& size) {
1447// if (!MemoryManagerX::Singleton)
1448// return 0;
1449// return MemoryManagerX::Singleton->getAndLockSystemBlock(pageID, size);
1450//}
1451//
1454//bool MemoryManagerX::UnlockSystemBlock(uint32 pageID) {
1455// if (!MemoryManagerX::Singleton)
1456// return 0;
1457// return MemoryManagerX::Singleton->unlockSystemBlock(pageID);
1458//}
1459//
1462//char* MemoryManagerX::CreateAndLockNewSystemPage(uint32 size, uint32& id) {
1463// if (!MemoryManagerX::Singleton)
1464// return 0;
1465// return MemoryManagerX::Singleton->createAndLockNewSystemPage(size, id);
1466//}
1467//
1470//char* MemoryManagerX::ResizeSystemPage(uint32 pageID, uint32 size) {
1471// if (!MemoryManagerX::Singleton)
1472// return 0;
1473// return MemoryManagerX::Singleton->resizeSystemPage(pageID, size);
1474//}
1475//
1478//bool MemoryManagerX::DestroySystemPage(uint32 pageID) {
1479// if (!MemoryManagerX::Singleton)
1480// return 0;
1481// return MemoryManagerX::Singleton->destroyPage(pageID);
1482//}
1483//
1484//
1486//bool MemoryManagerX::createSystemPages() {
1487//
1488// // Create main system page
1489// char* data;
1490// uint32 size = 1024*512; // ############# Need better size calc
1491// uint64 memID;
1492// // Create and initialise the System Page
1493// if ( (data = createSystemPage(ID_SYSPAGE, size, memID)) == NULL) {
1494// fprintf(stderr, "MemoryManager could not create the System page\n");
1495// return false;
1496// }
1497// initSystemPage(data, size);
1498// unlockSystemBlock(ID_SYSPAGE);
1499//
1500// // Create and initialise the Page Pool
1501// size = 1024*512; // ############# Need better size calc
1502// if ( (data = createSystemPage(ID_PAGEPOOL, size, memID)) == NULL) {
1503// fprintf(stderr, "MemoryManager could not create the Page Pool page\n");
1504// return false;
1505// }
1506// initPagePool(data, size);
1507// unlockSystemBlock(ID_PAGEPOOL);
1508//
1509// // Create and initialise the Queue Page
1510// size = 1024*512; // ############# Need better size calc
1511// if ( (data = createSystemPage(ID_QUEUEPAGE, size, memID)) == NULL) {
1512// fprintf(stderr, "MemoryManager could not create the Queue page\n");
1513// return false;
1514// }
1515// initQueuePage(data, size);
1516// unlockSystemBlock(ID_QUEUEPAGE);
1517//
1518// // Create and initialise the Component Map Page
1519// uint32 count = 0xFFFF;
1520// uint32 bitFieldSize = (uint32)ceil((double)count / 8);
1521// size = sizeof(ComponentMapHeader) + bitFieldSize + count*sizeof(ComponentMapEntry);
1522// if ( (data = createSystemPage(ID_COMPMAPPAGE, size, memID)) == NULL) {
1523// fprintf(stderr, "MemoryManager could not create the Component page\n");
1524// return false;
1525// }
1526// ComponentMapHeader* cmHeader = (ComponentMapHeader*)data;
1527// cmHeader->size = size;
1528// cmHeader->bitFieldSize = bitFieldSize;
1529// cmHeader->count = count;
1530// memset(data+sizeof(ComponentMapHeader), 255, bitFieldSize);
1531// memset(data+sizeof(ComponentMapHeader)+bitFieldSize, 0, size-sizeof(ComponentMapHeader)-bitFieldSize);
1532// // Position 0 is not allowed, used to indicate error or unused
1533// utils::SetBit(0, BITOCCUPIED, (uint32*)((char*)cmHeader + sizeof(ComponentMapHeader)), cmHeader->bitFieldSize);
1534// unlockSystemBlock(ID_COMPMAPPAGE);
1535//
1536// // Create and initialise the Type Map Page
1537// count = 0xFFFF;
1538// bitFieldSize = (uint32)ceil((double)count / 8);
1539// size = sizeof(TypeMapHeader) + bitFieldSize + count*sizeof(TypeMapEntry);
1540// if ( (data = createSystemPage(ID_TYPEMAPPAGE, size, memID)) == NULL) {
1541// fprintf(stderr, "MemoryManager could not create the TypeMap page\n");
1542// return false;
1543// }
1544// TypeMapHeader* typeHeader = (TypeMapHeader*)data;
1545// typeHeader->size = size;
1546// typeHeader->bitFieldSize = bitFieldSize;
1547// typeHeader->count = count;
1548// memset((char*)typeHeader+sizeof(TypeMapHeader), 255, bitFieldSize);
1549// memset((char*)typeHeader+sizeof(TypeMapHeader)+bitFieldSize, 0, size-sizeof(TypeMapHeader)-bitFieldSize);
1550// // Position 0 is not allowed, used to indicate error or unused
1551// utils::SetBit(0, BITOCCUPIED, (uint32*)((char*)typeHeader + sizeof(TypeMapHeader)), typeHeader->bitFieldSize);
1552// unlockSystemBlock(ID_TYPEMAPPAGE);
1553//
1554// // Create and initialise the Context Map Page
1555// count = 0xFFFF;
1556// bitFieldSize = (uint32)ceil((double)count / 8);
1557// size = sizeof(ContextMapHeader) + bitFieldSize + count*sizeof(ContextMapEntry);
1558// if ( (data = createSystemPage(ID_CONTEXTMAPPAGE, size, memID)) == NULL) {
1559// fprintf(stderr, "MemoryManager could not create the ContextMap page\n");
1560// return false;
1561// }
1562// ContextMapHeader* contextHeader = (ContextMapHeader*)data;
1563// contextHeader->size = size;
1564// contextHeader->bitFieldSize = bitFieldSize;
1565// contextHeader->count = count;
1566// memset((char*)contextHeader+sizeof(ContextMapHeader), 255, bitFieldSize);
1567// memset((char*)contextHeader+sizeof(ContextMapHeader)+bitFieldSize, 0, size-sizeof(ContextMapHeader)-bitFieldSize);
1568// // Position 0 is not allowed, used to indicate error or unused
1569// utils::SetBit(0, BITOCCUPIED, (uint32*)((char*)contextHeader + sizeof(ContextMapHeader)), contextHeader->bitFieldSize);
1570// unlockSystemBlock(ID_CONTEXTMAPPAGE);
1571//
1572// //// Create and initialise the Tag Map Page
1573// //count = 4096;
1574// //bitFieldSize = (uint32)ceil((double)count / 8);
1575// //size = sizeof(TagMapHeader) + bitFieldSize + count*sizeof(TagMapEntry);
1576// //if ( (data = createSystemPage(ID_TAGMAPPAGE, size, memID)) == NULL) {
1577// // fprintf(stderr, "MemoryManager could not create the TagMap page\n");
1578// // return false;
1579// //}
1580// //TagMapHeader* tagHeader = (TagMapHeader*)data;
1581// //tagHeader->size = size;
1582// //tagHeader->bitFieldSize = bitFieldSize;
1583// //tagHeader->count = count;
1584// //memset((char*)tagHeader+sizeof(TagMapHeader), 255, bitFieldSize);
1585// //memset((char*)tagHeader+sizeof(TagMapHeader)+bitFieldSize, 0, size-sizeof(TagMapHeader)-bitFieldSize);
1586// //// Position 0 is not allowed, used to indicate error or unused
1587// //utils::SetBit(0, BITOCCUPIED, (uint32*)((char*)tagHeader + sizeof(TagMapHeader)), tagHeader->bitFieldSize);
1588// //unlockSystemBlock(ID_TAGMAPPAGE);
1589//
1590// //// Create and initialise the Node Map Page
1591// //count = 4096;
1592// //bitFieldSize = (uint32)ceil((double)count / 8);
1593// //size = sizeof(NodeMapHeader) + bitFieldSize + count*sizeof(NodeMapEntry);
1594// //if ( (data = createSystemPage(ID_NODEMAPPAGE, size, memID)) == NULL) {
1595// // fprintf(stderr, "MemoryManager could not create the NodeMap page\n");
1596// // return false;
1597// //}
1598// //NodeMapHeader* nodeHeader = (NodeMapHeader*)data;
1599// //nodeHeader->size = size;
1600// //nodeHeader->bitFieldSize = bitFieldSize;
1601// //nodeHeader->count = count;
1602// //memset((char*)nodeHeader+sizeof(NodeMapHeader), 255, bitFieldSize);
1603// //memset((char*)nodeHeader+sizeof(NodeMapHeader)+bitFieldSize, 0, size-sizeof(NodeMapHeader)-bitFieldSize);
1604// //// Position 0 is not allowed, used to indicate error or unused
1605// //utils::SetBit(0, BITOCCUPIED, (uint32*)((char*)nodeHeader + sizeof(NodeMapHeader)), nodeHeader->bitFieldSize);
1606// //unlockSystemBlock(ID_NODEMAPPAGE);
1607//
1608// // Create and initialise the Crank Map Page
1609// count = 0xFFFF;
1610// bitFieldSize = (uint32)ceil((double)count / 8);
1611// size = sizeof(CrankMapHeader) + bitFieldSize + count*sizeof(CrankMapEntry);
1612// if ( (data = createSystemPage(ID_CRANKMAPPAGE, size, memID)) == NULL) {
1613// fprintf(stderr, "MemoryManager could not create the CrankMap page\n");
1614// return false;
1615// }
1616// CrankMapHeader* crankHeader = (CrankMapHeader*)data;
1617// crankHeader->size = size;
1618// crankHeader->bitFieldSize = bitFieldSize;
1619// crankHeader->count = count;
1620// memset((char*)crankHeader+sizeof(CrankMapHeader), 255, bitFieldSize);
1621// memset((char*)crankHeader+sizeof(CrankMapHeader)+bitFieldSize, 0, size-sizeof(CrankMapHeader)-bitFieldSize);
1622// // Position 0 is not allowed, used to indicate error or unused
1623// utils::SetBit(0, BITOCCUPIED, (uint32*)((char*)crankHeader + sizeof(CrankMapHeader)), crankHeader->bitFieldSize);
1624// unlockSystemBlock(ID_CRANKMAPPAGE);
1625//
1626// // Create and initialise the Queue Map Page
1627// count = 0xFFFF;
1628// bitFieldSize = (uint32)ceil((double)count / 8);
1629// size = sizeof(QueueMapHeader) + bitFieldSize + count*sizeof(QueueMapEntry);
1630// if ( (data = createSystemPage(ID_QUEUEMAPPAGE, size, memID)) == NULL) {
1631// fprintf(stderr, "MemoryManager could not create the QueueMap page\n");
1632// return false;
1633// }
1634// QueueMapHeader* queueHeader = (QueueMapHeader*)data;
1635// queueHeader->size = size;
1636// queueHeader->bitFieldSize = bitFieldSize;
1637// queueHeader->count = count;
1638// memset((char*)queueHeader+sizeof(QueueMapHeader), 255, bitFieldSize);
1639// memset((char*)queueHeader+sizeof(QueueMapHeader)+bitFieldSize, 0, size-sizeof(QueueMapHeader)-bitFieldSize);
1640// // Position 0 is not allowed, used to indicate error or unused
1641// utils::SetBit(0, BITOCCUPIED, (uint32*)((char*)queueHeader + sizeof(QueueMapHeader)), queueHeader->bitFieldSize);
1642// unlockSystemBlock(ID_QUEUEMAPPAGE);
1643//
1644// // Create and initialise the Process Map Page
1645// count = 256;
1646// bitFieldSize = (uint32)ceil((double)count / 8);
1647// size = sizeof(ProcessMapHeader) + bitFieldSize + count*sizeof(ProcessMapEntry);
1648// if ( (data = createSystemPage(ID_PROCESSMAPPAGE, size, memID)) == NULL) {
1649// fprintf(stderr, "MemoryManager could not create the ProcessMap page\n");
1650// return false;
1651// }
1652// ProcessMapHeader* processHeader = (ProcessMapHeader*)data;
1653// processHeader->size = size;
1654// processHeader->bitFieldSize = bitFieldSize;
1655// processHeader->count = count;
1656// memset((char*)processHeader+sizeof(ProcessMapHeader), 0, size-sizeof(ProcessMapHeader));
1657// memset((char*)processHeader+sizeof(ProcessMapHeader), 255, bitFieldSize);
1658// // Position 0 is not allowed, used to indicate error or unused
1659// utils::SetBit(0, BITOCCUPIED, (uint32*)((char*)processHeader + sizeof(ProcessMapHeader)), processHeader->bitFieldSize);
1660// unlockSystemBlock(ID_PROCESSMAPPAGE);
1661//
1662// // Create and initialise the Request Map Page
1663// count = 256;
1664// bitFieldSize = (uint32)ceil((double)count / 8);
1665// size = sizeof(RequestMapHeader) + bitFieldSize + count*sizeof(RequestMapEntry);
1666// if ( (data = createSystemPage(ID_REQUESTMAPPAGE, size, memID)) == NULL) {
1667// fprintf(stderr, "MemoryManager could not create the RequestMap page\n");
1668// return false;
1669// }
1670// RequestMapHeader* requestHeader = (RequestMapHeader*)data;
1671// requestHeader->size = size;
1672// requestHeader->bitFieldSize = bitFieldSize;
1673// requestHeader->count = count;
1674// memset((char*)requestHeader+sizeof(RequestMapHeader), 0, size-sizeof(RequestMapHeader));
1675// memset((char*)requestHeader+sizeof(RequestMapHeader), 255, bitFieldSize);
1676// // Position 0 is not allowed, used to indicate error or unused
1677// utils::SetBit(0, BITOCCUPIED, (uint32*)((char*)requestHeader + sizeof(RequestMapHeader)), requestHeader->bitFieldSize);
1678// unlockSystemBlock(ID_REQUESTMAPPAGE);
1679//
1680// uint16 pid;
1681// if ( (!MemoryMaps::CreateNewProcess("Node Process", pid)) || (pid != NODE_PROCESS_ID) ) {
1682// fprintf(stderr, "MemoryManager could not register own process (%u != %u)\n", pid, NODE_PROCESS_ID);
1683// return false;
1684// }
1685//
1686// return true;
1687//}
1688//
1690//bool MemoryManagerX::insertMemoryBlock(const char* data, uint32 size, uint64 eol, uint64& id) {
1692// // Lock Manager
1693// if (!pageMasterMutex->enter())
1694// return false;
1695// uint32 pageID = 0;
1696// // First find an appropriate page
1697// MemoryPage* page = findPageForBlock(size, eol, pageID);
1698// if (page == NULL) {
1699// // Create a new page
1700// uint16 blockTableSize = CalcBlockTableSize(size);
1701// if (blockTableSize == 0) {
1702// pageMasterMutex->leave();
1703// return false;
1704// }
1705// page = createPage((size+sizeof(MemoryBlock))*blockTableSize, blockTableSize, eol, pageID);
1706// if (page == NULL) {
1707// pageMasterMutex->leave();
1708// return false;
1709// }
1710// unlockPage(pageID);
1711// }
1712// // printf(">>>>>> Inserting block into page ID %u...\n", pageID);
1713// if (!insertMemoryBlockIntoPage(pageID, data, size, eol, id)) {
1714// pageMasterMutex->leave();
1715// return false;
1716// }
1717// pageMasterMutex->leave();
1720// return true;
1721//}
1722//
1724//bool MemoryManagerX::insertMemoryBlockIntoPage(uint32 pageID, const char* data, uint32 size, uint64 eol, uint64& id) {
1725// // Assume page and Manager locked
1727// MemoryPage* page = getCachedPage(pageID);
1728// if (page == NULL)
1729// return false;
1730// pageMasterMutex->leave();
1731//
1732// // printf("PageID %u EOL %lu {%p}...\n", pageID, page->eol, page);
1733//
1734// uint32 totalSize = sizeof(MemoryBlock) + size;
1735//
1736// // Now we have a page, check for room
1737// if (page->count >= page->blockTableSize) {
1738// return false;
1739// }
1740// if ( (int64)page->dataSize - (int64)page->dataUsage < (int64)totalSize ) {
1741// return false;
1742// }
1743// // Find location of first available byte
1744// MemoryBlock* newBlock, *lastBlock;
1745// uint32 offset;
1746// uint16 blockID;
1747// uint32* offsetTable = (uint32*)MP_GetBlockIndexStartLoc(page);
1748// MemoryBlock* dataTable = (MemoryBlock*)MP_GetBlockDataStartLoc(page);
1749// if (page->count == 0) {
1750// newBlock = dataTable;
1751// blockID = 0;
1752// offset = 0;
1753// }
1754// else {
1755// lastBlock = (MemoryBlock*) ( (char*)dataTable + offsetTable[page->count-1] );
1756// // insert memory block
1757// newBlock = (MemoryBlock*) ( (char*)lastBlock + lastBlock->size );
1758// blockID = page->count;
1759// //offsetLoc = MP_GetBlockOffsetLoc(page, page->count-1);
1760// //offsetLoc = (uint32*)MP_GetBlockIndexStartLoc(page) + ((page->count-1) * sizeof(uint32));
1761// offset = (uint32) ((char*)newBlock - (char*)dataTable);
1762// }
1763// newBlock->size = totalSize;
1764// if (data != NULL)
1765// memcpy((char*)newBlock + sizeof(MemoryBlock), data, size);
1766// else
1767// memset((char*)newBlock + sizeof(MemoryBlock), 0, size);
1768// page->count++;
1769// page->dataUsage += newBlock->size;
1770// offsetTable[page->count-1] = offset;
1771// // Lock Manager
1772// if (!pageMasterMutex->enter())
1773// return false;
1774// pageMaster->dataUsage[MP_GetPageType(pageID, eol)] += newBlock->size;
1775// MemoryID* mid = (MemoryID*) &id;
1776// mid->blockID = blockID;
1777// mid->sysID = pageMaster->sysID;
1778// mid->pageID = pageID;
1781// // Leave Manager locked
1782// return true;
1783//}
1784//
1785//char* MemoryManagerX::getAndLockMemoryBlock(uint64 id, uint32& size, uint64& eol) {
1786// // Lock Manager
1787// if (!pageMasterMutex->enter())
1788// return NULL;
1789// uint32 pageID = MP_GetPageID(id);
1790// //printf(">>>>>> Getting block from page ID %u...\n", pageID);
1791//
1792// MemoryPageEntry* entry = (MemoryPageEntry*)MP_GetPageEntryLoc(pageMaster, pageID);
1793// if (!lockPage(entry)) {
1794// pageMasterMutex->leave();
1795// return NULL;
1796// }
1797//
1798// MemoryPage* page = getCachedPage(entry);
1799// if (page == NULL) {
1800// pageMasterMutex->leave();
1801// return NULL;
1802// }
1803// // printf("PageID %u EOL %lu {%p}...\n", pageID, entry->page->eol, entry->page);
1804// pageMasterMutex->leave();
1805// return getLockedMemoryBlock(page, id, size, eol);
1806//}
1807//
1808//char* MemoryManagerX::getLockedMemoryBlock(MemoryPage* page, uint64 id, uint32& size, uint64& eol) {
1809// char* data = NULL;
1810// uint32* offsetTable = (uint32*)MP_GetBlockIndexStartLoc(page);
1811// MemoryBlock* dataTable = (MemoryBlock*)MP_GetBlockDataStartLoc(page);
1812//
1813// uint16 blockID = MP_GetBlockID(id);
1814// MemoryBlock* block = (MemoryBlock*) ( (char*)dataTable + offsetTable[blockID] );
1815// if (block == NULL) {
1816// // Unlock page
1817// unlockPage(MP_GetPageID(id));
1818// return NULL;
1819// }
1820// size = block->size - sizeof(MemoryBlock);
1821// eol = page->eol;
1822// return ((char*)block + sizeof(MemoryBlock));
1823//}
1824//
1825//bool MemoryManagerX::unlockMemoryBlock(uint64 id) {
1826// uint32 pageID = MP_GetPageID(id);
1827// unlockPage(pageID);
1828// return true;
1829//}
1830//
1831//char* MemoryManagerX::getCopyMemoryBlock(uint64 id, uint32& size, uint64& eol) {
1832// char* data = getAndLockMemoryBlock(id, size, eol);
1833// if (data == NULL)
1834// return false;
1835// char* output = new char[size];
1836// memcpy(output, data, size);
1837// unlockMemoryBlock(id);
1838// return output;
1839//}
1840//
1842//bool MemoryManagerX::overwriteMemoryBlock(uint64 id, const char* data, uint32 size, uint64 eol) {
1843// uint32 existingSize;
1844// uint64 existingEOL;
1845// char* existingData = getAndLockMemoryBlock(id, existingSize, existingEOL);
1846// if ((existingData == NULL) || (existingSize != size) || (existingEOL != eol) )
1847// return false;
1848// memcpy(existingData, data, size);
1849// unlockMemoryBlock(id);
1850// return true;
1851//}
1852//
1854//MemoryPage* MemoryManagerX::createPage(uint32 size, uint16 tableSize, uint64 eol, uint32& pageID) {
1856// // Lock Manager
1857// if (!pageMasterMutex->enter())
1858// return NULL;
1859//
1860// // First calculate total size
1861// uint32 pageSize = sizeof(MemoryPage) + (tableSize*sizeof(uint32)) + size;
1862//
1863// MemoryPageEntry* entry = NULL;
1864// // Now check if caller is requesting a particular id
1865// if (pageID > 0) {
1866// entry = (MemoryPageEntry*)MP_GetPageEntryLoc(pageMaster, pageID);
1867// if ((entry == NULL) || (entry->pageSize != 0))
1868// return NULL;
1869// }
1870// else {
1871// // Get a page from the pool with the right data size
1872// if (getPageFromPool(size, pageID)) {
1873// //printf("CreateFromPool %u...\n", pageID);
1874// // We have a valid page from the pool
1875// }
1876// // Find first available Page Entry
1877// else if (!utils::GetFirstFreeBitLoc((uint32*)MP_GetBitFieldLoc(pageMaster), pageMaster->pageTableSize, pageID)) {
1878// pageMasterMutex->leave();
1879// return NULL;
1880// }
1881// }
1882//
1883// if (pageID >= pageMaster->pageTableSize) {
1884// // ############## should resize pagetable ##############
1885// LogPrint(0,0,0,"Page Table needs resizing!");
1886// pageMasterMutex->leave();
1887// return NULL;
1888// }
1889//
1890// entry = (MemoryPageEntry*)MP_GetPageEntryLoc(pageMaster, pageID);
1891// if (entry->pageSize == 0)
1892// entry->pageID = pageID;
1893// if (!lockPage(entry)) {
1894// pageMasterMutex->leave();
1895// return NULL;
1896// }
1897//
1898// MemoryPage* page = NULL;
1899// // If the page already exists, use it
1900// // if not, create it
1901// if (entry->pageSize == 0) {
1902// char* pageName = new char[MAXKEYNAMELEN];
1903// sprintf(pageName, "Page_%u", pageID);
1904// // Allocate from shared memory
1905// page = (MemoryPage*) utils::CreateSharedMemorySegment(pageName, pageSize);
1906// delete [] pageName;
1907// if (page == NULL) {
1908// unlockPage(entry);
1909// pageMasterMutex->leave();
1910// return NULL;
1911// }
1912// entry->cacheSerial = 1;
1913// page->blockTableSize = tableSize;
1914// page->size = pageSize;
1915// page->dataSize = size;
1916// entry->pageSize = pageSize;
1917// // entry->pageID = pageID;
1918// page->eol = 0;
1919// // printf("CreateFromNew %u EOL %lu...\n", pageID, entry->page->eol);
1920// }
1921// else {
1922// page = getCachedPage(entry);
1923// if (page == NULL) {
1924// unlockPage(entry);
1925// pageMasterMutex->leave();
1926// return NULL;
1927// }
1928// }
1929//
1930// utils::SetBit(pageID, BITOCCUPIED, (uint32*)MP_GetBitFieldLoc(pageMaster), pageMaster->bitFieldSize);
1931// if (eol == 0)
1932// pageMaster->lastCreatedStaticPage = pageID;
1933// else
1934// insertPageIntoEOL(pageID, eol, page->eol);
1935//
1936// // Initialise page
1937// page->count = 0;
1938// page->dataUsage = 0;
1940// memset((void*)MP_GetBlockIndexStartLoc(page), 0, (tableSize*sizeof(uint32)));
1941//
1942// entry->pageSerial++;
1943// pageMaster->count[MP_GetPageType(pageID, eol)]++;
1944// pageMaster->pagesSize += page->size;
1945// pageMaster->dataSize[MP_GetPageType(pageID, eol)] += page->dataSize;
1946//
1947// updateCachedPage(entry, page);
1948//
1949// // Unlock page mutex
1951// // Unlock Manager
1952// pageMasterMutex->leave();
1955// return page;
1956//}
1957//
1959//bool MemoryManagerX::freePageIntoPool(uint32 pageID) {
1960// uint32 dataSize = 0;
1961// if (!removePageFromStats(pageID, dataSize))
1962// return false;
1963// if (!insertPageIntoPool(pageID, dataSize))
1964// return false;
1965// return true;
1966//}
1967//
1969//bool MemoryManagerX::removePageFromStats(uint32 pageID, uint32& dataSize) {
1970// // Lock Manager
1971// if (!pageMasterMutex->enter())
1972// return false;
1973// MemoryPageEntry* entry = (MemoryPageEntry*) MP_GetPageEntryLoc(pageMaster, pageID);
1974// // Lock page
1975// if (!lockPage(entry)) {
1976// pageMasterMutex->leave();
1977// return false;
1978// }
1979//
1980// MemoryPage* page = getCachedPage(entry);
1981// if (page == NULL) {
1982// pageMasterMutex->leave();
1983// return true;
1984// }
1985//
1987//
1988// dataSize = page->dataSize;
1989// pageMaster->count[MP_GetPageType(pageID, page->eol)]--;
1990// pageMaster->dataSize[MP_GetPageType(pageID, page->eol)] -= page->dataSize;
1991// pageMaster->dataUsage[MP_GetPageType(pageID, page->eol)] -= page->dataUsage;
1992// pageMaster->pagesSize -= page->size;
1993// // Do not destroy shared memory segment at entry->page
1994// // and leave page link in there
1995// // entry->page = NULL;
1996// // Unlock page
1997// unlockPage(entry);
1998// // destroyPageMutex(pageID);
1999// // Page location remains in use
2000// // utils::SetBit(pageID, BITFREE, (uint32*)MP_GetBitFieldLoc(pageMaster), pageMaster->bitFieldSize);
2001// // Unlock Manager
2002// pageMasterMutex->leave();
2003// return true;
2004//}
2005//
2007//bool MemoryManagerX::insertPageIntoPool(uint32 pageID, uint32 dataSize) {
2008// uint32 sbSize = 0;
2009// PagePoolHeader* header = (PagePoolHeader*) getSystemBlock(ID_PAGEPOOL, sbSize);
2010// // Find empty spot
2011// PagePoolEntry* entry = (PagePoolEntry*) ((char*)header + sizeof(PagePoolHeader));
2012// while ((char*)entry < (char*)header + header->size) {
2013// if (entry->dataSize == 0) {
2014// //printf("Freeing to pool page id %d\n", pageID);
2015// //fflush(stdout);
2016// entry->dataSize = dataSize;
2017// entry->time = GetTimeNow();
2018// entry->pageID = pageID;
2019// return true;
2020// }
2021// else
2022// entry += 1;
2023// //entry += sizeof(PagePoolEntry);
2024// }
2025//
2026// // no free entry was found, remove the oldest one, then...
2027// entry = (PagePoolEntry*) ((char*)header + sizeof(PagePoolHeader));
2028// //printf("No free Pool Entries available for id %d, destroying id %d first\n", pageID, entry->pageID);
2029// //fflush(stdout);
2030// // Delete actual page
2031// destroyPage(entry->pageID, false);
2032// // Put in new one
2033// entry->dataSize = dataSize;
2034// entry->time = GetTimeNow();
2035// entry->pageID = pageID;
2036// return true;
2037//}
2038//
2040//bool MemoryManagerX::getPageFromPool(uint32 size, uint32& pageID) {
2041// uint32 sbSize = 0;
2042// PagePoolHeader* header = (PagePoolHeader*) getSystemBlock(ID_PAGEPOOL, sbSize);
2043// if (header == NULL)
2044// return false;
2045// // Find empty spot
2046// PagePoolEntry* entry = (PagePoolEntry*) ((char*)header + sizeof(PagePoolHeader));
2047// while ((char*)entry < (char*)header + header->size) {
2048// if (entry->dataSize >= size) {
2049// pageID = entry->pageID;
2050// //printf("Got from pool page id %d\n", pageID);
2051// //fflush(stdout);
2052// // Remove from pool
2053// memset(entry, 0, sizeof(PagePoolEntry));
2054// return true;
2055// }
2056// else
2057// entry += 1;
2058// //entry += sizeof(PagePoolEntry);
2059// }
2060// return false;
2061//}
2062//
2064//bool MemoryManagerX::destroyAllPages() {
2065// // Lock Manager
2066// if (!pageMasterMutex->enter())
2067// return false;
2068// if (pageMaster == NULL) {
2069// pageMasterMutex->leave();
2070// return true;
2071// }
2072//
2073// // MemoryPageEntry* entry = (MemoryPageEntry*) MP_GetPageTableLoc(pageMaster);
2074// for (uint32 n=0; n<pageMaster->pageTableSize; n++)
2075// destroyPage(n);
2076// // Unlock Manager
2077// pageMasterMutex->leave();
2078// return true;
2079//}
2080//
2082//bool MemoryManagerX::destroyPage(uint32 pageID, bool updateStats) {
2083// // Lock Manager
2084// if (!pageMasterMutex->enter())
2085// return false;
2086// MemoryPageEntry* entry = (MemoryPageEntry*) MP_GetPageEntryLoc(pageMaster, pageID);
2087// // Lock page
2088// if (!lockPage(entry)) {
2089// pageMasterMutex->leave();
2090// return false;
2091// }
2092//
2093// MemoryPage* page = getCachedPage(entry);
2094// if (page == NULL) {
2095// pageMasterMutex->leave();
2096// return true;
2097// }
2098//
2099// if (updateStats) {
2100// pageMaster->count[MP_GetPageType(pageID, page->eol)]--;
2101// pageMaster->dataSize[MP_GetPageType(pageID, page->eol)] -= page->dataSize;
2102// pageMaster->dataUsage[MP_GetPageType(pageID, page->eol)] -= page->dataUsage;
2103// pageMaster->pagesSize -= page->size;
2104// }
2105// // Destroy shared memory segment at entry->page
2106// //printf("Closing cached page %d...\n", pageID);
2107// //fflush(stdout);
2108// utils::DestroySharedMemorySegment((char*)(page), page->size);
2109// page = NULL;
2110// entry->cacheSerial = 0;
2111// entry->pageSize = 0;
2112// updateCachedPage(entry, NULL);
2113// // Unlock page
2114// unlockPage(entry);
2115// utils::SetBit(pageID, BITFREE, (uint32*)MP_GetBitFieldLoc(pageMaster), pageMaster->bitFieldSize);
2116// // Unlock Manager
2117// pageMasterMutex->leave();
2118// return true;
2119//}
2120//
2127//
2134//
2141//
2150//
2158//
2159//bool MemoryManagerX::lockPage(uint32 pageID) {
2160// if (!utils::EnterMutex(pageID, 5000)) {
2161// LogPrint(0,0,0,"Mutex lock timeout for memory page %u", pageID);
2162// return false;
2163// }
2164// return true;
2165//
2167//}
2168//
2169//bool MemoryManagerX::unlockPage(uint32 pageID) {
2170// return utils::LeaveMutex(pageID);
2172//}
2173//
2176//
2179//
2180//bool MemoryManagerX::lockPage(MemoryPageEntry* entry) {
2181// // Assume that pageMasterMutex is locked
2182// if (entry == NULL)
2183// return false;
2184//
2185// if (!utils::EnterMutex(entry->pageID, 5000)) {
2186// LogPrint(0,0,0,"Mutex lock timeout for memory page %u", entry->pageID);
2187// return false;
2188// }
2189// return true;
2190//
2191// //uint64 t1, t2;
2192// //uint32 myID = 0;
2193// //if (!utils::GetCurrentThreadOSID(myID) || !myID)
2194// // return false;
2195//
2196// //// wait until it reaches 0
2197// //utils::Semaphore* sem;
2198// //while ( (entry->lockCount > 0) && (entry->lockID != myID) ) {
2199// //// printf("[%u] Waiting for page %u locked by %u\n", myID, entry->pageID, entry->lockID);
2200// // // if we are waiting the page semaphore exists
2201// // if (!(sem = getPageSemaphore(entry->pageID)))
2202// // return false;
2203// // pageMasterMutex->leave();
2204// // t1 = GetTimeNow();
2205// // if (!sem->wait(1000)) {
2206// // t2 = GetTimeNow();
2207// // delete(sem);
2208// // return false;
2209// // }
2210// // else
2211// // delete(sem);
2212// // if (!pageMasterMutex->enter())
2213// // return false;
2214// //}
2215//
2216// ////if (entry->lockCount)
2217// //// printf("[%u] Locked page %u AGAIN: %u\n", myID, entry->pageID, entry->lockCount);
2218// ////else
2219// //// printf("[%u] Locked page %u\n", myID, entry->pageID);
2220//
2221// //entry->lockCount++;
2222// //entry->lockTime = GetTimeNow();
2223// //entry->lockID = myID;
2224// //return true;
2225//}
2226//
2227//bool MemoryManagerX::unlockPage(MemoryPageEntry* entry) {
2228// if (entry == NULL)
2229// return false;
2230//
2231// return utils::LeaveMutex(entry->pageID);
2232//
2259//}
2260//
2261//
2262//
2264//MemoryPage* MemoryManagerX::findPageForBlock(uint32 size, uint64 eol, uint32& id) {
2265// MemoryPage* page = NULL;
2266// if (eol > 0) {
2267// // search only in eol pages
2268// uint32 sbSize = 0;
2269// EOLHeader* header = (EOLHeader*) getSystemBlock(ID_EOLPAGE, sbSize);
2270// if (header == NULL)
2271// return NULL;
2272//
2273// EOLEntry* entry = NULL;
2274// // Find the appropriate slot
2275// uint64 now = GetTimeNow();
2276// uint64 difTime = 0;
2277// if (eol - now > 0)
2278// difTime = eol - header->startTime;
2279// uint32 difSlot = (uint32)(difTime / header->slotDuration);
2280// // If too far in the future, choose end slot - buffer slot
2281// if (difSlot >= (header->slotCount - header->bufferSlots))
2282// difSlot = header->slotCount - 1 - header->bufferSlots;
2283// // Find actual slot...
2284// uint32 actualSlot = header->startSlot + difSlot;
2285// if (actualSlot >= header->slotCount)
2286// actualSlot -= header->slotCount;
2287// entry = (EOLEntry*)((char*)header + sizeof(EOLHeader) +
2288// (actualSlot * header->pagesPerSlot * sizeof(EOLEntry)));
2289// char* endEntry = (char*) entry + header->pagesPerSlot*sizeof(EOLEntry);
2290// while ((char*) entry <= endEntry) {
2291// if (entry->eol > 0) {
2292// // page = MP_GetPageLoc(pageMaster, entry->pageID);
2293// page = getCachedPage(entry->pageID);
2294// if ((page != NULL) && ( (int64)page->dataSize - (int64)page->dataUsage >= (int64)(size+sizeof(MemoryBlock)) ) ) {
2295// id = entry->pageID;
2296// return page;
2297// }
2298// }
2299// entry += 1;
2300// //entry += sizeof(EOLEntry);
2301// }
2302// }
2303// else {
2304// // search in non-eol pages
2305// // First check the last created page
2306// //page = MP_GetPageLoc(pageMaster, pageMaster->lastCreatedStaticPage);
2307// page = getCachedPage(pageMaster->lastCreatedStaticPage);
2308// if ((page != NULL) && ( (int64)page->dataSize - (int64)page->dataUsage >= (int64)(size+sizeof(MemoryBlock)) ) ) {
2309// id = pageMaster->lastCreatedStaticPage;
2310// return page;
2311// }
2312// // Since we don't (yet) support deletion of memory within static pages,
2313// // there is no need to look further
2314// }
2315//
2316// return NULL;
2317//}
2318//
2319//
2321//uint16 MemoryManagerX::CalcBlockTableSize(uint32 size) {
2322// if (size >= 10*1024*1024) // 10 MB
2323// return 10;
2324// else if (size >= 1024*1024) // 1 MB
2325// return 100;
2326// else if (size >= 256*1024) // 256 kB
2327// return 512;
2328// else if (size >= 16*1024) // 16 kB
2329// return 1024;
2330// else
2331// return 4096;
2332//
2333//}
2334//
2336//char* MemoryManagerX::getBitFieldAsString(uint32& size) {
2337// size = this->pageMaster->bitFieldSize * 16;
2338// char* str = new char[size];
2339//
2340// char* src = (char*)MP_GetBitFieldLoc(pageMaster);
2341// uint32 bfsize = pageMaster->bitFieldSize;
2342//
2343// uint32 n=0, p=0,i,j;
2344// for(i=0;i<bfsize;i++) {
2345// for(j=0;j<8;j++) {
2346// str[n++] = (src[i] & (1<<j)) ? '_' : '0' + (uint8)(getPageUsage(p)*10);
2347// if (++p >= pageMaster->pageTableSize)
2348// break;
2349// }
2350// str[n++] = ' ';
2351// };
2352// str[n] = 0;
2353// return str;
2354//}
2355//
2357//bool MemoryManagerX::printBitFieldAsString(char* title) {
2358// uint32 size = 0;
2359// char* str = getBitFieldAsString(size);
2360// if (str == NULL)
2361// return false;
2362// if (size < 73) {
2363// if (title != NULL)
2364// printf("%s [%u]: %s\n", title, pageMaster->pageTableSize, str);
2365// else
2366// printf("%s\n", str);
2367// }
2368// else {
2369// if (title != NULL)
2370// printf("%s [%u]:\n", title, pageMaster->pageTableSize);
2371// uint32 loc = 35;
2372// while (loc < size-1) {
2373// str[loc] = '\n';
2374// loc += 36;
2375// }
2376// printf("%s\n", str);
2377// }
2378// delete [] str;
2379// return true;
2380//}
2381//
2383//bool MemoryManagerX::getPageUsage(uint32 pageID, double& val) {
2385// MemoryPage* page = getCachedPage(pageID);
2386// if (page == NULL)
2387// return false;
2388// val = ((double)page->dataUsage)/page->dataSize;
2389// return true;
2390//}
2391//
2393//double MemoryManagerX::getPageUsage(uint32 pageID) {
2395// MemoryPage* page = getCachedPage(pageID);
2396// if (page == NULL)
2397// return 0;
2398// return ((double)page->dataUsage)/page->dataSize;
2399//}
2400//
2402//bool MemoryManagerX::getPageFree(uint32 pageID, uint32& bytes) {
2404// MemoryPage* page = getCachedPage(pageID);
2405// if (page == NULL)
2406// return false;
2407// bytes = page->dataSize - page->dataUsage;
2408// return true;
2409//}
2410//
2412//bool MemoryManagerX::getPageSize(uint32 pageID, uint32& bytes) {
2414// MemoryPage* page = getCachedPage(pageID);
2415// if (page == NULL)
2416// return false;
2417// bytes = page->dataSize;
2418// return true;
2419//}
2420//
2422//bool MemoryManagerX::initSystemPage(char* data, uint32 size) {
2423// memset(data, 0, size);
2424// return true;
2425//}
2426//
2428//bool MemoryManagerX::initPagePool(char* data, uint32 size) {
2429// PagePoolHeader* header = (PagePoolHeader*) data;
2430// header->size = size;
2431// memset(data+sizeof(PagePoolHeader), 0, size-sizeof(PagePoolHeader));
2432// return true;
2433//}
2434//
2436//bool MemoryManagerX::resizeEOLPage(uint32 slotCount, uint32 pagesPerSlot, uint32 slotDuration, uint32 bufferSlots) {
2437//
2438// if ( (slotCount < 5) || (pagesPerSlot < 5) || (slotDuration < 100000) || (bufferSlots < 1) )
2439// return false;
2440//
2441// uint32 oldSize = 0, newSize = (slotCount+bufferSlots)*pagesPerSlot*sizeof(EOLEntry) + sizeof(EOLHeader);
2442// MemoryPageEntry* oldEntry = (MemoryPageEntry*)MP_GetPageEntryLoc(pageMaster, ID_EOLPAGE);
2444// char* oldData = NULL;
2445// if ((oldEntry != NULL) && (oldEntry->pageSize != 0)) {
2446// // Make copy...
2447// char* eolData = getSystemBlock(ID_EOLPAGE, oldSize);
2448// if (newSize <= oldSize)
2449// return false;
2450// oldData = new char[oldSize];
2451// memcpy(eolData, oldData, oldSize);
2452// destroyPage(ID_EOLPAGE);
2453// }
2454// uint64 memID;
2455// char* data = createSystemPage(ID_EOLPAGE, newSize, memID);
2456// if (data == NULL)
2457// return false;
2459// memset(data, 0, newSize);
2460// EOLHeader* header = (EOLHeader*) data;
2461// header->slotCount = slotCount+bufferSlots;
2462// header->pagesPerSlot = pagesPerSlot;
2463// header->slotDuration = slotDuration;
2464// header->startSlot = 0;
2465// header->startTime = GetTimeNow();
2466// header->bufferSlots = bufferSlots;
2467//
2468// uint64 slotEOL = 0;
2469// if (oldData != NULL) {
2470// EOLHeader* oldHeader = (EOLHeader*) oldData;
2471// // Copy old data back in...
2472// EOLEntry* entry = (EOLEntry*) oldHeader + sizeof(EOLHeader);
2473// uint64 endHeader = (uint64) oldHeader + (oldHeader->slotCount*oldHeader->pagesPerSlot*sizeof(EOLEntry)) + sizeof(EOLHeader);
2474// while ((uint64) entry <= endHeader) {
2475// if (entry->eol > 0) {
2476// // Insert entry in new structure
2477// insertPageIntoEOL(entry->pageID, entry->eol, slotEOL);
2478// }
2479// entry += 1;
2480// //entry += sizeof(EOLEntry);
2481// }
2482// // Delete copy
2483// delete [] oldData;
2484// }
2485// return true;
2486//}
2487//
2489//bool MemoryManagerX::insertPageIntoEOL(uint32 pageID, uint64 eol, uint64& slotEOL) {
2490// uint32 sbSize = 0;
2491// EOLHeader* header = (EOLHeader*) getSystemBlock(ID_EOLPAGE, sbSize);
2492// if (header == NULL)
2493// return false;
2494//
2495// EOLEntry* entry = NULL;
2496// // Find the appropriate slot
2497// uint64 now = GetTimeNow();
2498// uint64 difTime = 0;
2499// if (eol - now > 0)
2500// difTime = eol - now;
2501// // If too far in the future, choose end slot
2502// uint32 difSlot = (uint32)(difTime / header->slotDuration);
2503// // If too far in the future, choose end slot - buffer slot
2504// if (difSlot >= (header->slotCount - header->bufferSlots))
2505// difSlot = header->slotCount - 1 - header->bufferSlots;
2506// // Calc end time of actual slot
2507// slotEOL = difSlot * header->slotDuration;
2508// // Find actual slot, possible wrap-around...
2509// uint32 actualSlot = header->startSlot + difSlot;
2510// if (actualSlot >= header->slotCount)
2511// actualSlot -= header->slotCount;
2512//
2514//
2515// entry = (EOLEntry*)((char*)header + sizeof(EOLHeader) +
2516// (actualSlot * header->pagesPerSlot * sizeof(EOLEntry)));
2517// char* endEntry = (char*) entry + header->pagesPerSlot*sizeof(EOLEntry);
2518// while ((char*) entry < endEntry) {
2519// if (entry->eol == 0) {
2520// entry->eol = eol;
2521// entry->pageID = pageID;
2522// return true;
2523// }
2524// else
2525// entry += 1;
2526// //entry += sizeof(EOLEntry);
2527// }
2528// // Out of room in current slot, try the next slot
2529// if (difSlot < header->slotCount - 1)
2530// return insertPageIntoEOL(pageID, eol+header->slotDuration, slotEOL);
2531// else {
2532// // we need to resize the EOL structure
2533// resizeEOLPage(header->slotCount, header->pagesPerSlot * 4, header->slotDuration, header->bufferSlots);
2534// return insertPageIntoEOL(pageID, eol, slotEOL);
2535// }
2536//}
2537//
2538//
2540//bool MemoryManagerX::initQueuePage(char* data, uint32 size) {
2541// memset(data, 0, size);
2542// return true;
2543//}
2544//
2545//
2546//MemoryPage* MemoryManagerX::getCachedPage(uint32 pageID) {
2547// return getCachedPage((MemoryPageEntry*)MP_GetPageEntryLoc(pageMaster, pageID));
2548//}
2549//
2550//MemoryPage* MemoryManagerX::getCachedPage(MemoryPageEntry *entry) {
2551// if (entry == NULL)
2552// return NULL;
2553//
2554// if (pageCache == NULL) {
2555// uint32 size = sizeof(MemoryPageCache) + pageMaster->pageTableSize*sizeof(MemoryPageCacheEntry);
2556// pageCache = (MemoryPageCache*) malloc(size);
2557// pageCache->size = size;
2558// pageCache->count = pageMaster->pageTableSize;
2559// memset((char*)pageCache + sizeof(MemoryPageCache), 0, size - sizeof(MemoryPageCache));
2560// }
2561//
2562// // Find CachedEntry
2563// MemoryPageCacheEntry* cEntry = (MemoryPageCacheEntry*) ((char*)pageCache + sizeof(MemoryPageCache) + (entry->pageID * sizeof(MemoryPageCacheEntry)));
2564// if (cEntry == NULL)
2565// return NULL;
2566// else if ( (cEntry->page == NULL) || (cEntry->cacheSerial != entry->cacheSerial) || (cEntry->pageSerial != entry->pageSerial) ) {
2567// // Cache needs updating
2568// if (cEntry->page != NULL)
2569// utils::DestroySharedMemorySegment((char*)cEntry->page, cEntry->pageSize);
2570// // Map page memory location
2571//
2572// char* pageName = new char[MAXKEYNAMELEN];
2573// sprintf(pageName, "Page_%u", entry->pageID);
2574// cEntry->page = (MemoryPage*) utils::OpenSharedMemorySegment(pageName, entry->pageSize);
2575// delete [] pageName;
2576// if (cEntry->page == NULL)
2577// return NULL;
2578// cEntry->cacheSerial = entry->cacheSerial;
2579// cEntry->pageID = entry->pageID;
2580// cEntry->pageSerial = entry->pageSerial;
2581// cEntry->pageSize = entry->pageSize;
2582// }
2583// //printf("Got cached page id %d: %p\n", entry->pageID, cEntry->page);
2584// //fflush(stdout);
2585// return cEntry->page;
2586//}
2587//
2588//bool MemoryManagerX::updateCachedPage(MemoryPageEntry *entry, MemoryPage *page) {
2589// if (entry == NULL)
2590// return false;
2591//
2592// if (pageCache == NULL) {
2593// uint32 size = sizeof(MemoryPageCache) + pageMaster->pageTableSize*sizeof(MemoryPageCacheEntry);
2594// pageCache = (MemoryPageCache*)malloc(size);
2595// pageCache->size = size;
2596// pageCache->count = pageMaster->pageTableSize;
2597// memset((char*)pageCache + sizeof(MemoryPageCache), 0, size - sizeof(MemoryPageCache));
2598// }
2599//
2600// // Find CachedEntry
2601// MemoryPageCacheEntry* cEntry = (MemoryPageCacheEntry*) ((char*)pageCache + sizeof(MemoryPageCache) + (entry->pageID * sizeof(MemoryPageCacheEntry)));
2602// if (cEntry == NULL)
2603// return NULL;
2604//
2605// // Should existing page be removed?
2606// if ( (cEntry->page != NULL) && (cEntry->page != page) && ( (page != NULL) || (entry->pageSize == 0) ) ) {
2607// utils::DestroySharedMemorySegment((char*)cEntry->page, cEntry->pageSize);
2608// cEntry->page = NULL;
2609// }
2610// if (page != NULL)
2611// cEntry->page = page;
2612// cEntry->cacheSerial = entry->cacheSerial;
2613// cEntry->pageID = entry->pageID;
2614// cEntry->pageSerial = entry->pageSerial;
2615// cEntry->pageSize = entry->pageSize;
2616//
2617// return true;
2618//}
2619//
2620//
2621//
2622//
2623//
2624//
2625//
2626//
2627//
2628//
2629//
2630//
2631//
2632//
2633//
2634//
2635//
2636//
2637//
2638//
2644//
2646//uint32 MemoryManagerX::runManager() {
2647// LogPrint(0, LOG_SYSTEM, 5, "Memory Management running...\n\n");
2648// isRunning = true;
2649//
2650// uint64 nextPageCheck = 0, now;
2651//
2652// while (shouldContinue) {
2653// if (!pageMasterMutex->enter())
2654// break;
2655//
2656// if (isMaster)
2657// pageMaster->timesync = LocalSyncAdjustment;
2658// else
2659// LocalSyncAdjustment = pageMaster->timesync;
2660//
2661// now = GetTimeNow();
2662//
2663// if (!nextPageCheck || (now >= nextPageCheck) ) {
2664//
2665// uint32 sbSize = 0;
2666// EOLHeader* header = (EOLHeader*) getSystemBlock(ID_EOLPAGE, sbSize);
2667// if (header == NULL) {
2668// pageMasterMutex->leave();
2669// break;
2670// }
2671//
2672// EOLEntry* entry;
2673// char* endEntry;
2674// int32 delSlot;
2675// // Check if we should tick the current EOL startSlot to the next slot
2676// while ( now - header->startTime > header->slotDuration) {
2677// // Move the current slot one forward
2678// header->startSlot++;
2679// if (header->startSlot > header->slotCount)
2680// header->startSlot -= header->slotCount;
2681// header->startTime += header->slotDuration;
2682// // printf("New startSlot: %u (%d)...\n", header->startSlot, GetTimeNow() - header->startTime);
2683// // Find the slot minus bufferSlots
2684// delSlot = header->startSlot - header->bufferSlots;
2685// if (delSlot < 0)
2686// delSlot += header->slotCount;
2687//
2688// // Free all pages in the slot
2689// entry = (EOLEntry*)((char*)header + sizeof(EOLHeader) +
2690// (delSlot * header->pagesPerSlot * sizeof(EOLEntry)));
2691// endEntry = (char*) entry + header->pagesPerSlot*sizeof(EOLEntry);
2692// while ((char*) entry < endEntry) {
2693// if (entry->eol > 0) {
2694// // printf("--------- Freeing page ID %u, slot %u, eol %llu...\n", entry->pageID, delSlot, entry->eol);
2695// freePageIntoPool(entry->pageID);
2696// entry->eol = 0;
2697// entry->pageID = 0;
2698// }
2699// entry += 1;
2700// }
2701//
2702// }
2703// nextPageCheck = header->startTime + header->slotDuration + 20000;
2704// // sleep = header->startTime + header->slotDuration - GetTimeNow() + 20000;
2705// pageMasterMutex->leave();
2706// }
2707// else {
2708// pageMasterMutex->leave();
2709// utils::Sleep(20);
2710// }
2711// }
2712//
2713// isRunning = false;
2714// return 0;
2715//}
2716//
2717//bool MemoryManagerX::UnitTest() {
2718// printf("Testing Static Memory Management...\n\n");
2719//
2720// // First create and initialise the MemoryManager
2721// MemoryManagerX* manager = new MemoryManagerX();
2722// uint32 maxPageCount = 15;
2723// // fprintf(stderr, "MemoryManager init() 0...\n");
2724// if (!manager->create(0, maxPageCount)) {
2725// fprintf(stderr, "MemoryManager init() failed...\n");
2726// delete(manager);
2727// return false;
2728// }
2729// // fprintf(stderr, "MemoryManager init() success...\n");
2730//
2731// uint64 eol = 0;
2732// uint32 size = 4096;
2733// char* data = new char[size];
2734//
2735// // we should be able to add
2736// uint32 expectedCount = CalcBlockTableSize(size);
2737// uint32 expectedMaxCount = (maxPageCount-RESERVEDPAGECOUNT) * expectedCount;
2738// uint32 count = expectedMaxCount;
2739// uint64* ids = new uint64[count];
2740//
2741// // printf("\n\n>>>>>> Inserting %lu blocks ...\n\n", count);
2742//
2743// uint32 n;
2744// uint64 id;
2745// uint64 t1 = GetTimeNow();
2746// for (n=0; n<count; n++) {
2747// strcpy(data, "Test");
2748// utils::Int2Ascii(n, data+4, size-4, 10);
2749// if (!manager->insertMemoryBlock(data, size, eol, id)) {
2750// fprintf(stderr, "MemoryManager insert %d failed...\n", n);
2751// delete [] ids;
2752// delete [] data;
2753// delete(manager);
2754// return false;
2755// }
2756// ids[n] = id;
2757// }
2758// uint64 t2 = GetTimeNow();
2759//
2760// uint32 size2 = 0;
2761// uint64 eol2 = 0;
2762// char* data2;
2763//
2764// // printf("\n\n>>>>>> Getting %lu blocks ...\n\n", count);
2765// for (n=0; n<count; n++) {
2766// data2 = manager->getCopyMemoryBlock(ids[n], size2, eol2);
2767// if (data2 == NULL) {
2768// fprintf(stderr, "MemoryManager getcopy failed...\n");
2769// delete [] ids;
2770// delete [] data;
2771// delete(manager);
2772// return false;
2773// }
2774// if (size2 != size) {
2775// fprintf(stderr, "MemoryManager getcopy got wrong size back...\n");
2776// delete [] ids;
2777// delete [] data;
2778// delete [] data2;
2779// delete(manager);
2780// return false;
2781// }
2782// strcpy(data, "Test");
2783// utils::Int2Ascii(n, data+4, size-4, 10);
2784// if (strcmp(data2, data) != 0) {
2785// fprintf(stderr, "MemoryManager getcopy got wrong data back...\n");
2786// delete [] ids;
2787// delete [] data;
2788// delete [] data2;
2789// delete(manager);
2790// return false;
2791// }
2792// if (eol2 != eol) {
2793// fprintf(stderr, "MemoryManager getcopy got wrong eol back (%llu != %llu) [%u]...\n", eol2, eol, n);
2794// delete [] ids;
2795// delete [] data;
2796// delete [] data2;
2797// delete(manager);
2798// return false;
2799// }
2800// delete [] data2;
2801// }
2802// uint64 t3 = GetTimeNow();
2803//
2804// printf("Performance:\n Writing %u: %.3f MB/s / %.3f entries/s (%u us) [%u b]\n",
2805// count, (1.0*size*count)/(t2-t1), (1000000.0*count)/(t2-t1), (uint32)(t2-t1), size);
2806// printf(" Reading %u: %.3f MB/s / %.3f entries/s (%u us) [%u b]\n\n",
2807// count, (1.0*size*count)/(t3-t2), (1000000.0*count)/(t3-t2), (uint32)(t3-t2), size);
2808//
2809// delete [] ids;
2810// delete [] data;
2811// delete(manager);
2812// fprintf(stdout, "*** Static Memory Management test ran successfully ***\n\n\n");
2813//
2815//
2816// printf("Testing Dynamic Memory Management...\n\n");
2817//
2818// manager = new MemoryManagerX();
2819// // Initialise for 10 slots of 1 sec each, 0 buffer = 10 second max keep
2820// // fprintf(stderr, "MemoryManager init() 0...\n");
2821// if (!manager->create(0, 100, 10, 100000, 1)) {
2822// fprintf(stderr, "MemoryManager init() failed...\n");
2823// delete(manager);
2824// return false;
2825// }
2826// // fprintf(stderr, "MemoryManager init() success...\n");
2827//
2828// uint64 now = GetTimeNow();
2829//
2830// uint32 total, usage, sysTotal, sysUsage, staticTotal, staticUsage, dynamicTotal, dynamicUsage;
2831// if (GetMemoryUsage(total, usage, sysTotal, sysUsage, staticTotal, staticUsage, dynamicTotal, dynamicUsage))
2832// printf("Dynamic Memory in use before test: %u (%u allocated))\n", dynamicUsage, dynamicTotal);
2833//
2834// char* mem;
2835// for (n=0; n<30; n++) {
2836// mem = new char[1024];
2837// if (!manager->insertMemoryBlock(mem, 1024, now+1000000, id)) {
2838// fprintf(stderr, "MemoryManager insert memory failed...\n");
2839// delete(manager);
2840// return false;
2841// }
2842// delete [] mem;
2843// if (GetMemoryUsage(total, usage, sysTotal, sysUsage, staticTotal, staticUsage, dynamicTotal, dynamicUsage))
2844// printf("Dynamic Memory in use add %u: %u (%u allocated))\n", n, dynamicUsage, dynamicTotal);
2845// utils::Sleep(100);
2846// now = GetTimeNow();
2847// }
2848//
2849// for (n=0; n<20; n++) {
2850// if (GetMemoryUsage(total, usage, sysTotal, sysUsage, staticTotal, staticUsage, dynamicTotal, dynamicUsage))
2851// printf("Dynamic Memory in use idle %u: %u (%u allocated))\n", n, dynamicUsage, dynamicTotal);
2852// utils::Sleep(100);
2853// }
2854//
2855//
2856// delete(manager);
2857// fprintf(stdout, "*** Dynamic Memory Management test ran successfully ***\n\n\n");
2858//
2859// return true;
2860//}
2861
2862//#define SEGSIZE ((size_t)1024)
2863//
2864//int server() {
2865//
2866// int shmFD;
2867// void *shmAdd;
2868// int i, useMode=1; /* 1=use segment, not create it. */
2869//
2870// /* We get "open" a shared memory segment with the given name. The
2871// flags work just as they do with open: O_CREAT creates the segment
2872// if it doesn't exist, O_EXCL errors out if the segment already
2873// exists, and O_RDRW opens it for read and write. The perms are as
2874// with chmod. Normally, things opened with shm_open do now appear
2875// in the filesystem; however, it is best to specify a path to a
2876// file you can write to! */
2877// shmFD = shm_open("foobar", O_RDWR | O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO);
2878// if(shmFD < 0) {
2879// /* I have a case for all of the interesting cases, even the ones
2880// that can not happen in this situation... */
2881// switch(errno) {
2882// case EACCES: printf("shm_open failed: The requested permissions were denied or create denied .\n");
2883// break;
2884// case EEXIST: printf("shm_open failed: Object already exists and O_CREAT and O_EXCL were specified.\n");
2885// useMode=1;
2886// break;
2887// case EINTR: printf("shm_open failed: The operation was interrupted by a signal.\n");
2888// break;
2889// case EINVAL: printf("shm_open failed: The operation is not supported.\n");
2890// break;
2891// case EMFILE: printf("shm_open failed: Too many file descriptors were already open.\n");
2892// break;
2893// case ENAMETOOLONG: printf("shm_open failed: Name was too long (longer than SHM_NAME_MAX chars).\n");
2894// break;
2895// case ENFILE: printf("shm_open failed: The system file table is full.\n");
2896// break;
2897// case ENOENT: printf("shm_open failed: Object doesn't exist (O_CREAT was not specified).\n");
2898// break;
2899// case ENOSPC: printf("shm_open failed: No memory to create object (O_CREAT was specified).\n");
2900// break;
2901// default: printf("shm_open failed: Duno why...\n");
2902// break;
2903// } /* end switch */
2904//
2905// exit(1);
2906// } /* end if */
2907//
2908//
2909// /* Use ftruncate() to size the region -- IMO an only semi-intuitive
2910// choice on the part of the POSIX committee. */
2911// if(ftruncate(shmFD, SEGSIZE) < 0) {
2912// /* I have included all typically supported error cases below, even
2913// if they don't apply here. */
2914// switch(errno) {
2915// case EBADF: printf("ftruncate failed: The fd is not a valid descriptor.\n");
2916// break;
2917// case EINVAL: printf("ftruncate failed: Not open for writing, or references a socket, not a file.\n");
2918// break;
2919// default: printf("ftruncate failed: Duno why...\n");
2920// break;
2921// } /* end switch */
2922// exit(1);
2923// } /* end if */
2924//
2925// shmAdd = (char *)mmap(NULL, // Almost always not used
2926// SEGSIZE, // Length of the mapped space
2927// PROT_READ | PROT_WRITE, // Access type
2928// MAP_SHARED, // Write changes to device (see: MAP_PRIVATE)
2929// shmFD, // FD of the shared memory segment
2930// 0); // Offset into segment.
2931//
2932// /* For more info on the strange return and possible error conditions
2933// of mmap(), see the mmap.c example program. */
2934// if(shmAdd == MAP_FAILED) {
2935// switch(errno) {
2936// case EACCES: printf("mmap failed: The FD was not open for read, or for write with (PROT_WRITE or MAP_SHARED)\n");
2937// break;
2938// case EAGAIN: printf("mmap failed: The mapping could not be locked in memory\n");
2939// break;
2940// case EBADF: printf("mmap failed: The FD not a valid open file descriptor.\n");
2941// break;
2942// case EINVAL: printf("mmap failed: The value of len is zero, addr is not valid, bad combination of args\n");
2943// break;
2944// case EMFILE: printf("mmap failed: The too many regions mapped already\n");
2945// break;
2946// case ENODEV: printf("mmap failed: The FD file type is not supported by mmap().\n");
2947// break;
2948// case ENOMEM: printf("mmap failed: Not enough memory\n");
2949// break;
2950// case ENOTSUP: printf("mmap failed: Options not supported on this platform\n");
2951// break;
2952// case ENXIO: printf("mmap failed: Range [off,off+len) are invalid for the FD, MAP_FIXED & invalid addresses, or FD not accessible\n");
2953// break;
2954// case EOVERFLOW: printf("mmap failed: File is too big!\n");
2955// break;
2956// default: printf("mmap failed: Duno why! (errno: %d)\n", errno);
2957// break;
2958// } /* end switch */
2959// exit(1);
2960// } /* end if */
2961//
2962// /* We copy some stuff into the segment so that we can read it out later... */
2963// printf("Write 'Hello' into the segment.\n");
2964// strcpy((char*)shmAdd, "Hello");
2965//
2966// return 0;
2967//} /* end func main() */
2968//
2969//
2970//int client() {
2971// int shmFD;
2972// void *shmAdd;
2973// int i, useMode=0; /* 1=use segment, not create it. */
2974//
2975// /* If we failed before because the segment already existed, then we try to open it
2976// up and use it -- thus combining the "make" and "use" example programs. */
2977// shmFD = shm_open("foobar", O_RDWR, S_IRWXU | S_IRWXG | S_IRWXO);
2978// if(shmFD < 0) {
2979// switch(errno) {
2980// case EACCES: printf("shm_open failed: The requested permissions were denied or create denied .\n");
2981// break;
2982// case EEXIST: printf("shm_open failed: Object already exists and O_CREAT and O_EXCL were specified.\n");
2983// useMode=1;
2984// break;
2985// case EINTR: printf("shm_open failed: The operation was interrupted by a signal.\n");
2986// break;
2987// case EINVAL: printf("shm_open failed: The operation is not supported.\n");
2988// break;
2989// case EMFILE: printf("shm_open failed: Too many file descriptors were already open.\n");
2990// break;
2991// case ENAMETOOLONG: printf("shm_open failed: Name was too long (longer than SHM_NAME_MAX chars).\n");
2992// break;
2993// case ENFILE: printf("shm_open failed: The system file table is full.\n");
2994// break;
2995// case ENOENT: printf("shm_open failed: Object doesn't exist (O_CREAT was not specified).\n");
2996// break;
2997// case ENOSPC: printf("shm_open failed: No memory to create object (O_CREAT was specified).\n");
2998// break;
2999// default: printf("shm_open failed: Duno why...\n");
3000// break;
3001// } /* end switch */
3002// exit(1);
3003// } /* end if */
3004//
3005//
3006// shmAdd = (char *)mmap(NULL, // Almost always not used
3007// SEGSIZE, // Length of the mapped space
3008// PROT_READ | PROT_WRITE, // Access type
3009// MAP_SHARED, // Write changes to device (see: MAP_PRIVATE)
3010// shmFD, // FD of the shared memory segment
3011// 0); // Offset into segment.
3012//
3013// /* For more info on the strange return and possible error conditions
3014// of mmap(), see the mmap.c example program. */
3015// if(shmAdd == MAP_FAILED) {
3016// switch(errno) {
3017// case EACCES: printf("mmap failed: The FD was not open for read, or for write with (PROT_WRITE or MAP_SHARED)\n");
3018// break;
3019// case EAGAIN: printf("mmap failed: The mapping could not be locked in memory\n");
3020// break;
3021// case EBADF: printf("mmap failed: The FD not a valid open file descriptor.\n");
3022// break;
3023// case EINVAL: printf("mmap failed: The value of len is zero, addr is not valid, bad combination of args\n");
3024// break;
3025// case EMFILE: printf("mmap failed: The too many regions mapped already\n");
3026// break;
3027// case ENODEV: printf("mmap failed: The FD file type is not supported by mmap().\n");
3028// break;
3029// case ENOMEM: printf("mmap failed: Not enough memory\n");
3030// break;
3031// case ENOTSUP: printf("mmap failed: Options not supported on this platform\n");
3032// break;
3033// case ENXIO: printf("mmap failed: Range [off,off+len) are invalid for the FD, MAP_FIXED & invalid addresses, or FD not accessible\n");
3034// break;
3035// case EOVERFLOW: printf("mmap failed: File is too big!\n");
3036// break;
3037// default: printf("mmap failed: Duno why! (errno: %d)\n", errno);
3038// break;
3039// } /* end switch */
3040// exit(1);
3041// } /* end if */
3042//
3043// /* The segment already existed, so we print out it's contents and change them. */
3044// /* Just print the printable chars in case the segment has binary junk in it... */
3045// printf("The segment content: \n");
3046// for(i=0;(i<SEGSIZE)&&(((char *)shmAdd)[i]!=0);i++)
3047// if(isalpha(((char *)shmAdd)[i]) || isdigit(((char *)shmAdd)[i]))
3048// printf("%c", ((char *)shmAdd)[i]);
3049// printf("\n");
3050//
3051// /* Now we change the data to "Goodbye" */
3052// printf("Change the contents to: 'Goodbye'..\n");
3053// strcpy((char*)shmAdd, "Goodbye");
3054//
3055// /* While not required, one should unmap from segments when done with them. */
3056// if(munmap(shmAdd, SEGSIZE) < 0) {
3057// switch(errno) {
3058// case EINVAL: printf("munmap failed: The address range [addr,addr+len) is invalid.\n"
3059// " munmap failed: The len argument is 0.\n"
3060// " munmap failed: The addr argument is not a multiple of page size.\n");
3061// break;
3062// default: printf("munmap failed: Duno why! (errno %d).\n", errno);
3063// break;
3064// } /* end switch */
3065// exit(1);
3066// } /* end if */
3067//
3068// /* One should also close FDs opened with shm_open (again, not
3069// necessarily required, but good practice). */
3070// if(close(shmFD) < 0) {
3071// switch(errno) {
3072// case EBADF: printf("close failed: The FD is not an active descriptor.\n");
3073// break;
3074// case EINTR: printf("close failed: An interrupt was received.\n"); // Should try again... :)
3075// break;
3076// } /* end switch */
3077// } /* end if */
3078//
3079// return 0;
3080//} /* end func main() */
3081
3083
3084 // NOTE: the original shared-memory exercise (CreateSharedMemorySegment /
3085 // OpenSharedMemorySegment / server() / client()) is disabled in this build,
3086 // so this test is currently a smoke check that the entry point is callable.
3087 unittest::progress(10, "shared memory smoke check");
3088
3089 //char *data = utils::CreateSharedMemorySegment("foobar", 1024);
3090 //if (!data)
3091 // unittest::detail("Couldn't create test shared memory segment...");
3092
3093 //char* data2 = utils::OpenSharedMemorySegment("foobar", 1024);
3094 //if (!data2)
3095 // unittest::detail("Couldn't open test shared memory segment...");
3096
3097 unittest::progress(100, "done");
3098 return true;
3099
3100// server();
3101// client();
3102}
3103
3104
3107 "Static memory management insert/read-back throughput", "memory");
3109 "Shared memory segment smoke check", "memory");
3110}
3111
3112
3113} // namespace cmlabs
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
Central shared-memory manager for a Psyclone node: master segment, per-subsystem shared maps and the ...
#define PSYCLONE_STATUS_ENDED
Instance has shut down (or crashed and was reaped).
#define PSYCLONE_INDEX_SIZE
Total byte size of the instance-index shared-memory segment.
#define PSYCLONE_STATUS_INIT
Instance is starting up, not yet serving.
#define PSYCLONE_INDEX_MAXCOUNT
Maximum number of concurrently tracked Psyclone instances per machine.
#define PSYCLONE_STATUS_READY
Instance is fully operational.
#define PSYCLONE_STATUS_NONE
No instance recorded in this slot.
#define PSYCLONEINDEXID
Definition ObjectIDs.h:46
#define PSYCLONEMASTERID
Definition ObjectIDs.h:47
CMSDK time: µs-resolution 64-bit timestamps and the Time Mapping Constant (TMC).
Small, dependency-free unit test harness used by all CMSDK object tests.
#define MAXKEYNAMELEN
Definition Utils.h:85
#define thread_ret_val(ret)
Definition Utils.h:131
#define THREAD_RET
Definition Utils.h:127
#define THREAD_FUNCTION_CALL
Definition Utils.h:129
#define LOG_MEMORY
Definition Utils.h:216
#define LogPrint
Definition Utils.h:330
#define THREAD_ARG
Definition Utils.h:130
Accessor for the shared component registry.
Accessor for the shared name/id maps and the request map.
bool maintenance()
Periodic cleanup (e.g.
The central Psyclone data container: a self-contained binary message with typed, named user entries.
bool setEOL(uint64 eol)
setEOL(uint64 eol)
bool getInt(const char *key, int64 &value)
getInt(const char* key, int64& value)
bool setInt(const char *key, int64 value)
setInt(const char* key, int64 value)
uint32 getSize()
getSize() Get message size Many types of data of any size can be put into a message as user entries; ...
bool setData(const char *key, const char *value, uint32 size)
setData(const char* key, const char* value, uint32 size)
Handle to the node's master shared-memory segment (MemoryMasterStruct).
uint32 incrementDynamicShmemSerial()
Bump the dynamic segment serial after resize.
bool create(uint16 port)
Create the master segment for the node instance listening on port.
uint32 incrementDataMapsShmemSerial()
Bump the data-maps segment serial after resize.
uint16 getID()
MemoryController interface:
bool setComponentShmemSize(uint64 size)
Record a new component segment size.
bool setID(uint16 id)
MemoryController interface: set the node id.
uint16 port
Node port this master segment belongs to (names all related segments).
bool setDataMapsShmemSize(uint64 size)
Record a new data-maps segment size.
uint32 incrementProcessShmemSerial()
Bump the process segment serial after resize.
uint32 incrementComponentShmemSerial()
Bump the component segment serial after resize.
bool setDynamicShmemSize(uint64 size)
Record a new dynamic segment size.
bool setNodeID(uint16 id)
Set the cluster-wide node id.
bool setProcessShmemSize(uint64 size)
Record a new process segment size.
bool open(uint16 port)
Attach to an existing master segment created by another process.
Top-level facade of the shared-memory subsystem for one process.
ProcessMemory * processMemory
Accessor for the process table and per-process queues.
DataMessage * getCopyOfMessage(uint64 id)
Fetch a private copy of a previously published message.
ComponentMemory * componentMemory
Accessor for the component registry.
bool create(uint16 sysID, uint32 slotCount=100000, uint16 binCount=2, uint32 minBlockSize=1024, uint32 maxBlockSize=64 *1024, uint64 initSize=50000000L, uint64 maxSize=1000000000L, bool force=false)
Create all shared segments for a new node instance (master process only).
static bool UnitTest()
Self-test of the shared-memory manager.
std::string subTypeToText(uint16 subtype)
Resolve a subtype id to its registered name.
DataMessage * retrieveAllSystemIDs()
Enumerate all live Psyclone system ids/ports on this machine (via the PsycloneIndex).
uint8 getNodeStatus(uint64 &lastseen, uint64 &createdTime)
Get the node status from the master segment.
bool setNodeID(uint16 id)
Set this node's cluster-wide id.
static MemoryManager * Singleton
Per-process singleton instance, set by the constructor.
static bool ShmUnitTest()
Self-test of the raw shared-memory primitives.
bool insertMessage(DataMessage *msg, uint64 &id)
Publish a DataMessage into shared (temporal) memory.
std::string getComponentName(uint32 compID)
Resolve a component id to its name.
std::string subContextToText(uint16 subcontext)
Resolve a subcontext id to its registered name.
std::string typeToText(PsyType type)
Resolve a type id to its registered name.
bool getTimeSyncData(uint64 &tmc, int64 &adjust)
Read the cluster time-sync values from the master segment.
bool getMemoryUsage(uint64 &sysAlloc, uint64 &sysUsage, uint64 &dataAlloc, uint64 &dataUsage)
Report allocation/usage figures for the system and data segments.
DataMapsMemory * dataMapsMemory
Accessor for the type/context/tag/crank/request maps.
bool connect(uint16 sysID, bool isMaster)
Attach this process to an existing node's shared segments.
TemporalMemory * temporalMemory
Accessor for time-limited message storage.
friend THREAD_RET THREAD_FUNCTION_CALL MemoryManagement(THREAD_ARG arg)
Background maintenance thread entry point for MemoryManager / MemoryManagerX.
std::string contextToText(PsyContext context)
Resolve a context id to its registered name.
bool setTimeSyncData(uint64 tmc, int64 adjust)
Write the cluster time-sync values into the master segment.
Accessor for the shared process table and per-process queues.
Accessor for the machine-global instance index segment.
bool setStatus(uint8 status)
Update this instance's status and heartbeat in the shared index.
bool init(uint16 port, uint64 instID)
Attach to (or create) the index segment and claim/refresh the slot for this instance.
static bool GetStatus(uint16 port, uint8 &status, uint64 &heartbeat)
Look up the status of the instance registered on port.
Accessor for the temporal (dynamic) message store in shared memory.
static bool CreateThread(THREAD_FUNCTION func, void *args, uint32 &newID, uint32 reqID=0)
Create a new native thread and start it immediately.
static bool Shutdown()
Terminate all managed threads, then destroy the singleton.
static UnitTestRunner & instance()
Access the singleton (created on first use).
void registerTest(const char *name, UnitTestFunc func, const char *description="", const char *category="", bool inDefaultRun=true, uint32 timeoutSec=0)
Register a test with the runner.
Recursive mutual-exclusion lock, optionally named for cross-process use.
Definition Utils.h:480
uint64 GetTimeNow()
Return the current absolute time (µs since year 0) according to the TMC.
Definition PsyTime.cpp:69
bool SetCurrentTimeSyncData(uint64 tmc, int64 netTimeAdjust)
Install externally computed sync data (e.g.
Definition PsyTime.cpp:140
std::string PrintTimeDifString(uint64 t, bool us=true, bool ms=true)
Definition PsyTime.cpp:722
int32 GetTimeAgeMS(uint64 t)
Age of a timestamp relative to now, in milliseconds.
Definition PsyTime.cpp:35
int64 GetTimeAge(uint64 t)
Age of a timestamp relative to now.
Definition PsyTime.cpp:25
bool GetCurrentTimeSyncData(uint64 &tmc, int64 &netTimeAdjust)
Read the current sync data.
Definition PsyTime.cpp:147
uint32 RemovePortSharedSegments(uint16 port)
Remove every shared-memory/semaphore name for this port (as ClearStaleSharedSegments,...
Definition Utils.cpp:3627
bool Sleep(uint32 ms)
Suspend the calling thread.
Definition Utils.cpp:4078
char * OpenSharedMemorySegment(const char *name, uint64 size)
Open and map an existing named shared memory segment.
Definition Utils.cpp:3380
char * CreateSharedMemorySegment(const char *name, uint64 size, bool force=false)
Create a named shared memory segment and map it into this process.
Definition Utils.cpp:3247
bool CloseSharedMemorySegment(char *data, uint64 size)
Unmap a segment previously created/opened here.
Definition Utils.cpp:3491
bool DisownSharedMemorySegment(char *data)
Give up this process's ownership of a segment's name, so closing it here only unmaps.
Definition Utils.cpp:3529
void ClearStaleSharedSegments(uint16 port)
Remove stale OS shared-memory/semaphore objects left by a crashed node on this port.
Definition Utils.cpp:3648
void fail(const char *fmt,...)
Set an explanatory reason shown on the FAIL line.
void metric(const char *name, double value, const char *unit="", bool higherIsBetter=true)
Record a performance metric.
void detail(const char *fmt,...)
Verbose-only indented diagnostic line (shown only when verbose=1).
void progress(int percent, const char *action)
Report progress with a short description of the current action.
std::string StringFormat(const char *format,...)
printf into a std::string.
Definition Utils.cpp:9061
THREAD_RET THREAD_FUNCTION_CALL MemoryManagement(THREAD_ARG arg)
Background maintenance thread entry point for MemoryManager / MemoryManagerX.
void Register_MemoryManager_Tests()
Hierarchical execution-context identifier.
Definition Types.h:284
Hierarchical message type identifier — the key used for publish/subscribe matching in Psyclone.
Definition Types.h:123
Root header of the node's master shared-memory segment.
One slot in the machine-global Psyclone instance index.
uint16 port
TCP port the instance listens on; doubles as the instance key.
uint64 heartbeat
Last heartbeat timestamp (µs since epoch); staleness implies a dead instance.
uint8 status
One of the PSYCLONE_STATUS_* values.
Header of the machine-global Psyclone instance index shared-memory segment.