Remove setCacheProxy entry method from PageArray
[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(thisProxy, 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.ckSetReductionClient(new CkCallback(CkIndex_MSA_CacheGroup<ENTRY_TYPE, ENTRY_OPS_CLASS, ENTRIES_PER_PAGE>::SyncDone(), thisProxy));
806
807                         MSADEBPRINT(printf("MSA_CacheGroup nEntries %d \n",nEntries););
808                 }
809
810     // MSA_CacheGroup::
811     inline ~MSA_CacheGroup()
812                 {
813                         FreeMem();
814                 }
815
816     /* To change the accumulate function TBD @@ race conditions */
817     inline void changeEntryOpsObject(ENTRY_OPS_CLASS *e) {
818         entryOpsObject = e;
819         pageArray.changeEntryOpsObject(e);
820     }
821
822     // MSA_CacheGroup::
823     inline const ENTRY_TYPE* readablePage(unsigned int page)
824                 {
825                         accessPage(page,Read_Fault);
826         
827                         return pageTable[page];
828                 }
829
830     // MSA_CacheGroup::
831     //
832     // known local page
833     inline const void* readablePage2(unsigned int page)
834                 {
835                         return pageTable[page];
836                 }
837
838     // MSA_CacheGroup::
839     // Obtains a writable copy of the page.
840     inline ENTRY_TYPE* writeablePage(unsigned int page, unsigned int offset)
841                 {
842                         accessPage(page,Write_Fault);
843
844                         // NOTE: Since we assume write once semantics, i.e. between two calls to sync,
845                         // either there can be no write to a location or a single write to a location,
846                         // a readable page will suffice as a writeable page too, because no one else
847                         // is going to write to this location. In reality, two locations on the *same*
848                         // page can be written by two different threads, in which case we will need
849                         // to keep track of which parts of the page have been written, hence:
850                         stateN(page)->write(offset);
851 //     ckout << "write:" << page*ENTRIES_PER_PAGE+offset << endl;
852         
853                         return pageTable[page];
854                 }
855
856     // MSA_CacheGroup::
857     inline ENTRY_TYPE &accumulate(unsigned int page, unsigned int offset)
858                 {
859                         accessPage(page,Accumulate_Fault);
860                         stateN(page)->write(offset);
861                         return pageTable[page][offset];
862                 }
863
864     /// A requested page has arrived from the network.
865     ///  nEntriesInPage_ = num entries being sent (0 for empty page, num entries otherwise)
866     inline void ReceivePageWithPUP(unsigned int page, page_t &pageData, int size)
867                 {
868                         ReceivePage(page, pageData.getData(), size);
869                 }
870
871     inline void ReceivePage(unsigned int page, ENTRY_TYPE* pageData, int size)
872                 {
873                         CkAssert(0==size || ENTRIES_PER_PAGE == size);
874                         // the page we requested has been received
875                         ENTRY_TYPE *nu=makePage(page);
876                         if(size!=0)
877                         {
878                                 for(unsigned int i = 0; i < size; i++)
879                                         nu[i] = pageData[i]; // @@@, calls assignment operator
880                         }
881                         else /* isEmpty */
882                         {
883                                 // the page we requested for is empty, so we can just initialize it.
884                                 writeIdentity(nu);
885                         }
886         
887                         state(page)->readRequests.signal(page);
888                 }
889
890     // This EP is invoked during sync to acknowledge that a dirty page
891     // has been received and written back to the page owner.  We keep track
892     // of the number of ack's yet to arrive in nChangesWaiting.  Once
893     // all the dirty pages have been ack'd, we awaken the thread that
894     // flushed the page.
895     //
896     // It's not clear this is useful very often...
897     //
898     // MSA_CacheGroup::
899     inline void AckPage(unsigned int page)
900                 {
901                         state(page)->writeRequests.signal(page);
902                 }
903
904     // MSA_CacheGroup::
905     // synchronize all the pages and also clear up the cache
906     inline void SyncReq(int single)
907                 {
908                         MSADEBPRINT(printf("SyncReq single %d\n",single););
909                         if(single)
910                         {
911                                 /*ask all the caches to send their updates to the page
912                                  * array, but we don't need to empty the caches on the
913                                  * other PEs*/
914                                 SingleSync();
915                                 EmptyCache();
916
917                                 getListener()->suspend();
918                         }
919                         else{
920                                 Sync();
921                         }
922                 }
923
924     // MSA_CacheGroup::
925     inline void FlushCache()
926                 {
927                         // flush the local cache
928                         // for each writeable page, send that page to the array element
929                         for(unsigned int i = 0; i < nPages; i++)
930                         {
931                                 if(shouldWriteback(i)) {
932                                         //ckout << "p" << CkMyPe() << "FlushCache: sending page " << i << endl;
933                                         sendChangesToPageArray(i, 1);
934                                 }
935                         }
936                 }
937
938     // MSA_CacheGroup::
939     void EmptyCache()
940                 {
941                         /* just makes all the pages empty, assuming that the data
942                          * in those pages has been flushed to the owners */
943                         for(unsigned int i = 0; i < nPages; i++)
944                         {
945                                 if(pageTable[i]) pagePool.push(destroyPage(i));
946                         }
947                 }
948
949 /************************ Enroll ********************/
950     /// Enroll phase 1: called by users.
951     // MSA_CacheGroup::
952     inline void enroll(unsigned int num_workers)
953                 {
954                         CkAssert(num_workers == numberOfWorkerThreads); // just to verify
955                         CkAssert(enrollDoneq == 0);
956                         numberLocalWorkerThreads++;
957                         // @@ how to ensure that enroll is called only once?
958
959                         //ckout << "[" << CkMyPe() << "] sending sync ack to PE 0" << endl;
960                         thisProxy[0].enrollAck(CkMyPe());
961                         //ckout << "[" << CkMyPe() << "] suspening thread in Sync() " << endl;
962                         addAndSuspend(enrollWaiters);
963                         //ckout << "[" << CkMyPe() << "] rsuming thread in Sync()" << endl;
964
965                         CkAssert(enrollDoneq == 1);
966                         return;
967                 }
968
969     /// Enroll phase 2: called on PE 0 from everywhere
970     inline void enrollAck(int originator)
971                 {
972                         CkAssert(CkMyPe() == 0);  // enrollAck is only called on PE 0
973                         CkAssert(enrollDoneq == 0);  // prevent multiple enroll operations
974         
975                         syncAckCount++;
976                         enrolledPEs.insert(originator);
977                         //ckout << "[" << CkMyPe() << "] SyncAckcount = " << syncAckCount << endl;
978                         if(syncAckCount == numberOfWorkerThreads) {
979 //             ckout << "[" << CkMyPe() << "]" << "Enroll operation is almost done" << endl;
980                                 syncAckCount = 0;
981                                 enrollDoneq = 1;
982                                 // What if fewer worker threads than pe's ?  Handled in
983                                 // enrollDone.
984                                 thisProxy.enrollDone();
985                         }
986                 }
987
988     /// Enroll phase 3: called everywhere by PE 0
989     inline void enrollDone()
990                 {
991 //         ckout << "[" << CkMyPe() << "] enrollDone.  Waking threads."
992 //               <<  " numberOfWorkerThreads=" << numberOfWorkerThreads
993 //               <<  " local=" << numberLocalWorkerThreads << endl;
994                         enrollDoneq = 1;
995                         enrollWaiters.signal(0);
996                 }
997
998 /******************************** Sync & writeback ***********************/
999     // MSA_CacheGroup::
1000     inline void SingleSync()
1001                 {
1002                         /* a single thread issued a sync call with all = 1. The
1003                          * first thing to do is to flush the local cache */
1004                         FlushCache();
1005                 }
1006
1007     // MSA_CacheGroup::
1008     inline void Sync()
1009                 {
1010                         syncThreadCount++;
1011                         //ckout << "[" << CkMyPe() << "] syncThreadCount = " << syncThreadCount << " " << numberLocalWorkerThreads << endl;
1012                         //ckout << "[" << CkMyPe() << "] syncThreadCount = " << syncThreadCount << ", registered threads = " << getNumRegisteredThreads()
1013                         //  << ", number of suspended threads = " << getNumSuspendedThreads() << endl;
1014
1015                         // First, all threads on this processor need to reach the sync
1016                         // call; only then can we proceed with merging the data.  Only
1017                         // the last thread on this processor needs to do the FlushCache,
1018                         // etc.  Others just suspend until the sync is over.
1019                         MSADEBPRINT(printf("Sync syncThreadCount %d \n",syncThreadCount););
1020                         if(syncThreadCount < numberLocalWorkerThreads)
1021                         {
1022                                 MSADEBPRINT(printf("Sync addAndSuspend \n"););
1023                                 addAndSuspend(syncWaiters);
1024                                 return;
1025                         }
1026                 
1027                         //ckout << "[" << CkMyPe() << "] Sync started" << endl;
1028
1029                         // flush the cache asynchronously and also empty it
1030                         FlushCache();
1031                         // idea: instead of invalidating the pages, switch it to read
1032                         // mode. That will not work, since the page may have also been
1033                         // modified by another thread.
1034                         EmptyCache();
1035
1036                         // Now, we suspend too (if we had at least one dirty page).
1037                         // We will be awoken when all our dirty pages have been
1038                         // written and acknowledged.
1039                         MSADEBPRINT(printf("Sync calling suspend on getListener\n"););
1040                         getListener()->suspend();
1041                         MSADEBPRINT(printf("Sync awakening after suspend\n"););
1042
1043                         // So far, the sync has been asynchronous, i.e. PE0 might be ahead
1044                         // of PE1.  Next we basically do a barrier to ensure that all PE's
1045                         // are synchronized.
1046
1047                         // at this point, the sync's across the group should
1048                         // synchronize among themselves by each one sending
1049                         // a sync acknowledge message to PE 0. (this is like
1050                         // a reduction over a group)
1051                         if(CkMyPe() != 0)
1052                         {
1053                                 thisProxy[0].SyncAck();
1054                         }
1055                         else /* I *am* PE 0 */
1056                         {
1057                                 SyncAck();
1058                         }
1059                         MSADEBPRINT(printf("Sync all local threads done, going to addAndSuspend\n"););
1060                         /* Wait until sync is reflected from PE 0 */
1061                         addAndSuspend(syncWaiters);
1062                                 
1063                         MSADEBPRINT(printf("Sync all local threads done waking up after addAndSuspend\n"););
1064                         //ckout << "[" << CkMyPe() << "] Sync finished" << endl;        
1065                 }
1066
1067     inline unsigned int getNumEntries() { return nEntries; }
1068     inline CProxy_PageArray_t getArray() { return pageArray; }
1069
1070     // TODO: Can this SyncAck and other simple Acks be made efficient?
1071     inline void SyncAck()
1072                 {
1073                         CkAssert(CkMyPe() == 0);  // SyncAck is only called on PE 0
1074                         syncAckCount++;
1075                         // DONE @@ what if fewer worker threads than pe's ?
1076                         // @@ what if fewer worker threads than pe's and >1 threads on 1 pe?
1077                         //if(syncAckCount == min(numberOfWorkerThreads, CkNumPes())){
1078                         if (syncAckCount == enrolledPEs.size()) {
1079                                 MSADEBPRINT(printf("SyncAck starting reduction on pageArray of size %d number of pages %d\n",
1080                                                                    nEntries, nPages););
1081                                 pageArray.Sync();
1082                         }               
1083                 }
1084
1085     inline void SyncDone()
1086                 {
1087                         //ckout << "[" << CkMyPe() << "] Sync Done indication" << endl;
1088                         //ckout << "[" << CkMyPe() << "] Sync Done indication" << endl;
1089                         /* Reset for next sync */
1090                         syncThreadCount = 0;
1091                         syncAckCount = 0;
1092                         MSADEBPRINT(printf("SyncDone syncWaiters signal to be called\n"););
1093                         syncWaiters.signal(0);
1094                 }
1095
1096     inline void FreeMem()
1097                 {
1098                         for(unsigned int i = 0; i < nPages; i++)
1099                         {
1100                                 if(pageTable[i]) delete [] destroyPage(i);
1101                         }
1102
1103                         while(!pagePool.empty())
1104                         {
1105                                 delete [] pagePool.top();  // @@@
1106                                 pagePool.pop();
1107                         }
1108         
1109                         resident_pages=0;
1110                 }
1111
1112         /** 
1113                 Deregister a client. Decrement the number of local threads. If total number of local threads 
1114                 hits 0 FreeMem()
1115         */
1116         inline void unroll() {
1117                 numberLocalWorkerThreads--;
1118                 if(numberLocalWorkerThreads == 0){
1119                         FreeMem();
1120                 }
1121         }
1122
1123     /**
1124      * Issue a prefetch request for the given range of pages. These pages will
1125      * be locked into the cache, so that they will not be swapped out.
1126      */
1127     inline void Prefetch(unsigned int pageStart, unsigned int pageEnd)
1128                 {
1129                         /* prefetching is feasible only if we we did not encounter an out
1130                          * of buffer condition in the previous prefetch call
1131                          */
1132                         if(!outOfBufferInPrefetch)
1133                         {
1134                                 //ckout << "prefetching pages " << pageStart << " through " << pageEnd << endl;
1135                                 for(unsigned int p = pageStart; p <= pageEnd; p++)
1136                                 {
1137                                         if(NULL == pageTable[p])
1138                                         {
1139
1140                                                 /* relocate the buffer asynchronously */
1141                                                 ENTRY_TYPE* nu = tryBuffer(1);
1142                                                 if(NULL == nu)
1143                                                 {
1144                                                         /* signal that sufficient buffer space is not available */
1145                                                         outOfBufferInPrefetch = 1;
1146                                                         break;
1147                                                 }
1148
1149                                                 pageTable[p] = nu;
1150                                                 state(p)->state = Read_Fault;
1151
1152                                                 pageArray[p].GetPage(CkMyPe());
1153                                                 IncrementPagesWaiting(p);
1154                                                 //ckout << "Prefetch page" << p << ", pages waiting = " << nPagesWaiting << endl;
1155                                                 /* don't suspend the thread */
1156                                         }
1157
1158                                         /* mark the page as being locked */
1159                                         state(p)->locked = true;
1160                                 }
1161                         }
1162                 }
1163
1164     /**
1165      * Wait for all the prefetch pages to be fetched into the cache.
1166      * Returns: 0 if prefetch successful, 1 if not
1167      */
1168     inline int WaitAll(void)
1169                 {
1170                         if(outOfBufferInPrefetch)
1171                         {
1172                                 // we encountered out of buffer in the previous prefetch call, return error
1173                                 outOfBufferInPrefetch = 0;
1174                                 getListener()->suspend();
1175                                 UnlockPages();
1176                                 return 1;
1177                         }
1178                         else
1179                         {
1180                                 // prefetch requests have been successfully issued already, so suspend the
1181                                 // thread and wait for completion
1182                                 outOfBufferInPrefetch = 0;
1183                                 getListener()->suspend();
1184                                 return 0;
1185                         }
1186                 }
1187     
1188     inline void UnlockPage(unsigned int page) {
1189         pageState_t *s=stateN(page);
1190                 if(s && s->locked) {
1191             replacementPolicy->pageAccessed(page);
1192             s->locked = false;
1193                 }
1194     }
1195
1196     /**
1197      * Unlock all the pages locked in the cache
1198      */
1199     inline void UnlockPages()
1200                 {
1201                         // add all the locked pages to page replacement policy
1202                         for(unsigned int page = 0; page < nPages; page++)
1203                                 UnlockPage(page);
1204                 }
1205
1206     /**
1207      * Unlock the given pages: [startPage ... endPage]
1208      *  Note that the range is inclusive.
1209      */
1210     inline void UnlockPages(unsigned int startPage, unsigned int endPage)
1211                 {
1212                         for(unsigned int page = startPage; page <= endPage; page++)
1213                                 UnlockPage(page);
1214                 }
1215
1216     /// Debugging routine
1217     inline void emitBufferValue(int ID, unsigned int pageNum, unsigned int offset)
1218                 {
1219                         CkAssert( pageNum < nPages );
1220                         CkAssert( offset < ENTRIES_PER_PAGE );
1221
1222                         //ckout << "p" << CkMyPe() << "ID" << ID;
1223 //         if (pageTable[pageNum] == 0)
1224 //             ckout << "emitBufferValue: page " << pageNum << " not available in local cache." << endl;
1225 //         else
1226 //             ckout << "emitBufferValue: [" << pageNum << "," << offset << "] = " << pageTable[pageNum][offset] << endl;
1227                 }
1228 };
1229
1230 // each element of this array is responsible for managing
1231 // the information about a single page. It is in effect the
1232 // "owner" as well as the "manager" for that page.
1233 //
1234 template<class ENTRY_TYPE, class ENTRY_OPS_CLASS,unsigned int ENTRIES_PER_PAGE> 
1235 class MSA_PageArray : public ArrayElement1D
1236 {
1237     typedef CProxy_MSA_CacheGroup<ENTRY_TYPE, ENTRY_OPS_CLASS, ENTRIES_PER_PAGE> CProxy_CacheGroup_t;
1238     typedef MSA_PageT<ENTRY_TYPE, ENTRY_OPS_CLASS, ENTRIES_PER_PAGE> page_t;
1239     
1240 protected:
1241     ENTRY_TYPE *epage;
1242     ENTRY_OPS_CLASS entryOpsObject;
1243     CProxy_CacheGroup_t cache;
1244
1245     unsigned int pageNo() { return thisIndex; }
1246
1247     inline void allocatePage(MSA_Page_Fault_t access) // @@@
1248                 {
1249                         if(epage == NULL)
1250                         {
1251                                 epage = new ENTRY_TYPE[ENTRIES_PER_PAGE];
1252                                 if (access==Accumulate_Fault)
1253                                         writeIdentity();
1254                         }
1255                 }
1256
1257     // begin and end are indexes into the page.
1258     inline void set(const ENTRY_TYPE* buffer, unsigned int begin, unsigned int end)
1259                 {
1260                         //ckout << "set: " << begin << "," << end << endl;
1261                         for(unsigned int i = 0; i < (end - begin); i++) {
1262                                 epage[begin + i] = buffer[i]; // @@@, calls assignment operator
1263                                 //ckout << "set val[" << begin+i << "]=" << buffer[i] << endl;
1264                         }
1265                 }
1266
1267     // MSA_PageArray::
1268     inline void combine(const ENTRY_TYPE* buffer, unsigned int begin, unsigned int end)
1269                 {
1270                         ENTRY_TYPE* pagePtr = epage + begin;
1271                         for(unsigned int i = 0; i < (end - begin); i++)
1272                                 entryOpsObject.accumulate(pagePtr[i], buffer[i]);
1273                 }
1274
1275     // MSA_PageArray::
1276     inline void writeIdentity()
1277                 {
1278                         for(unsigned int i = 0; i < ENTRIES_PER_PAGE; i++)
1279                                 epage[i] = entryOpsObject.getIdentity();
1280                 }
1281
1282 public:
1283     inline MSA_PageArray(CProxy_CacheGroup_t &cache_) : epage(NULL), cache(cache_) { }
1284     inline MSA_PageArray(CkMigrateMessage* m) { delete m; }
1285     
1286     virtual void pup(PUP::er& p)
1287                 {
1288                         ArrayElement1D::pup(p);
1289                         int epage_present=(epage!=0);
1290                         p|epage_present;
1291                         if (epage_present) {
1292                                 if(p.isUnpacking())
1293                                         allocatePage(Write_Fault);
1294                                 for (int i=0;i<ENTRIES_PER_PAGE;i++)
1295                                         p|epage[i];
1296                         }
1297                 }
1298     
1299     inline ~MSA_PageArray()
1300                 {
1301                         if(epage) delete [] epage;
1302                 }
1303
1304     /// Request our page.
1305     ///   pe = to which to send page
1306     inline void GetPage(int pe)
1307                 {
1308                         if(epage == NULL) {
1309                                 // send empty page
1310                                 if (entryOpsObject.pupEveryElement())
1311                                         cache[pe].ReceivePageWithPUP(pageNo(), page_t((ENTRY_TYPE*)NULL), 0);
1312                                 else
1313                                         cache[pe].ReceivePage(pageNo(), (ENTRY_TYPE*)NULL, 0);
1314                         } else {
1315                                 // send page with data
1316                                 if (entryOpsObject.pupEveryElement())
1317                                         cache[pe].ReceivePageWithPUP(pageNo(), page_t(epage), ENTRIES_PER_PAGE);
1318                                 else
1319                                         cache[pe].ReceivePage(pageNo(), epage, ENTRIES_PER_PAGE);  // send page with data                
1320                         }
1321                 }
1322
1323     /// Receive a non-runlength encoded page from the network:
1324     // @@ TBD: ERROR: This does not work for  varsize pages.
1325     inline void PAReceivePage(ENTRY_TYPE *pageData,
1326                                                           int pe, MSA_Page_Fault_t pageState)
1327                 {
1328                         allocatePage(pageState);
1329
1330                         if(pageState == Write_Fault)
1331                                 set(pageData, 0, ENTRIES_PER_PAGE);
1332                         else
1333                                 combine(pageData, 0, ENTRIES_PER_PAGE);
1334         
1335                         // send the acknowledgement to the sender that we received the page
1336                         //ckout << "Sending Ack to PE " << pe << endl;
1337                         cache[pe].AckPage(thisIndex);
1338                 }
1339
1340     /// Receive a runlength encoded page from the network:
1341     inline void PAReceiveRLEPageWithPup(
1342         const MSA_WriteSpan_t *spans, unsigned int nSpans, 
1343         page_t &entries, unsigned int nEntries, 
1344         int pe, MSA_Page_Fault_t pageState)
1345                 {
1346                         PAReceiveRLEPage(spans, nSpans, entries.getData(), nEntries, pe, pageState);
1347                 }
1348
1349
1350     inline void PAReceiveRLEPage(
1351         const MSA_WriteSpan_t *spans, unsigned int nSpans, 
1352         const ENTRY_TYPE *entries, unsigned int nEntries, 
1353         int pe, MSA_Page_Fault_t pageState)
1354                 {
1355                         allocatePage(pageState);
1356         
1357                         //ckout << "p" << CkMyPe() << "ReceiveRLEPage nSpans=" << nSpans << " nEntries=" << nEntries << endl;
1358                         int e=0; /* consumed entries */
1359                         for (int s=0;s<nSpans;s++) {
1360                                 if(pageState == Write_Fault)
1361                                         set(&entries[e], spans[s].start,spans[s].end);
1362                                 else /* Accumulate_Fault */
1363                                         combine(&entries[e], spans[s].start,spans[s].end);
1364                                 e+=spans[s].end-spans[s].start;
1365                         } 
1366
1367                         // send the acknowledgement to the sender that we received the page
1368                         //ckout << "Sending AckRLE to PE " << pe << endl;
1369                         cache[pe].AckPage(thisIndex);
1370                 }
1371
1372     // MSA_PageArray::
1373     inline void Sync()
1374                 {
1375                         MSADEBPRINT(printf("MSA_PageArray::Sync about to call contribute \n");); 
1376                         contribute(0, NULL, CkReduction::concat);
1377                 }
1378
1379     inline void emit(int ID, int index)
1380                 {
1381                         //ckout << "p" << CkMyPe() << "ID" << ID;
1382 //         if(epage == NULL)
1383 //             ckout << "emit: epage is NULL" << endl;
1384 //         else
1385 //             ckout << "emit: " << epage[index] << endl;
1386                 }
1387 };
1388
1389 #define CK_TEMPLATES_ONLY
1390 #include "msa.def.h"
1391 #undef CK_TEMPLATES_ONLY
1392
1393 #endif