ba04a87a3ec614500270d6c220cbfb0b827443bf
[charm.git] / src / libs / ck-libs / multiphaseSharedArrays / msa-DistPageMgr.h
1 // emacs mode line -*- mode: c++; tab-width: 4 ; c-basic-style: stroustrup -*-
2
3 #ifndef MSA_DISTPAGEMGR_H
4 #define MSA_DISTPAGEMGR_H
5
6 #include <charm++.h>
7 #include <string.h>
8 #include <list>
9 #include <stack>
10 #include <map>
11 #include <set>
12 #include <vector>
13 #include "msa-common.h"
14
15 // forward decl needed in msa-DistPageMgr.ci, i.e. in msa.decl.h
16
17 /// Stores a list of indices to be written out.
18 struct MSA_WriteSpan_t {
19     int start,end;
20     inline void pup(PUP::er &p) {
21         p|start; p|end;
22     }
23 };
24
25 template <class ENTRY, class MERGER,
26           unsigned int ENTRIES_PER_PAGE>
27 class MSA_PageT;
28 #include "msa.decl.h"
29
30 //=======================================================
31 // Utility Classes
32
33 /// Listens for some event on a page or set of pages.
34 class MSA_Listener {
35 public:
36         MSA_Listener() {}
37         virtual ~MSA_Listener();
38         /// Getting added to a lister list.
39         virtual void add(void) =0;
40         /// Event waiting for has occurred.
41         virtual void signal(unsigned int pageNo) =0;
42 };
43
44 /// Keeps a list of MSA_Listeners
45 class MSA_Listeners {
46         CkVec<MSA_Listener *> listeners;
47 public:
48         MSA_Listeners();
49         ~MSA_Listeners();
50         
51         /// Add this listener to your set.  Calls l->add().
52         void add(MSA_Listener *l);
53         
54         /// Return the number of listeners in our set.
55         unsigned int size(void) const {return listeners.size();}
56         
57         /// Signal all added listeners and remove them from the set.
58         void signal(unsigned int pageNo);
59 };
60
61
62 /** Resumes a thread once all needed pages have arrived */
63 class MSA_Thread_Listener : public MSA_Listener {
64         CthThread thread;    // the suspended thread of execution (0 if not suspended)
65         int count;  // number of pages we're still waiting for
66 public:
67         MSA_Thread_Listener() :thread(0), count(0) {}
68         
69         /// Wait for one more page.
70         void add(void);
71         
72         /// If we're waiting for any pages, suspend our thread.
73         void suspend(void);
74         
75         /// Another page arrived.
76         void signal(unsigned int pageNo);
77 };
78
79
80
81 /// Fast, fixed-size bitvector class.
82 template <unsigned int NUM_BITS>
83 class fixedlength_bitvector {
84 public:
85         /// Data type used to store actual bits in the vector.
86         typedef unsigned long store_t;
87         enum { store_bits=8*sizeof(store_t) };
88         
89         /// Number of store_t's in our vector.
90         enum { len=(NUM_BITS+(store_bits-1))/store_bits };
91         store_t store[len];
92         
93         fixedlength_bitvector() {reset();}
94
95         /// Fill the entire vector with this value.
96         void fill(store_t s) {
97                 for (int i=0;i<len;i++) store[i]=s;
98         }
99
100         void reset(void) {fill(0);}
101         
102         /// Set-to-1 bit i of the vector.
103         void set(unsigned int i) { store[i/store_bits] |= (1lu<<(i%store_bits)); }
104
105         /// Clear-to-0 bit i of the vector.
106         void reset(unsigned int i) { store[i/store_bits] &= ~(1lu<<(i%store_bits)); }
107         
108         /// Return the i'th bit of the vector.
109         bool test(unsigned int i) { return (store[i/store_bits] & (1lu<<(i%store_bits))); }
110 };
111
112 /// Stores all housekeeping information about a cached copy of a page: 
113 ///   everything but the actual page data.
114 template <class ENTRY, unsigned int ENTRIES_PER_PAGE>
115 class MSA_Page_StateT
116 {
117         /** Write tracking:
118                 Somehow, we have to identify the entries in a page 
119                 that have been written to.  Our method for doing this is
120                 a bitvector: 0's indicate the entry hasn't been written; 
121                 1's indicate the entry has been written.
122         */
123         typedef fixedlength_bitvector<ENTRIES_PER_PAGE> writes_t;
124         writes_t writes;
125         typedef typename writes_t::store_t writes_store_t;
126         enum {writes_bits=writes_t::store_bits};
127         
128         /// Tracking writes to our writes: a smaller vector, used to 
129         ///  avoid the large number of 0's in the writes vector.
130         ///  Bit i of writes2 indicates that store_t i of writes has 1's.
131         typedef fixedlength_bitvector<writes_t::len> writes2_t;
132         writes2_t writes2;
133         typedef typename writes2_t::store_t writes2_store_t;
134         enum {writes2_bits=writes2_t::store_bits*writes_t::store_bits};
135
136 public:
137         /// e.g., Read_Fault for a read-only page.
138         MSA_Page_Fault_t state;
139         
140         /// If true, this page is locked in memory.
141         ///   Pages get locked so people can safely use the non-checking version of "get".
142         bool locked;
143         
144         /// Threads waiting for this page to be paged in from the network.
145         MSA_Listeners readRequests;
146         /// Threads waiting for this page to be paged out to the network.
147         MSA_Listeners writeRequests;
148         
149         /// Return true if this page can be safely written back.
150         bool canPageOut(void) const {
151                 return (!locked) && canDelete();
152         }
153         
154         /// Return true if this page can be safely purged from memory.
155         bool canDelete(void) const {
156                 return (readRequests.size()==0) && (writeRequests.size()==0);
157         }
158         
159         MSA_Page_StateT()
160                 : writes(), writes2(), state(Uninit_State), locked(false),
161                   readRequests(), writeRequests()
162                 { }
163
164         /// Write entry i of this page.
165         void write(unsigned int i) {
166                 writes.set(i);
167                 writes2.set(i/writes_t::store_bits);
168         }
169         
170         /// Clear the write list for this page.
171         void writeClear(void) {
172                 for (int i2=0;i2<writes2_t::len;i2++)
173                         if (writes2.store[i2]) { /* some bits set: clear them all */
174                                 int o=i2*writes2_t::store_bits;
175                                 for (int i=0;i<writes_t::len;i++) 
176                                         writes.store[o+i]=0;
177                                 writes2.store[i2]=0;
178                         }
179         }
180         
181         /// Return the nearest multiple of m >= v.
182         inline int roundUp(int v,int m) {
183                 return (v+m-1)/m*m;
184         }
185         
186         /// Get a list of our written output values as this list of spans.
187         ///   Returns the total number of spans written to "span".
188         int writeSpans(MSA_WriteSpan_t *span) {
189                 int nSpans=0;
190                 
191                 int cur=0; // entry we're looking at
192                 while (true) {
193                         /* skip over unwritten space */
194                         while (true) { 
195                                 if (writes2.store[cur/writes2_bits]==(writes2_store_t)0) 
196                                         cur=roundUp(cur+1,writes2_bits);
197                                 else if (writes.store[cur/writes_bits]==(writes_store_t)0)
198                                         cur=roundUp(cur+1,writes_bits); 
199                                 else if (writes.test(cur)==false)
200                                         cur++;
201                                 else /* writes.test(cur)==true */
202                                         break;
203                                 if (cur>=ENTRIES_PER_PAGE) return nSpans;
204                         }
205                         /* now writes.test(cur)==true */
206                         span[nSpans].start=cur;
207                         /* skip over written space */
208                         while (true) { 
209                                 /* // 0-1 symmetry doesn't hold here, since writes2 may have 1's, but writes may still have some 0's...
210                                    if (writes2.store[cur/writes2_bits]==~(writes2_store_t)0) 
211                                    cur=roundUp(cur+1,writes2_bits);
212                                    else */
213                                 if (writes.store[cur/writes_bits]==~(writes_store_t)0)
214                                         cur=roundUp(cur+1,writes_bits); 
215                                 else if (writes.test(cur)==true)
216                                         cur++;
217                                 else /* writes.test(cur)==false */
218                                         break;
219                                 if (cur>=ENTRIES_PER_PAGE) {
220                                         span[nSpans++].end=ENTRIES_PER_PAGE; /* finish the last span */
221                                         return nSpans;
222                                 }
223                         }
224                         /* now writes.test(cur)==false */
225                         span[nSpans++].end=cur;
226                 }
227         }
228 };
229
230
231 //=======================================================
232 // Page-out policy
233
234 /**
235    class vmPageReplacementPolicy
236    Abstract base class providing the interface to the various page
237    replacement policies available for use with an MSA
238 */
239 template <class ENTRY_TYPE, unsigned int ENTRIES_PER_PAGE>
240 class MSA_PageReplacementPolicy
241 {
242 public:
243         /// Note that a page was just accessed
244         virtual void pageAccessed(unsigned int page) = 0;
245
246         /// Ask for the index of a page to discard
247         virtual unsigned int selectPage() = 0;
248 };
249
250 /**
251    class vmLRUPageReplacementPolicy
252    This class provides the functionality of least recently used page replacement policy.
253    It needs to be notified when a page is accessed using the pageAccessed() function and
254    a page can be selected for replacement using the selectPage() function.
255  
256    WARNING: a list is absolutely the wrong data structure for this class, 
257    because it makes *both* updating as well as searching for a page O(n),
258    where n is the number of pages.  A heap would be a better choice,
259    as both operations would then become O(lg(n))
260 */
261 template <class ENTRY_TYPE, unsigned int ENTRIES_PER_PAGE>
262 class vmLRUReplacementPolicy : public MSA_PageReplacementPolicy <ENTRY_TYPE, ENTRIES_PER_PAGE>
263 {
264 protected:
265     unsigned int nPages;            // number of pages
266         const std::vector<ENTRY_TYPE *> &pageTable; // actual data for pages (NULL means page is gone)
267         typedef MSA_Page_StateT<ENTRY_TYPE, ENTRIES_PER_PAGE> pageState_t;
268         const std::vector<pageState_t *> &pageState;  // state of each page
269     std::list<unsigned int> stackOfPages;
270     unsigned int lastPageAccessed;
271
272 public:
273         inline vmLRUReplacementPolicy(unsigned int nPages_, 
274                                                                   const std::vector<ENTRY_TYPE *> &pageTable_, 
275                                                                   const std::vector<pageState_t *> &pageState_)
276                 : nPages(nPages_), pageTable(pageTable_), pageState(pageState_), lastPageAccessed(MSA_INVALID_PAGE_NO) {}
277
278     inline void pageAccessed(unsigned int page)
279                 {
280                         if(page != lastPageAccessed)
281                         {
282                                 lastPageAccessed = page;
283
284                                 // delete this page from the stack and push it at the top
285                                 std::list<unsigned int>::iterator i;
286                                 for(i = stackOfPages.begin(); i != stackOfPages.end(); i++)
287                                         if(*i == page)
288                                                 i = stackOfPages.erase(i);
289
290                                 stackOfPages.push_back(page);
291                         }
292                 }
293
294     inline unsigned int selectPage()
295                 {
296                         if(stackOfPages.size() == 0)
297                                 return MSA_INVALID_PAGE_NO;
298
299                         // find a non-empty unlocked page to swap, delete all empty pages from the stack
300                         std::list<unsigned int>::iterator i = stackOfPages.begin();
301                         while(i != stackOfPages.end())
302                         {
303                                 if(pageTable[*i] == NULL) i = stackOfPages.erase(i);
304                                 else if(!pageState[*i]->canPageOut()) i++;
305                                 else break;
306                         }
307
308                         if(i != stackOfPages.end())
309                                 return *i;
310                         else
311                                 return MSA_INVALID_PAGE_NO;
312                 }
313 };
314
315 /**
316    class vmNRUPageReplacementPolicy
317    This class provides the functionality of not-recently-used page replacement policy.
318    It needs to be notified when a page is accessed using the pageAccessed() function and
319    a page can be selected for replacement using the selectPage() function.
320   
321    "not-recently-used" could replace any page that has not been used in the 
322    last K accesses; that is, it's a memory-limited version of LRU.
323   
324    pageAccessed is O(1).
325    selectPage best-case is O(K) (if we immediately find a doomed page); 
326    worst-case is O(K n) (if there are no doomed pages).
327 */
328 template <class ENTRY_TYPE, unsigned int ENTRIES_PER_PAGE>
329 class vmNRUReplacementPolicy : public MSA_PageReplacementPolicy <ENTRY_TYPE, ENTRIES_PER_PAGE>
330 {
331 protected:
332         unsigned int nPages;            // number of pages
333         const std::vector<ENTRY_TYPE *> &pageTable; // actual pages (NULL means page is gone)
334         typedef MSA_Page_StateT<ENTRY_TYPE, ENTRIES_PER_PAGE> pageState_t;
335         const std::vector<pageState_t *> &pageState;  // state of each page
336     enum {K=5}; // Number of distinct pages to remember
337     unsigned int last[K]; // pages that have been used recently
338     unsigned int Klast; // index into last array.
339     
340     unsigned int victim; // next page to throw out.
341     
342     bool recentlyUsed(unsigned int page) {
343         for (int k=0;k<K;k++) if (page==last[k]) return true;
344         return false;
345     }
346
347 public:
348         inline vmNRUReplacementPolicy(unsigned int nPages_, 
349                                                                   const std::vector<ENTRY_TYPE *> &pageTable_, 
350                                                                   const std::vector<pageState_t *> &pageState_)
351                 : nPages(nPages_), pageTable(pageTable_), pageState(pageState_), Klast(0), victim(0)
352                 {
353                         for (int k=0;k<K;k++) last[k]=MSA_INVALID_PAGE_NO;
354                 }
355
356     inline void pageAccessed(unsigned int page)
357                 {
358                         if (page!=last[Klast]) {
359                                 Klast++; if (Klast>=K) Klast=0;
360                                 last[Klast]=page;
361                         }
362                 }
363
364     inline unsigned int selectPage() {
365         unsigned int last_victim=victim;
366         do {
367             victim++; if (victim>=nPages) victim=0;
368             if (pageTable[victim]
369                 &&pageState[victim]->canPageOut()
370                 &&!recentlyUsed(victim)) {
371                 /* victim is an allocated, unlocked, non-recently-used page: page him out. */
372                 return victim;
373             }
374         } while (victim!=last_victim);
375         return MSA_INVALID_PAGE_NO;  /* nobody is pageable */
376     }
377 };
378
379 //================================================================
380
381 /**
382    UNUSED
383
384    Holds the untyped data for one MSA page.
385    This is the interface MSA_CacheGroup uses to access a cached page.
386    MSA_CacheGroup asks the templated code to create a MSA_Page
387    for each new page, then talks to the page directly.
388 */
389 class MSA_Page {
390 public:
391         virtual ~MSA_Page();
392
393         /**
394            Pack or unpack the data in this page.
395            Used to send and receive pages from the network
396            (or even disk, if somebody needs it.)
397         */
398         virtual void pup(PUP::er &p) =0;
399
400         /**
401            Merge this page's data into our own.
402            Only parts of this page may have been set.
403         */
404         virtual void merge(MSA_Page &otherPage) =0;
405 };
406
407 /**
408    Holds the typed data for one MSA page.
409    Implementation of puppedPage used by the templated code.
410 */
411 template <
412         class ENTRY, 
413         class MERGER=DefaultEntry<ENTRY>,
414         unsigned int ENTRIES_PER_PAGE=MSA_DEFAULT_ENTRIES_PER_PAGE
415         >
416 class MSA_PageT {
417     unsigned int n; // number of entries on this page.  Used to send page updates.
418         /** The contents of this page: array of ENTRIES_PER_PAGE items */
419         ENTRY *data;
420         /** Merger object */
421         MERGER m;
422         bool duplicate;
423
424 public:
425
426         MSA_PageT()
427                 : n(ENTRIES_PER_PAGE), data(new ENTRY[ENTRIES_PER_PAGE]), duplicate(false)
428                 {
429                         for (int i=0;i<ENTRIES_PER_PAGE;i++){
430                                 data[i]=m.getIdentity();
431                         }
432                 }
433
434     // This constructor is used in PageArray to quickly convert an
435     // array of ENTRY into an MSA_PageT.  So we just make a copy of
436     // the pointer.  When it comes time to destruct the object, we
437     // need to ensure we do NOT delete the data but just discard the
438     // pointer.
439         MSA_PageT(ENTRY *d):data(d), duplicate(true), n(ENTRIES_PER_PAGE) {
440     }
441         MSA_PageT(ENTRY *d, unsigned int n_):data(d), duplicate(true), n(n_) {
442     }
443         virtual ~MSA_PageT() {
444                 if (!duplicate) {
445             delete [] data;
446         }
447         }
448
449         virtual void pup(PUP::er &p) {
450                 p | n;
451                 /*this pup routine was broken, It didnt consider the case
452                   in which n > 0 and data = NULL. This is possible when  
453                   sending empty pages. It also doesnt seem to do any allocation
454                   for the data variable while unpacking which seems to be wrong
455                 */
456                 bool nulldata;
457                 if(!p.isUnpacking()){
458                         nulldata = (data == NULL);
459                 }
460                 p | nulldata;
461                 if(nulldata){
462                         data = NULL;
463                         return;
464                 }
465                 if(p.isUnpacking()){
466                         data = new ENTRY[n];
467                 }
468                 for (int i=0;i<n;i++){
469                         p|data[i];
470                 }       
471         }
472
473         virtual void merge(MSA_PageT<ENTRY, MERGER, ENTRIES_PER_PAGE> &otherPage) {
474                 for (int i=0;i<ENTRIES_PER_PAGE;i++)
475                         m.accumulate(data[i],otherPage.data[i]);
476         }
477
478         // These accessors might be used by the templated code.
479         inline ENTRY &operator[](int i) {return data[i];}
480         inline const ENTRY &operator[](int i) const {return data[i];}
481     inline ENTRY *getData() { return data; }
482 };
483
484 //=============================== Cache Manager =================================
485
486 template <class ENTRY_TYPE, class ENTRY_OPS_CLASS,unsigned int ENTRIES_PER_PAGE>
487 class MSA_CacheGroup : public Group
488 {
489     typedef MSA_PageT<ENTRY_TYPE, ENTRY_OPS_CLASS, ENTRIES_PER_PAGE> page_t;
490
491 protected:
492     ENTRY_OPS_CLASS *entryOpsObject;
493     unsigned int numberOfWorkerThreads;      // number of worker threads across all processors for this shared array
494     // @@ migration?
495     unsigned int numberLocalWorkerThreads;   // number of worker threads on THIS processor for this shared array
496     unsigned int enrollDoneq;                 // has enroll() been done on this processor?
497     MSA_Listeners enrollWaiters;
498     MSA_Listeners syncWaiters;
499     std::set<int> enrolledPEs;                          // which PEs are involved?
500
501     unsigned int nPages;            ///< number of pages
502         std::vector<ENTRY_TYPE*> pageTable;          ///< the page table for this PE: stores actual data.
503     typedef MSA_Page_StateT<ENTRY_TYPE,ENTRIES_PER_PAGE> pageState_t;
504         std::vector<pageState_t *> pageStateStorage; ///< Housekeeping information for each allocated page.
505     
506     std::stack<ENTRY_TYPE*> pagePool;     // a pool of unused pages
507     
508         typedef vmNRUReplacementPolicy<ENTRY_TYPE, ENTRIES_PER_PAGE> vmPageReplacementPolicy;
509     MSA_PageReplacementPolicy<ENTRY_TYPE, ENTRIES_PER_PAGE> *replacementPolicy;
510
511     // structure for the bounds of a single write
512     typedef struct { unsigned int begin; unsigned int end; } writebounds_t;
513
514     // a list of write bounds associated with a given page
515     typedef std::list<writebounds_t> writelist_t;
516
517     writelist_t** writes;           // the write lists for each page
518
519     unsigned int resident_pages;             // pages currently allocated
520     unsigned int max_resident_pages;         // max allowable pages to allocate
521     unsigned int nEntries;          // number of entries for this array
522     unsigned int syncAckCount;      // number of sync ack's we received
523     int outOfBufferInPrefetch;      // flag to indicate if the last prefetch ran out of buffers
524
525     int syncThreadCount;            // number of local threads that have issued Sync
526     
527     
528     // used during output
529     MSA_WriteSpan_t writeSpans[ENTRIES_PER_PAGE];
530     ENTRY_TYPE writeEntries[ENTRIES_PER_PAGE];
531
532     typedef CProxy_MSA_PageArray<ENTRY_TYPE, ENTRY_OPS_CLASS, ENTRIES_PER_PAGE> CProxy_PageArray_t;
533     CProxy_PageArray_t pageArray;     // a proxy to the page array
534     typedef CProxy_MSA_CacheGroup<ENTRY_TYPE, ENTRY_OPS_CLASS, ENTRIES_PER_PAGE> CProxy_CacheGroup_t;
535     CProxy_CacheGroup_t thisProxy; // a proxy to myself.
536
537     std::map<CthThread, MSA_Thread_Listener *> threadList;
538
539     /// Return the state for this page, returning NULL if no state available.
540     inline pageState_t *stateN(unsigned int pageNo) {
541         return pageStateStorage[pageNo];
542     }
543     
544         /// Return the state for this page, allocating if needed.
545         pageState_t *state(unsigned int pageNo)
546                 {
547                         pageState_t *ret=pageStateStorage[pageNo];
548                         if (ret==NULL)
549                         {
550                                 ret=new pageState_t;
551                                 pageStateStorage[pageNo]=ret;
552                         }
553                         return ret;
554                 }
555
556     /// Look up or create the listener for the current thread.
557     MSA_Thread_Listener *getListener(void) {
558         CthThread t=CthSelf();
559         MSA_Thread_Listener *l=threadList[t];
560                 if (l==NULL) {
561                 l=new MSA_Thread_Listener;
562                 threadList[t]=l;
563                 }
564                 return l;
565     }
566     /// Add our thread to this list and suspend
567     void addAndSuspend(MSA_Listeners &dest) {
568         MSA_Thread_Listener *l=getListener();
569                 dest.add(l);
570                 l->suspend();
571     }
572
573     /*********************************************************************************/
574     /** these routines deal with managing the page queue **/
575
576     // increment the number of pages the thread is waiting on.
577     // also add thread to the page queue; then thread is woken when the page arrives.
578     inline void IncrementPagesWaiting(unsigned int page)
579                 {
580                         state(page)->readRequests.add(getListener());
581                 }
582
583     inline void IncrementChangesWaiting(unsigned int page)
584                 {
585                         state(page)->writeRequests.add(getListener());
586                 }
587
588 /************************* Page allocation and management **************************/
589     
590     /// Allocate a new page, removing old pages if we're over the limit.
591     /// Returns NULL if no buffer space is available
592     inline ENTRY_TYPE* tryBuffer(int async=0) // @@@
593                 {
594                         ENTRY_TYPE* nu = NULL;
595
596                         // first try the page pool
597                         if(!pagePool.empty())
598                         {
599                                 nu = pagePool.top();
600                                 pagePool.pop();
601                         }
602
603                         // else try to allocate the buffer
604                         if(nu == NULL && resident_pages < max_resident_pages)
605                         {
606                                 nu = new ENTRY_TYPE[ENTRIES_PER_PAGE];
607                                 resident_pages++;
608                         }
609
610                         // else swap out one of the pages
611                         if(nu == NULL)
612                         {
613                                 int pageToSwap = replacementPolicy->selectPage();
614                                 if(pageToSwap != MSA_INVALID_PAGE_NO)
615                                 {
616                                         CkAssert(pageTable[pageToSwap] != NULL);
617                                         CkAssert(state(pageToSwap)->canPageOut() == true);
618                 
619                                         relocatePage(pageToSwap, async);
620                                         nu = pageTable[pageToSwap];
621                                         pageTable[pageToSwap] = 0;
622                                         delete pageStateStorage[pageToSwap];
623                                         pageStateStorage[pageToSwap]=0;
624                                 }
625                         }
626
627                         // otherwise return NULL
628
629                         return nu;
630                 }
631     
632     /// Allocate storage for this page, if none has been allocated already.
633     ///  Update pageTable, and return the storage for the page.
634     inline ENTRY_TYPE* makePage(unsigned int page) // @@@
635                 {
636                         ENTRY_TYPE* nu=pageTable[page];
637                         if (nu==0) {
638                                 nu=tryBuffer();
639                                 if (nu==0) CkAbort("MSA: No available space to create pages.\n");
640                                 pageTable[page]=nu;
641                         }
642                         return nu;
643                 }
644     
645     /// Throw away this allocated page.
646     ///  Returns the page itself, for deletion or recycling.
647     ENTRY_TYPE* destroyPage(unsigned int page)
648                 {
649                         ENTRY_TYPE* nu=pageTable[page];
650                         pageTable[page] = 0;
651                         if (pageStateStorage[page]->canDelete()) {
652                                 delete pageStateStorage[page];
653                                 pageStateStorage[page]=0;
654                         }
655                         resident_pages--;
656                         return nu;
657                 }
658     
659     //MSA_CacheGroup::
660     void pageFault(unsigned int page, MSA_Page_Fault_t why)
661                 {
662                         // Write the page to the page table
663                         state(page)->state = why;
664                         if(why == Read_Fault)
665                         { // Issue a remote request to fetch the new page
666                                 // If the page has not been requested already, then request it.
667                                 if (stateN(page)->readRequests.size()==0) {
668                                         pageArray[page].GetPage(CkMyPe());
669                                         //ckout << "Requesting page first time"<< endl;
670                                 } else {
671                                         ;//ckout << "Requesting page next time.  Skipping request."<< endl;
672                                 }
673                                 MSA_Thread_Listener *l=getListener();
674                                 stateN(page)->readRequests.add(l);
675                                 l->suspend(); // Suspend until page arrives.
676                         }
677                         else {
678                                 // Build an empty buffer into which to create the new page
679                                 ENTRY_TYPE* nu = makePage(page);
680                                 writeIdentity(nu);
681                         }
682                 }
683     
684     /// Make sure this page is accessible, faulting the page in if needed.
685     // MSA_CacheGroup::
686     inline void accessPage(unsigned int page,MSA_Page_Fault_t access)
687                 {
688                         if (pageTable[page] == 0) {
689 //             ckout << "p" << CkMyPe() << ": Calling pageFault" << endl;
690                                 pageFault(page, access);
691                         }
692 #ifndef CMK_OPTIMIZE
693                         if (stateN(page)->state!=access) {
694                                 CkPrintf("page=%d mode=%d pagestate=%d", page, access, stateN(page)->state);
695                                 CkAbort("MSA Runtime error: Attempting to access a page that is still in another mode.");
696                         }
697 #endif
698                         replacementPolicy->pageAccessed(page);
699                 }
700
701     // MSA_CacheGroup::
702     // Fill this page with identity values, to prepare for writes or 
703     //  accumulates.
704     void writeIdentity(ENTRY_TYPE* pagePtr)
705                 {
706                         for(unsigned int i = 0; i < ENTRIES_PER_PAGE; i++)
707                                 pagePtr[i] = entryOpsObject->getIdentity();
708                 }
709     
710 /************* Page Flush and Writeback *********************/
711     bool shouldWriteback(unsigned int page) {
712         if (!pageTable[page]) return false;
713                 return (stateN(page)->state == Write_Fault || stateN(page)->state == Accumulate_Fault);
714     }
715     
716     inline void relocatePage(unsigned int page, int async)
717                 {
718                         //CkAssert(pageTable[page]);
719                         if(shouldWriteback(page))
720                         {
721                                 // the page to be swapped is a writeable page. So inform any
722                                 // changes this node has made to the page manager
723                                 sendChangesToPageArray(page, async);
724                         }
725                 }
726
727     inline void sendChangesToPageArray(const unsigned int page, const int async)
728                 {
729                         sendRLEChangesToPageArray(page);
730         
731                         MSA_Thread_Listener *l=getListener();
732                         state(page)->writeRequests.add(l);
733                         if (!async)
734                                 l->suspend(); // Suspend until page is really gone.
735                         // TODO: Are write acknowledgements really necessary ?
736                 }
737
738     // Send the page data as a contiguous block.
739     //   Note that this is INCORRECT when writes to pages overlap!
740     inline void sendNonRLEChangesToPageArray(const unsigned int page) // @@@
741                 {
742                         pageArray[page].PAReceivePage(pageTable[page], ENTRIES_PER_PAGE, CkMyPe(), stateN(page)->state);
743                 }
744     
745     // Send the page data as an RLE block.
746     // this function assumes that there are no overlapping writes in the list
747     inline void sendRLEChangesToPageArray(const unsigned int page)
748                 {
749                         ENTRY_TYPE *writePage=pageTable[page];
750                         int nSpans=stateN(page)->writeSpans(writeSpans);
751                         if (nSpans==1) 
752                         { /* common case: can make very fast */
753                                 int nEntries=writeSpans[0].end-writeSpans[0].start;
754                                 if (entryOpsObject->pupEveryElement()) {
755                                         pageArray[page].PAReceiveRLEPageWithPup(writeSpans,nSpans,
756                                                                                                                         page_t(&writePage[writeSpans[0].start],nEntries),nEntries,
757                                                                                                                         CkMyPe(),stateN(page)->state);
758                                 } else {
759                                         pageArray[page].PAReceiveRLEPage(writeSpans,nSpans,
760                                                                                                          &writePage[writeSpans[0].start], nEntries,
761                                                                                                          CkMyPe(),stateN(page)->state);
762                                 }
763                         } 
764                         else /* nSpans>1 */ 
765                         { /* must copy separate spans into a single output buffer (luckily rare) */
766                                 int nEntries=0;
767                                 for (int s=0;s<nSpans;s++) {
768                                         for (int i=writeSpans[s].start;i<writeSpans[s].end;i++)
769                                                 writeEntries[nEntries++]=writePage[i]; // calls assign
770                                 }
771                                 if (entryOpsObject->pupEveryElement()) {
772                                         pageArray[page].PAReceiveRLEPageWithPup(writeSpans,nSpans,
773                                                                                                                         page_t(writeEntries,nEntries),nEntries,
774                                                                                                                         CkMyPe(),stateN(page)->state);
775                                 } else {
776                                         pageArray[page].PAReceiveRLEPage(writeSpans,nSpans,
777                                                                                                          writeEntries,nEntries,
778                                                                                                          CkMyPe(),stateN(page)->state);
779                                 }
780                         }
781                 }
782
783 /*********************** Public Interface **********************/
784 public:
785     // 
786     //
787     // MSA_CacheGroup::
788         inline MSA_CacheGroup(unsigned int nPages_,
789                                                   unsigned int max_bytes_,
790                                                   unsigned int nEntries_,
791                                                   unsigned int numberOfWorkerThreads_)
792                 : numberOfWorkerThreads(numberOfWorkerThreads_),
793                   nPages(nPages_),
794                   nEntries(nEntries_), 
795                   pageTable(nPages, NULL),
796                   pageStateStorage(nPages, NULL),
797                   pageArray(CProxy_PageArray_t::ckNew(nPages_)),
798                   thisProxy(thisgroup),
799                   max_resident_pages(max_bytes_/(sizeof(ENTRY_TYPE)*ENTRIES_PER_PAGE)),
800                   entryOpsObject(new ENTRY_OPS_CLASS),
801                   replacementPolicy(new vmPageReplacementPolicy(nPages, pageTable, pageStateStorage)),
802                   outOfBufferInPrefetch(0), syncAckCount(0),syncThreadCount(0),
803                   resident_pages(0),numberLocalWorkerThreads(0), enrollDoneq(0)
804                 {
805                         pageArray.setCacheProxy(thisProxy);
806                         pageArray.ckSetReductionClient(new CkCallback(CkIndex_MSA_CacheGroup<ENTRY_TYPE, ENTRY_OPS_CLASS, ENTRIES_PER_PAGE>::SyncDone(), thisProxy));
807
808                         MSADEBPRINT(printf("MSA_CacheGroup nEntries %d \n",nEntries););
809                 }
810
811     // MSA_CacheGroup::
812     inline ~MSA_CacheGroup()
813                 {
814                         FreeMem();
815                 }
816
817     /* To change the accumulate function TBD @@ race conditions */
818     inline void changeEntryOpsObject(ENTRY_OPS_CLASS *e) {
819         entryOpsObject = e;
820         pageArray.changeEntryOpsObject(e);
821     }
822
823     // MSA_CacheGroup::
824     inline const ENTRY_TYPE* readablePage(unsigned int page)
825                 {
826                         accessPage(page,Read_Fault);
827         
828                         return pageTable[page];
829                 }
830
831     // MSA_CacheGroup::
832     //
833     // known local page
834     inline const void* readablePage2(unsigned int page)
835                 {
836                         return pageTable[page];
837                 }
838
839     // MSA_CacheGroup::
840     // Obtains a writable copy of the page.
841     inline ENTRY_TYPE* writeablePage(unsigned int page, unsigned int offset)
842                 {
843                         accessPage(page,Write_Fault);
844
845                         // NOTE: Since we assume write once semantics, i.e. between two calls to sync,
846                         // either there can be no write to a location or a single write to a location,
847                         // a readable page will suffice as a writeable page too, because no one else
848                         // is going to write to this location. In reality, two locations on the *same*
849                         // page can be written by two different threads, in which case we will need
850                         // to keep track of which parts of the page have been written, hence:
851                         stateN(page)->write(offset);
852 //     ckout << "write:" << page*ENTRIES_PER_PAGE+offset << endl;
853         
854                         return pageTable[page];
855                 }
856
857     // MSA_CacheGroup::
858     inline ENTRY_TYPE &accumulate(unsigned int page, unsigned int offset)
859                 {
860                         accessPage(page,Accumulate_Fault);
861                         stateN(page)->write(offset);
862                         return pageTable[page][offset];
863                 }
864
865     /// A requested page has arrived from the network.
866     ///  nEntriesInPage_ = num entries being sent (0 for empty page, num entries otherwise)
867     inline void ReceivePageWithPUP(unsigned int page, page_t &pageData, int size)
868                 {
869                         ReceivePage(page, pageData.getData(), size);
870                 }
871
872     inline void ReceivePage(unsigned int page, ENTRY_TYPE* pageData, int size)
873                 {
874                         CkAssert(0==size || ENTRIES_PER_PAGE == size);
875                         // the page we requested has been received
876                         ENTRY_TYPE *nu=makePage(page);
877                         if(size!=0)
878                         {
879                                 for(unsigned int i = 0; i < size; i++)
880                                         nu[i] = pageData[i]; // @@@, calls assignment operator
881                         }
882                         else /* isEmpty */
883                         {
884                                 // the page we requested for is empty, so we can just initialize it.
885                                 writeIdentity(nu);
886                         }
887         
888                         state(page)->readRequests.signal(page);
889                 }
890
891     // This EP is invoked during sync to acknowledge that a dirty page
892     // has been received and written back to the page owner.  We keep track
893     // of the number of ack's yet to arrive in nChangesWaiting.  Once
894     // all the dirty pages have been ack'd, we awaken the thread that
895     // flushed the page.
896     //
897     // It's not clear this is useful very often...
898     //
899     // MSA_CacheGroup::
900     inline void AckPage(unsigned int page)
901                 {
902                         state(page)->writeRequests.signal(page);
903                 }
904
905     // MSA_CacheGroup::
906     // synchronize all the pages and also clear up the cache
907     inline void SyncReq(int single)
908                 {
909                         MSADEBPRINT(printf("SyncReq single %d\n",single););
910                         if(single)
911                         {
912                                 /*ask all the caches to send their updates to the page
913                                  * array, but we don't need to empty the caches on the
914                                  * other PEs*/
915                                 SingleSync();
916                                 EmptyCache();
917
918                                 getListener()->suspend();
919                         }
920                         else{
921                                 Sync();
922                         }
923                 }
924
925     // MSA_CacheGroup::
926     inline void FlushCache()
927                 {
928                         // flush the local cache
929                         // for each writeable page, send that page to the array element
930                         for(unsigned int i = 0; i < nPages; i++)
931                         {
932                                 if(shouldWriteback(i)) {
933                                         //ckout << "p" << CkMyPe() << "FlushCache: sending page " << i << endl;
934                                         sendChangesToPageArray(i, 1);
935                                 }
936                         }
937                 }
938
939     // MSA_CacheGroup::
940     void EmptyCache()
941                 {
942                         /* just makes all the pages empty, assuming that the data
943                          * in those pages has been flushed to the owners */
944                         for(unsigned int i = 0; i < nPages; i++)
945                         {
946                                 if(pageTable[i]) pagePool.push(destroyPage(i));
947                         }
948                 }
949
950 /************************ Enroll ********************/
951     /// Enroll phase 1: called by users.
952     // MSA_CacheGroup::
953     inline void enroll(unsigned int num_workers)
954                 {
955                         CkAssert(num_workers == numberOfWorkerThreads); // just to verify
956                         CkAssert(enrollDoneq == 0);
957                         numberLocalWorkerThreads++;
958                         // @@ how to ensure that enroll is called only once?
959
960                         //ckout << "[" << CkMyPe() << "] sending sync ack to PE 0" << endl;
961                         thisProxy[0].enrollAck(CkMyPe());
962                         //ckout << "[" << CkMyPe() << "] suspening thread in Sync() " << endl;
963                         addAndSuspend(enrollWaiters);
964                         //ckout << "[" << CkMyPe() << "] rsuming thread in Sync()" << endl;
965
966                         CkAssert(enrollDoneq == 1);
967                         return;
968                 }
969
970     /// Enroll phase 2: called on PE 0 from everywhere
971     inline void enrollAck(int originator)
972                 {
973                         CkAssert(CkMyPe() == 0);  // enrollAck is only called on PE 0
974                         CkAssert(enrollDoneq == 0);  // prevent multiple enroll operations
975         
976                         syncAckCount++;
977                         enrolledPEs.insert(originator);
978                         //ckout << "[" << CkMyPe() << "] SyncAckcount = " << syncAckCount << endl;
979                         if(syncAckCount == numberOfWorkerThreads) {
980 //             ckout << "[" << CkMyPe() << "]" << "Enroll operation is almost done" << endl;
981                                 syncAckCount = 0;
982                                 enrollDoneq = 1;
983                                 // What if fewer worker threads than pe's ?  Handled in
984                                 // enrollDone.
985                                 thisProxy.enrollDone();
986                         }
987                 }
988
989     /// Enroll phase 3: called everywhere by PE 0
990     inline void enrollDone()
991                 {
992 //         ckout << "[" << CkMyPe() << "] enrollDone.  Waking threads."
993 //               <<  " numberOfWorkerThreads=" << numberOfWorkerThreads
994 //               <<  " local=" << numberLocalWorkerThreads << endl;
995                         enrollDoneq = 1;
996                         enrollWaiters.signal(0);
997                 }
998
999 /******************************** Sync & writeback ***********************/
1000     // MSA_CacheGroup::
1001     inline void SingleSync()
1002                 {
1003                         /* a single thread issued a sync call with all = 1. The
1004                          * first thing to do is to flush the local cache */
1005                         FlushCache();
1006                 }
1007
1008     // MSA_CacheGroup::
1009     inline void Sync()
1010                 {
1011                         syncThreadCount++;
1012                         //ckout << "[" << CkMyPe() << "] syncThreadCount = " << syncThreadCount << " " << numberLocalWorkerThreads << endl;
1013                         //ckout << "[" << CkMyPe() << "] syncThreadCount = " << syncThreadCount << ", registered threads = " << getNumRegisteredThreads()
1014                         //  << ", number of suspended threads = " << getNumSuspendedThreads() << endl;
1015
1016                         // First, all threads on this processor need to reach the sync
1017                         // call; only then can we proceed with merging the data.  Only
1018                         // the last thread on this processor needs to do the FlushCache,
1019                         // etc.  Others just suspend until the sync is over.
1020                         MSADEBPRINT(printf("Sync syncThreadCount %d \n",syncThreadCount););
1021                         if(syncThreadCount < numberLocalWorkerThreads)
1022                         {
1023                                 MSADEBPRINT(printf("Sync addAndSuspend \n"););
1024                                 addAndSuspend(syncWaiters);
1025                                 return;
1026                         }
1027                 
1028                         //ckout << "[" << CkMyPe() << "] Sync started" << endl;
1029
1030                         // flush the cache asynchronously and also empty it
1031                         FlushCache();
1032                         // idea: instead of invalidating the pages, switch it to read
1033                         // mode. That will not work, since the page may have also been
1034                         // modified by another thread.
1035                         EmptyCache();
1036
1037                         // Now, we suspend too (if we had at least one dirty page).
1038                         // We will be awoken when all our dirty pages have been
1039                         // written and acknowledged.
1040                         MSADEBPRINT(printf("Sync calling suspend on getListener\n"););
1041                         getListener()->suspend();
1042                         MSADEBPRINT(printf("Sync awakening after suspend\n"););
1043
1044                         // So far, the sync has been asynchronous, i.e. PE0 might be ahead
1045                         // of PE1.  Next we basically do a barrier to ensure that all PE's
1046                         // are synchronized.
1047
1048                         // at this point, the sync's across the group should
1049                         // synchronize among themselves by each one sending
1050                         // a sync acknowledge message to PE 0. (this is like
1051                         // a reduction over a group)
1052                         if(CkMyPe() != 0)
1053                         {
1054                                 thisProxy[0].SyncAck();
1055                         }
1056                         else /* I *am* PE 0 */
1057                         {
1058                                 SyncAck();
1059                         }
1060                         MSADEBPRINT(printf("Sync all local threads done, going to addAndSuspend\n"););
1061                         /* Wait until sync is reflected from PE 0 */
1062                         addAndSuspend(syncWaiters);
1063                                 
1064                         MSADEBPRINT(printf("Sync all local threads done waking up after addAndSuspend\n"););
1065                         //ckout << "[" << CkMyPe() << "] Sync finished" << endl;        
1066                 }
1067
1068     inline unsigned int getNumEntries() { return nEntries; }
1069     inline CProxy_PageArray_t getArray() { return pageArray; }
1070
1071     // TODO: Can this SyncAck and other simple Acks be made efficient?
1072     inline void SyncAck()
1073                 {
1074                         CkAssert(CkMyPe() == 0);  // SyncAck is only called on PE 0
1075                         syncAckCount++;
1076                         // DONE @@ what if fewer worker threads than pe's ?
1077                         // @@ what if fewer worker threads than pe's and >1 threads on 1 pe?
1078                         //if(syncAckCount == min(numberOfWorkerThreads, CkNumPes())){
1079                         if (syncAckCount == enrolledPEs.size()) {
1080                                 MSADEBPRINT(printf("SyncAck starting reduction on pageArray of size %d number of pages %d\n",
1081                                                                    nEntries, nPages););
1082                                 pageArray.Sync();
1083                         }               
1084                 }
1085
1086     inline void SyncDone()
1087                 {
1088                         //ckout << "[" << CkMyPe() << "] Sync Done indication" << endl;
1089                         //ckout << "[" << CkMyPe() << "] Sync Done indication" << endl;
1090                         /* Reset for next sync */
1091                         syncThreadCount = 0;
1092                         syncAckCount = 0;
1093                         MSADEBPRINT(printf("SyncDone syncWaiters signal to be called\n"););
1094                         syncWaiters.signal(0);
1095                 }
1096
1097     inline void FreeMem()
1098                 {
1099                         for(unsigned int i = 0; i < nPages; i++)
1100                         {
1101                                 if(pageTable[i]) delete [] destroyPage(i);
1102                         }
1103
1104                         while(!pagePool.empty())
1105                         {
1106                                 delete [] pagePool.top();  // @@@
1107                                 pagePool.pop();
1108                         }
1109         
1110                         resident_pages=0;
1111                 }
1112
1113         /** 
1114                 Deregister a client. Decrement the number of local threads. If total number of local threads 
1115                 hits 0 FreeMem()
1116         */
1117         inline void unroll() {
1118                 numberLocalWorkerThreads--;
1119                 if(numberLocalWorkerThreads == 0){
1120                         FreeMem();
1121                 }
1122         }
1123
1124     /**
1125      * Issue a prefetch request for the given range of pages. These pages will
1126      * be locked into the cache, so that they will not be swapped out.
1127      */
1128     inline void Prefetch(unsigned int pageStart, unsigned int pageEnd)
1129                 {
1130                         /* prefetching is feasible only if we we did not encounter an out
1131                          * of buffer condition in the previous prefetch call
1132                          */
1133                         if(!outOfBufferInPrefetch)
1134                         {
1135                                 //ckout << "prefetching pages " << pageStart << " through " << pageEnd << endl;
1136                                 for(unsigned int p = pageStart; p <= pageEnd; p++)
1137                                 {
1138                                         if(NULL == pageTable[p])
1139                                         {
1140
1141                                                 /* relocate the buffer asynchronously */
1142                                                 ENTRY_TYPE* nu = tryBuffer(1);
1143                                                 if(NULL == nu)
1144                                                 {
1145                                                         /* signal that sufficient buffer space is not available */
1146                                                         outOfBufferInPrefetch = 1;
1147                                                         break;
1148                                                 }
1149
1150                                                 pageTable[p] = nu;
1151                                                 state(p)->state = Read_Fault;
1152
1153                                                 pageArray[p].GetPage(CkMyPe());
1154                                                 IncrementPagesWaiting(p);
1155                                                 //ckout << "Prefetch page" << p << ", pages waiting = " << nPagesWaiting << endl;
1156                                                 /* don't suspend the thread */
1157                                         }
1158
1159                                         /* mark the page as being locked */
1160                                         state(p)->locked = true;
1161                                 }
1162                         }
1163                 }
1164
1165     /**
1166      * Wait for all the prefetch pages to be fetched into the cache.
1167      * Returns: 0 if prefetch successful, 1 if not
1168      */
1169     inline int WaitAll(void)
1170                 {
1171                         if(outOfBufferInPrefetch)
1172                         {
1173                                 // we encountered out of buffer in the previous prefetch call, return error
1174                                 outOfBufferInPrefetch = 0;
1175                                 getListener()->suspend();
1176                                 UnlockPages();
1177                                 return 1;
1178                         }
1179                         else
1180                         {
1181                                 // prefetch requests have been successfully issued already, so suspend the
1182                                 // thread and wait for completion
1183                                 outOfBufferInPrefetch = 0;
1184                                 getListener()->suspend();
1185                                 return 0;
1186                         }
1187                 }
1188     
1189     inline void UnlockPage(unsigned int page) {
1190         pageState_t *s=stateN(page);
1191                 if(s && s->locked) {
1192             replacementPolicy->pageAccessed(page);
1193             s->locked = false;
1194                 }
1195     }
1196
1197     /**
1198      * Unlock all the pages locked in the cache
1199      */
1200     inline void UnlockPages()
1201                 {
1202                         // add all the locked pages to page replacement policy
1203                         for(unsigned int page = 0; page < nPages; page++)
1204                                 UnlockPage(page);
1205                 }
1206
1207     /**
1208      * Unlock the given pages: [startPage ... endPage]
1209      *  Note that the range is inclusive.
1210      */
1211     inline void UnlockPages(unsigned int startPage, unsigned int endPage)
1212                 {
1213                         for(unsigned int page = startPage; page <= endPage; page++)
1214                                 UnlockPage(page);
1215                 }
1216
1217     /// Debugging routine
1218     inline void emitBufferValue(int ID, unsigned int pageNum, unsigned int offset)
1219                 {
1220                         CkAssert( pageNum < nPages );
1221                         CkAssert( offset < ENTRIES_PER_PAGE );
1222
1223                         //ckout << "p" << CkMyPe() << "ID" << ID;
1224 //         if (pageTable[pageNum] == 0)
1225 //             ckout << "emitBufferValue: page " << pageNum << " not available in local cache." << endl;
1226 //         else
1227 //             ckout << "emitBufferValue: [" << pageNum << "," << offset << "] = " << pageTable[pageNum][offset] << endl;
1228                 }
1229 };
1230
1231 // each element of this array is responsible for managing
1232 // the information about a single page. It is in effect the
1233 // "owner" as well as the "manager" for that page.
1234 //
1235 template<class ENTRY_TYPE, class ENTRY_OPS_CLASS,unsigned int ENTRIES_PER_PAGE> 
1236 class MSA_PageArray : public ArrayElement1D
1237 {
1238     typedef CProxy_MSA_CacheGroup<ENTRY_TYPE, ENTRY_OPS_CLASS, ENTRIES_PER_PAGE> CProxy_CacheGroup_t;
1239     typedef MSA_PageT<ENTRY_TYPE, ENTRY_OPS_CLASS, ENTRIES_PER_PAGE> page_t;
1240     
1241 protected:
1242     ENTRY_TYPE *epage;
1243     ENTRY_OPS_CLASS entryOpsObject;
1244     CProxy_CacheGroup_t cache;
1245
1246     unsigned int pageNo() { return thisIndex; }
1247
1248     inline void allocatePage(MSA_Page_Fault_t access) // @@@
1249                 {
1250                         if(epage == NULL)
1251                         {
1252                                 epage = new ENTRY_TYPE[ENTRIES_PER_PAGE];
1253                                 if (access==Accumulate_Fault)
1254                                         writeIdentity();
1255                         }
1256                 }
1257
1258     // begin and end are indexes into the page.
1259     inline void set(const ENTRY_TYPE* buffer, unsigned int begin, unsigned int end)
1260                 {
1261                         //ckout << "set: " << begin << "," << end << endl;
1262                         for(unsigned int i = 0; i < (end - begin); i++) {
1263                                 epage[begin + i] = buffer[i]; // @@@, calls assignment operator
1264                                 //ckout << "set val[" << begin+i << "]=" << buffer[i] << endl;
1265                         }
1266                 }
1267
1268     // MSA_PageArray::
1269     inline void combine(const ENTRY_TYPE* buffer, unsigned int begin, unsigned int end)
1270                 {
1271                         ENTRY_TYPE* pagePtr = epage + begin;
1272                         for(unsigned int i = 0; i < (end - begin); i++)
1273                                 entryOpsObject.accumulate(pagePtr[i], buffer[i]);
1274                 }
1275
1276     // MSA_PageArray::
1277     inline void writeIdentity()
1278                 {
1279                         for(unsigned int i = 0; i < ENTRIES_PER_PAGE; i++)
1280                                 epage[i] = entryOpsObject.getIdentity();
1281                 }
1282
1283 public:
1284     inline MSA_PageArray() : epage(NULL) { }
1285     inline MSA_PageArray(CkMigrateMessage* m) { delete m; }
1286     
1287     void setCacheProxy(CProxy_CacheGroup_t &cache_)
1288                 {
1289                         cache=cache_;
1290                 }
1291     
1292     virtual void pup(PUP::er& p)
1293                 {
1294                         ArrayElement1D::pup(p);
1295                         int epage_present=(epage!=0);
1296                         p|epage_present;
1297                         if (epage_present) {
1298                                 if(p.isUnpacking())
1299                                         allocatePage(Write_Fault);
1300                                 for (int i=0;i<ENTRIES_PER_PAGE;i++)
1301                                         p|epage[i];
1302                         }
1303                 }
1304     
1305     inline ~MSA_PageArray()
1306                 {
1307                         if(epage) delete [] epage;
1308                 }
1309
1310     /// Request our page.
1311     ///   pe = to which to send page
1312     inline void GetPage(int pe)
1313                 {
1314                         if(epage == NULL) {
1315                                 // send empty page
1316                                 if (entryOpsObject.pupEveryElement())
1317                                         cache[pe].ReceivePageWithPUP(pageNo(), page_t((ENTRY_TYPE*)NULL), 0);
1318                                 else
1319                                         cache[pe].ReceivePage(pageNo(), (ENTRY_TYPE*)NULL, 0);
1320                         } else {
1321                                 // send page with data
1322                                 if (entryOpsObject.pupEveryElement())
1323                                         cache[pe].ReceivePageWithPUP(pageNo(), page_t(epage), ENTRIES_PER_PAGE);
1324                                 else
1325                                         cache[pe].ReceivePage(pageNo(), epage, ENTRIES_PER_PAGE);  // send page with data                
1326                         }
1327                 }
1328
1329     /// Receive a non-runlength encoded page from the network:
1330     // @@ TBD: ERROR: This does not work for  varsize pages.
1331     inline void PAReceivePage(ENTRY_TYPE *pageData,
1332                                                           int pe, MSA_Page_Fault_t pageState)
1333                 {
1334                         allocatePage(pageState);
1335
1336                         if(pageState == Write_Fault)
1337                                 set(pageData, 0, ENTRIES_PER_PAGE);
1338                         else
1339                                 combine(pageData, 0, ENTRIES_PER_PAGE);
1340         
1341                         // send the acknowledgement to the sender that we received the page
1342                         //ckout << "Sending Ack to PE " << pe << endl;
1343                         cache[pe].AckPage(thisIndex);
1344                 }
1345
1346     /// Receive a runlength encoded page from the network:
1347     inline void PAReceiveRLEPageWithPup(
1348         const MSA_WriteSpan_t *spans, unsigned int nSpans, 
1349         MSA_PageT<ENTRY_TYPE, ENTRY_OPS_CLASS, ENTRIES_PER_PAGE> &entries, unsigned int nEntries, 
1350         int pe, MSA_Page_Fault_t pageState)
1351                 {
1352                         PAReceiveRLEPage(spans, nSpans, entries.getData(), nEntries, pe, pageState);
1353                 }
1354
1355
1356     inline void PAReceiveRLEPage(
1357         const MSA_WriteSpan_t *spans, unsigned int nSpans, 
1358         const ENTRY_TYPE *entries, unsigned int nEntries, 
1359         int pe, MSA_Page_Fault_t pageState)
1360                 {
1361                         allocatePage(pageState);
1362         
1363                         //ckout << "p" << CkMyPe() << "ReceiveRLEPage nSpans=" << nSpans << " nEntries=" << nEntries << endl;
1364                         int e=0; /* consumed entries */
1365                         for (int s=0;s<nSpans;s++) {
1366                                 if(pageState == Write_Fault)
1367                                         set(&entries[e], spans[s].start,spans[s].end);
1368                                 else /* Accumulate_Fault */
1369                                         combine(&entries[e], spans[s].start,spans[s].end);
1370                                 e+=spans[s].end-spans[s].start;
1371                         } 
1372
1373                         // send the acknowledgement to the sender that we received the page
1374                         //ckout << "Sending AckRLE to PE " << pe << endl;
1375                         cache[pe].AckPage(thisIndex);
1376                 }
1377
1378     // MSA_PageArray::
1379     inline void Sync()
1380                 {
1381                         MSADEBPRINT(printf("MSA_PageArray::Sync about to call contribute \n");); 
1382                         contribute(0, NULL, CkReduction::concat);
1383                 }
1384
1385     inline void emit(int ID, int index)
1386                 {
1387                         //ckout << "p" << CkMyPe() << "ID" << ID;
1388 //         if(epage == NULL)
1389 //             ckout << "emit: epage is NULL" << endl;
1390 //         else
1391 //             ckout << "emit: " << epage[index] << endl;
1392                 }
1393 };
1394
1395 #define CK_TEMPLATES_ONLY
1396 #include "msa.def.h"
1397 #undef CK_TEMPLATES_ONLY
1398
1399 #endif