GRASS Programmer's Manual  6.4.2(2012)
pagein.c
Go to the documentation of this file.
00001 
00015 #include <stdio.h>
00016 #include <unistd.h>
00017 #include <string.h>
00018 #include <errno.h>
00019 #include <grass/segment.h>
00020 
00021 
00022 static int segment_select(SEGMENT *, int);
00023 
00024 
00039 int segment_pagein(SEGMENT * SEG, int n)
00040 {
00041     int age;
00042     int cur;
00043     int i;
00044     int read_result;
00045 
00046     /* is n the current segment? */
00047     if (n == SEG->scb[SEG->cur].n)
00048         return SEG->cur;
00049 
00050     /* search the in memory segments */
00051     for (i = 0; i < SEG->nseg; i++)
00052         if (n == SEG->scb[i].n)
00053             return segment_select(SEG, i);
00054 
00055     /* find a slot to use to hold segment */
00056     age = 0;
00057     cur = 0;
00058     for (i = 0; i < SEG->nseg; i++)
00059         if (SEG->scb[i].n < 0) {        /* free slot */
00060             cur = i;
00061             break;
00062         }
00063         else if (age < SEG->scb[i].age) {       /* find oldest segment */
00064             cur = i;
00065             age = SEG->scb[i].age;
00066         }
00067 
00068     /* if slot is used, write it out, if dirty */
00069     if (SEG->scb[cur].n >= 0 && SEG->scb[cur].dirty)
00070         if (segment_pageout(SEG, cur) < 0)
00071             return -1;
00072 
00073     /* read in the segment */
00074     SEG->scb[cur].n = n;
00075     SEG->scb[cur].dirty = 0;
00076     segment_seek(SEG, SEG->scb[cur].n, 0);
00077 
00078     read_result = read(SEG->fd, SEG->scb[cur].buf, SEG->size);
00079     if (read_result != SEG->size) {
00080         G_debug(2, "segment_pagein: read_result=%d  SEG->size=%d",
00081                 read_result, SEG->size);
00082 
00083         if (read_result < 0)
00084             G_warning("segment_pagein: %s", strerror(errno));
00085         else if (read_result == 0)
00086             G_warning("segment_pagein: read EOF");
00087         else
00088             G_warning
00089                 ("segment_pagein: short count during read(), got %d, expected %d",
00090                  read_result, SEG->size);
00091 
00092         return -1;
00093     }
00094 
00095     return segment_select(SEG, cur);
00096 }
00097 
00098 
00099 static int segment_select(SEGMENT * SEG, int n)
00100 {
00101     int i;
00102 
00103     SEG->scb[n].age = 0;
00104     for (i = 0; i < SEG->nseg; i++)
00105         SEG->scb[i].age++;
00106 
00107     return SEG->cur = n;
00108 }
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Defines