ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/rt/ambient.c
(Generate patch)

Comparing ray/src/rt/ambient.c (file contents):
Revision 2.6 by greg, Thu Jul 16 12:09:08 1992 UTC vs.
Revision 2.41 by greg, Wed Jul 10 13:33:56 1996 UTC

# Line 1 | Line 1
1 < /* Copyright (c) 1991 Regents of the University of California */
1 > /* Copyright (c) 1996 Regents of the University of California */
2  
3   #ifndef lint
4   static char SCCSid[] = "$SunId$ LBL";
# Line 6 | Line 6 | static char SCCSid[] = "$SunId$ LBL";
6  
7   /*
8   *  ambient.c - routines dealing with ambient (inter-reflected) component.
9 *
10 *  The macro AMBFLUSH (if defined) is the number of ambient values
11 *      to wait before flushing to the ambient file.
12 *
13 *     5/9/86
9   */
10  
11   #include  "ray.h"
# Line 23 | Line 18 | static char SCCSid[] = "$SunId$ LBL";
18  
19   #include  "random.h"
20  
21 < #define  OCTSCALE       0.5     /* ceil((valid rad.)/(cube size)) */
21 > #ifndef  OCTSCALE
22 > #define  OCTSCALE       1.0     /* ceil((valid rad.)/(cube size)) */
23 > #endif
24  
25   typedef struct ambtree {
26 <        AMBVAL  *alist;         /* ambient value list */
27 <        struct ambtree  *kid;   /* 8 child nodes */
26 >        AMBVAL  *alist;         /* ambient value list */
27 >        struct ambtree  *kid;   /* 8 child nodes */
28   }  AMBTREE;                     /* ambient octree */
29  
30   extern CUBE  thescene;          /* contains space boundaries */
31  
32 < #define  MAXASET        511     /* maximum number of elements in ambient set */
36 < OBJECT  ambset[MAXASET+1]={0};  /* ambient include/exclude set */
32 > extern char  *shm_boundary;     /* memory sharing boundary */
33  
34 < double  maxarad;                /* maximum ambient radius */
35 < double  minarad;                /* minimum ambient radius */
34 > #define  MAXASET        511     /* maximum number of elements in ambient set */
35 > OBJECT  ambset[MAXASET+1]={0};  /* ambient include/exclude set */
36  
37 < static AMBTREE  atrunk;         /* our ambient trunk node */
37 > double  maxarad;                /* maximum ambient radius */
38 > double  minarad;                /* minimum ambient radius */
39  
40 + static AMBTREE  atrunk;         /* our ambient trunk node */
41 +
42   static FILE  *ambfp = NULL;     /* ambient file pointer */
43 < static int  ambheadlen;         /* length of ambient file header */
43 > static int  nunflshed = 0;      /* number of unflushed ambient values */
44  
45 < #define  AMBFLUSH       (BUFSIZ/AMBVALSIZ)
45 > #ifndef SORT_THRESH
46 > #ifdef BIGMEM
47 > #define SORT_THRESH     ((9L<<20)/sizeof(AMBVAL))
48 > #else
49 > #define SORT_THRESH     ((3L<<20)/sizeof(AMBVAL))
50 > #endif
51 > #endif
52 > #ifndef SORT_INTVL
53 > #define SORT_INTVL      (SORT_THRESH<<1)
54 > #endif
55 > #ifndef MAX_SORT_INTVL
56 > #define MAX_SORT_INTVL  (SORT_INTVL<<6)
57 > #endif
58  
59 < #define  newambval()    (AMBVAL *)bmalloc(sizeof(AMBVAL))
59 > static COLOR  avsum = BLKCOLOR;         /* computed ambient value sum */
60 > static unsigned int  nambvals = 0;      /* total number of indirect values */
61 > static unsigned int  nambshare = 0;     /* number of values from file */
62 > static unsigned long  ambclock = 0;     /* ambient access clock */
63 > static unsigned long  lastsort = 0;     /* time of last value sort */
64 > static long  sortintvl = SORT_INTVL;    /* time until next sort */
65  
66 < #define  newambtree()   (AMBTREE *)calloc(8, sizeof(AMBTREE))
66 > #define MAXACLOCK       (1L<<30)        /* clock turnover value */
67 >        /*
68 >         * Track access times unless we are sharing ambient values
69 >         * through memory on a multiprocessor, when we want to avoid
70 >         * claiming our own memory (copy on write).  Go ahead anyway
71 >         * if more than two thirds of our values are unshared.
72 >         */
73 > #define tracktime       (shm_boundary == NULL || nambvals > 3*nambshare)
74  
75 + #define  AMBFLUSH       (BUFSIZ/AMBVALSIZ)
76  
77 + #define  newambval()    (AMBVAL *)bmalloc(sizeof(AMBVAL))
78 +
79 + extern long  ftell(), lseek();
80 + static int  initambfile(), avsave(), avinsert(), sortambvals(), avlmemi();
81 + static AMBVAL  *avstore();
82 + #ifdef  F_SETLKW
83 + static  aflock();
84 + #endif
85 +
86 +
87   setambres(ar)                           /* set ambient resolution */
88   int  ar;
89   {
90 +        ambres = ar < 0 ? 0 : ar;               /* may be done already */
91                                                  /* set min & max radii */
92          if (ar <= 0) {
93 <                minarad = 0.0;
93 >                minarad = 0;
94                  maxarad = thescene.cusize / 2.0;
95          } else {
96                  minarad = thescene.cusize / ar;
97 <                maxarad = 16.0 * minarad;               /* heuristic */
97 >                maxarad = 64 * minarad;                 /* heuristic */
98                  if (maxarad > thescene.cusize / 2.0)
99                          maxarad = thescene.cusize / 2.0;
100          }
101 <        if (maxarad <= FTINY)
102 <                maxarad = .001;
101 >        if (minarad <= FTINY)
102 >                minarad = 10*FTINY;
103 >        if (maxarad <= minarad)
104 >                maxarad = 64 * minarad;
105   }
106  
107  
108 + setambacc(newa)                         /* set ambient accuracy */
109 + double  newa;
110 + {
111 +        double  ambdiff;
112 +
113 +        if (newa < 0.0)
114 +                newa = 0.0;
115 +        ambdiff = fabs(newa - ambacc);
116 +        if (ambdiff >= .01 && (ambacc = newa) > FTINY && nambvals > 0)
117 +                sortambvals(1);                 /* rebuild tree */
118 + }
119 +
120 +
121   setambient(afile)                       /* initialize calculation */
122   char  *afile;
123   {
124 <        extern long  ftell();
125 <        AMBVAL  amb;
124 >        long  pos, flen;
125 >        AMBVAL  amb;
126                                                  /* init ambient limits */
127          setambres(ambres);
128 +        setambacc(ambacc);
129 +        if (afile == NULL)
130 +                return;
131 +        if (ambacc <= FTINY) {
132 +                sprintf(errmsg, "zero ambient accuracy so \"%s\" not opened",
133 +                                afile);
134 +                error(WARNING, errmsg);
135 +                return;
136 +        }
137                                                  /* open ambient file */
138 <        if (afile != NULL)
139 <                if ((ambfp = fopen(afile, "r+")) != NULL) {
140 <                        initambfile(0);
141 <                        while (readambval(&amb, ambfp))
142 <                                avinsert(&amb, &atrunk, thescene.cuorg,
143 <                                                thescene.cusize);
144 <                                                        /* align */
145 <                        fseek(ambfp, -((ftell(ambfp)-ambheadlen)%AMBVALSIZ), 1);
146 <                } else if ((ambfp = fopen(afile, "w")) != NULL)
147 <                        initambfile(1);
148 <                else {
149 <                        sprintf(errmsg, "cannot open ambient file \"%s\"",
150 <                                        afile);
151 <                        error(SYSTEM, errmsg);
138 >        if ((ambfp = fopen(afile, "r+")) != NULL) {
139 >                initambfile(0);
140 >                pos = ftell(ambfp);
141 >                while (readambval(&amb, ambfp))
142 >                        avinsert(avstore(&amb));
143 >                                                /* align */
144 >                pos += (long)nambvals*AMBVALSIZ;
145 >                flen = lseek(fileno(ambfp), 0L, 2);
146 >                if (flen != pos) {
147 >                        error(WARNING,
148 >                        "ignoring last %ld values in ambient file (corrupted)",
149 >                                        (flen - pos)/AMBVALSIZ);
150 >                        fseek(ambfp, pos, 0);
151 >                        ftruncate(fileno(ambfp), pos);
152                  }
153 +                nambshare = nambvals;
154 +        } else if ((ambfp = fopen(afile, "w+")) != NULL)
155 +                initambfile(1);
156 +        else {
157 +                sprintf(errmsg, "cannot open ambient file \"%s\"", afile);
158 +                error(SYSTEM, errmsg);
159 +        }
160 +        nunflshed++;    /* lie */
161 +        ambsync();
162   }
163  
164  
97 initambfile(creat)              /* initialize ambient file */
98 int  creat;
99 {
100        extern char  *progname, *octname;
101
102        setbuf(ambfp, bmalloc(BUFSIZ));
103        if (creat) {                    /* new file */
104                fprintf(ambfp, "%s -av %g %g %g -ab %d -aa %g ",
105                                progname, colval(ambval,RED),
106                                colval(ambval,GRN), colval(ambval,BLU),
107                                ambounce, ambacc);
108                fprintf(ambfp, "-ad %d -as %d -ar %d %s\n",
109                                ambdiv, ambssamp, ambres,
110                                octname==NULL ? "" : octname);
111                fputformat(AMBFMT, ambfp);
112                putc('\n', ambfp);
113                putambmagic(ambfp);
114                fflush(ambfp);
115        } else if (checkheader(ambfp, AMBFMT, NULL) < 0 || !hasambmagic(ambfp))
116                error(USER, "ambient file format error");
117        ambheadlen = ftell(ambfp);
118 }
119
120
165   ambnotify(obj)                  /* record new modifier */
166 < OBJECT  obj;
166 > OBJECT  obj;
167   {
168          static int  hitlimit = 0;
169 <        register OBJREC  *o = objptr(obj);
169 >        register OBJREC  *o = objptr(obj);
170          register char  **amblp;
171  
172          if (hitlimit || !ismodifier(o->otype))
# Line 140 | Line 184 | OBJECT  obj;
184   }
185  
186  
187 < ambient(acol, r)                /* compute ambient component for ray */
187 > ambient(acol, r, nrm)           /* compute ambient component for ray */
188   COLOR  acol;
189   register RAY  *r;
190 + FVECT  nrm;
191   {
192          static int  rdepth = 0;                 /* ambient recursion */
193 <        double  d;
193 >        double  d;
194  
195          if (ambdiv <= 0)                        /* no ambient calculation */
196                  goto dumbamb;
# Line 161 | Line 206 | register RAY  *r;
206                  rdepth++;
207                  d = doambient(acol, r, r->rweight, NULL, NULL);
208                  rdepth--;
209 <                if (d == 0.0)
209 >                if (d <= FTINY)
210                          goto dumbamb;
211                  return;
212          }
213 +
214 +        if (tracktime)                          /* sort to minimize thrashing */
215 +                sortambvals(0);
216                                                  /* get ambient value */
217          setcolor(acol, 0.0, 0.0, 0.0);
218 <        d = sumambient(acol, r, rdepth,
218 >        d = sumambient(acol, r, nrm, rdepth,
219                          &atrunk, thescene.cuorg, thescene.cusize);
220 <        if (d > FTINY)
220 >        if (d > FTINY) {
221                  scalecolor(acol, 1.0/d);
222 <        else {
175 <                d = makeambient(acol, r, rdepth++);
176 <                rdepth--;
222 >                return;
223          }
224 +        rdepth++;                               /* need to cache new value */
225 +        d = makeambient(acol, r, nrm, rdepth-1);
226 +        rdepth--;
227          if (d > FTINY)
228                  return;
229   dumbamb:                                        /* return global value */
230          copycolor(acol, ambval);
231 +        if (ambvwt <= 0 | nambvals == 0)
232 +                return;
233 +        scalecolor(acol, (double)ambvwt);
234 +        addcolor(acol, avsum);                  /* average in computations */
235 +        d = 1.0/(ambvwt+nambvals);
236 +        scalecolor(acol, d);
237   }
238  
239  
240   double
241 < sumambient(acol, r, al, at, c0, s)      /* get interpolated ambient value */
241 > sumambient(acol, r, rn, al, at, c0, s)  /* get interpolated ambient value */
242   COLOR  acol;
243   register RAY  *r;
244 + FVECT  rn;
245   int  al;
246 < AMBTREE  *at;
246 > AMBTREE  *at;
247   FVECT  c0;
248 < double  s;
248 > double  s;
249   {
250 <        extern double  sqrt();
195 <        double  d, e1, e2, wt, wsum;
250 >        double  d, e1, e2, wt, wsum;
251          COLOR  ct;
252          FVECT  ck0;
253          int  i;
254          register int  j;
255 <        register AMBVAL  *av;
256 <                                        /* do this node */
255 >        register AMBVAL  *av;
256 >
257          wsum = 0.0;
258 +                                        /* do this node */
259          for (av = at->alist; av != NULL; av = av->next) {
260 +                if (tracktime)
261 +                        av->latick = ambclock;
262                  /*
263                   *  Ambient level test.
264                   */
265 <                if (av->lvl > al || av->weight < r->rweight-FTINY)
265 >                if (av->lvl > al)       /* list sorted, so this works */
266 >                        break;
267 >                if (av->weight < r->rweight-FTINY)
268                          continue;
269                  /*
270                   *  Ambient radius test.
271                   */
272 <                e1 = 0.0;
273 <                for (j = 0; j < 3; j++) {
274 <                        d = av->pos[j] - r->rop[j];
275 <                        e1 += d * d;
276 <                }
272 >                d = av->pos[0] - r->rop[0];
273 >                e1 = d * d;
274 >                d = av->pos[1] - r->rop[1];
275 >                e1 += d * d;
276 >                d = av->pos[2] - r->rop[2];
277 >                e1 += d * d;
278                  e1 /= av->rad * av->rad;
279                  if (e1 > ambacc*ambacc*1.21)
280                          continue;
# Line 237 | Line 298 | double  s;
298                   *  Jittering final test reduces image artifacts.
299                   */
300                  wt = sqrt(e1) + sqrt(e2);
301 <                wt *= .9 + .2*urand(9015+samplendx);
241 <                if (wt > ambacc)
301 >                if (wt > ambacc*(.9+.2*urand(9015+samplendx)))
302                          continue;
303                  if (wt <= 1e-3)
304                          wt = 1e3;
305                  else
306                          wt = 1.0 / wt;
307                  wsum += wt;
308 <                extambient(ct, av, r->rop, r->ron);
308 >                extambient(ct, av, r->rop, rn);
309                  scalecolor(ct, wt);
310                  addcolor(acol, ct);
311          }
# Line 264 | Line 324 | double  s;
324                                  break;
325                  }
326                  if (j == 3)
327 <                        wsum += sumambient(acol, r, al, at->kid+i, ck0, s);
327 >                        wsum += sumambient(acol, r, rn, al, at->kid+i, ck0, s);
328          }
329          return(wsum);
330   }
331  
332  
333   double
334 < makeambient(acol, r, al)        /* make a new ambient value */
334 > makeambient(acol, r, rn, al)    /* make a new ambient value */
335   COLOR  acol;
336   register RAY  *r;
337 + FVECT  rn;
338   int  al;
339   {
340 <        AMBVAL  amb;
340 >        AMBVAL  amb;
341          FVECT   gp, gd;
342                                                  /* compute weight */
343          amb.weight = pow(AVGREFL, (double)al);
344 <        if (r->rweight < 0.2*amb.weight)        /* heuristic */
344 >        if (r->rweight < 0.1*amb.weight)        /* heuristic */
345                  amb.weight = r->rweight;
346                                                  /* compute ambient */
347          amb.rad = doambient(acol, r, amb.weight, gp, gd);
348 <        if (amb.rad == 0.0)
348 >        if (amb.rad <= FTINY)
349                  return(0.0);
350                                                  /* store it */
351          VCOPY(amb.pos, r->rop);
# Line 294 | Line 355 | int  al;
355          VCOPY(amb.gpos, gp);
356          VCOPY(amb.gdir, gd);
357                                                  /* insert into tree */
358 <        avinsert(&amb, &atrunk, thescene.cuorg, thescene.cusize);
359 <        avsave(&amb);                           /* write to file */
358 >        avsave(&amb);                           /* and save to file */
359 >        if (rn != r->ron)
360 >                extambient(acol, &amb, r->rop, rn);     /* texture */
361          return(amb.rad);
362   }
363  
364  
365   extambient(cr, ap, pv, nv)              /* extrapolate value at pv, nv */
366   COLOR  cr;
367 < register AMBVAL  *ap;
367 > register AMBVAL  *ap;
368   FVECT  pv, nv;
369   {
370          FVECT  v1, v2;
371          register int  i;
372 <        double  d;
372 >        double  d;
373  
374          d = 1.0;                        /* zeroeth order */
375                                          /* gradient due to translation */
# Line 327 | Line 389 | FVECT  pv, nv;
389  
390  
391   static
392 < avsave(av)                              /* save an ambient value */
393 < AMBVAL  *av;
392 > initambfile(creat)              /* initialize ambient file */
393 > int  creat;
394   {
395 <        static int  nunflshed = 0;
395 >        extern char  *progname, *octname, VersionID[];
396  
397 + #ifdef  F_SETLKW
398 +        aflock(creat ? F_WRLCK : F_RDLCK);
399 + #endif
400 + #ifdef MSDOS
401 +        setmode(fileno(ambfp), O_BINARY);
402 + #endif
403 +        setbuf(ambfp, bmalloc(BUFSIZ+8));
404 +        if (creat) {                    /* new file */
405 +                newheader("RADIANCE", ambfp);
406 +                fprintf(ambfp, "%s -av %g %g %g -aw %d -ab %d -aa %g ",
407 +                                progname, colval(ambval,RED),
408 +                                colval(ambval,GRN), colval(ambval,BLU),
409 +                                ambvwt, ambounce, ambacc);
410 +                fprintf(ambfp, "-ad %d -as %d -ar %d %s\n",
411 +                                ambdiv, ambssamp, ambres,
412 +                                octname==NULL ? "" : octname);
413 +                fprintf(ambfp, "SOFTWARE= %s\n", VersionID);
414 +                fputformat(AMBFMT, ambfp);
415 +                putc('\n', ambfp);
416 +                putambmagic(ambfp);
417 +        } else if (checkheader(ambfp, AMBFMT, NULL) < 0 || !hasambmagic(ambfp))
418 +                error(USER, "bad ambient file");
419 + }
420 +
421 +
422 + static
423 + avsave(av)                              /* insert and save an ambient value */
424 + AMBVAL  *av;
425 + {
426 +        avinsert(avstore(av));
427          if (ambfp == NULL)
428                  return;
429          if (writambval(av, ambfp) < 0)
430                  goto writerr;
431 <        if (++nunflshed >= AMBFLUSH) {
432 <                if (fflush(ambfp) == EOF)
431 >        if (++nunflshed >= AMBFLUSH)
432 >                if (ambsync() == EOF)
433                          goto writerr;
342                nunflshed = 0;
343        }
434          return;
435   writerr:
436          error(SYSTEM, "error writing ambient file");
437   }
438  
439  
440 + static AMBVAL *
441 + avstore(aval)                           /* allocate memory and store aval */
442 + register AMBVAL  *aval;
443 + {
444 +        register AMBVAL  *av;
445 +
446 +        if ((av = newambval()) == NULL)
447 +                error(SYSTEM, "out of memory in avstore");
448 +        copystruct(av, aval);
449 +        av->latick = ambclock;
450 +        av->next = NULL;
451 +        addcolor(avsum, av->val);       /* add to sum for averaging */
452 +        nambvals++;
453 +        return(av);
454 + }
455 +
456 +
457 + #define ATALLOCSZ       512             /* #/8 trees to allocate at once */
458 +
459 + static AMBTREE  *atfreelist = NULL;     /* free ambient tree structures */
460 +
461 +
462   static
463 < avinsert(aval, at, c0, s)               /* insert ambient value in a tree */
464 < AMBVAL  *aval;
353 < register AMBTREE  *at;
354 < FVECT  c0;
355 < double  s;
463 > AMBTREE *
464 > newambtree()                            /* allocate 8 ambient tree structs */
465   {
466 +        register AMBTREE  *atp, *upperlim;
467 +
468 +        if (atfreelist == NULL) {       /* get more nodes */
469 +                atfreelist = (AMBTREE *)bmalloc(ATALLOCSZ*8*sizeof(AMBTREE));
470 +                if (atfreelist == NULL)
471 +                        return(NULL);
472 +                                        /* link new free list */
473 +                upperlim = atfreelist + 8*(ATALLOCSZ-1);
474 +                for (atp = atfreelist; atp < upperlim; atp += 8)
475 +                        atp->kid = atp + 8;
476 +                atp->kid = NULL;
477 +        }
478 +        atp = atfreelist;
479 +        atfreelist = atp->kid;
480 +        bzero((char *)atp, 8*sizeof(AMBTREE));
481 +        return(atp);
482 + }
483 +
484 +
485 + static
486 + freeambtree(atp)                        /* free 8 ambient tree structs */
487 + AMBTREE  *atp;
488 + {
489 +        atp->kid = atfreelist;
490 +        atfreelist = atp;
491 + }
492 +
493 +
494 + static
495 + avinsert(av)                            /* insert ambient value in our tree */
496 + register AMBVAL  *av;
497 + {
498 +        register AMBTREE  *at;
499 +        register AMBVAL  *ap;
500 +        AMBVAL  avh;
501          FVECT  ck0;
502 +        double  s;
503          int  branch;
359        register AMBVAL  *av;
504          register int  i;
505  
506 <        if ((av = newambval()) == NULL)
507 <                goto memerr;
508 <        copystruct(av, aval);
509 <        VCOPY(ck0, c0);
506 >        if (av->rad <= FTINY)
507 >                error(CONSISTENCY, "zero ambient radius in avinsert");
508 >        at = &atrunk;
509 >        VCOPY(ck0, thescene.cuorg);
510 >        s = thescene.cusize;
511          while (s*(OCTSCALE/2) > av->rad*ambacc) {
512                  if (at->kid == NULL)
513                          if ((at->kid = newambtree()) == NULL)
514 <                                goto memerr;
514 >                                error(SYSTEM, "out of memory in avinsert");
515                  s *= 0.5;
516                  branch = 0;
517                  for (i = 0; i < 3; i++)
# Line 376 | Line 521 | double  s;
521                          }
522                  at = at->kid + branch;
523          }
524 <        av->next = at->alist;
525 <        at->alist = av;
526 <        return;
527 < memerr:
528 <        error(SYSTEM, "out of memory in avinsert");
524 >        avh.next = at->alist;           /* order by increasing level */
525 >        for (ap = &avh; ap->next != NULL; ap = ap->next)
526 >                if (ap->next->lvl >= av->lvl)
527 >                        break;
528 >        av->next = ap->next;
529 >        ap->next = av;
530 >        at->alist = avh.next;
531   }
532 +
533 +
534 + static
535 + unloadatree(at, f)                      /* unload an ambient value tree */
536 + register AMBTREE  *at;
537 + int     (*f)();
538 + {
539 +        register AMBVAL  *av;
540 +        register int  i;
541 +                                        /* transfer values at this node */
542 +        for (av = at->alist; av != NULL; av = at->alist) {
543 +                at->alist = av->next;
544 +                (*f)(av);
545 +        }
546 +        if (at->kid == NULL)
547 +                return;
548 +        for (i = 0; i < 8; i++)         /* transfer and free children */
549 +                unloadatree(at->kid+i, f);
550 +        freeambtree(at->kid);
551 +        at->kid = NULL;
552 + }
553 +
554 +
555 + static struct avl {
556 +        AMBVAL  *p;
557 +        unsigned long   t;
558 + }       *avlist1;                       /* ambient value list with ticks */
559 + static AMBVAL   **avlist2;              /* memory positions for sorting */
560 + static int      i_avlist;               /* index for lists */
561 +
562 +
563 + static
564 + av2list(av)
565 + register AMBVAL *av;
566 + {
567 + #ifdef DEBUG
568 +        if (i_avlist >= nambvals)
569 +                error(CONSISTENCY, "too many ambient values in av2list1");
570 + #endif
571 +        avlist1[i_avlist].p = avlist2[i_avlist] = av;
572 +        avlist1[i_avlist++].t = av->latick;
573 + }
574 +
575 +
576 + static int
577 + alatcmp(av1, av2)                       /* compare ambient values for MRA */
578 + struct avl      *av1, *av2;
579 + {
580 +        register long  lc = av2->t - av1->t;
581 +        return(lc<0 ? -1 : lc>0 ? 1 : 0);
582 + }
583 +
584 +
585 + static int
586 + aposcmp(avp1, avp2)                     /* compare ambient value positions */
587 + AMBVAL  **avp1, **avp2;
588 + {
589 +        return(*avp1 - *avp2);
590 + }
591 +
592 +
593 + #if 1
594 + static int
595 + avlmemi(avaddr)                         /* find list position from address */
596 + AMBVAL  *avaddr;
597 + {
598 +        register AMBVAL  **avlpp;
599 +
600 +        avlpp = (AMBVAL **)bsearch((char *)&avaddr, (char *)avlist2,
601 +                        nambvals, sizeof(AMBVAL *), aposcmp);
602 +        if (avlpp == NULL)
603 +                error(CONSISTENCY, "address not found in avlmemi");
604 +        return(avlpp - avlist2);
605 + }
606 + #else
607 + #define avlmemi(avaddr) ((AMBVAL **)bsearch((char *)&avaddr,(char *)avlist2, \
608 +                                nambvals,sizeof(AMBVAL *),aposcmp) - avlist2)
609 + #endif
610 +
611 +
612 + static
613 + sortambvals(always)                     /* resort ambient values */
614 + int     always;
615 + {
616 +        AMBTREE  oldatrunk;
617 +        AMBVAL  tav, *tap, *pnext;
618 +        register int    i, j;
619 +                                        /* see if it's time yet */
620 +        if (!always && (ambclock++ < lastsort+sortintvl ||
621 +                        nambvals < SORT_THRESH))
622 +                return;
623 +        /*
624 +         * The idea here is to minimize memory thrashing
625 +         * in VM systems by improving reference locality.
626 +         * We do this by periodically sorting our stored ambient
627 +         * values in memory in order of most recently to least
628 +         * recently accessed.  This ordering was chosen so that new
629 +         * ambient values (which tend to be less important) go into
630 +         * higher memory with the infrequently accessed values.
631 +         *      Since we expect our values to need sorting less
632 +         * frequently as the process continues, we double our
633 +         * waiting interval after each call.
634 +         *      This routine is also called by setambacc() with
635 +         * the "always" parameter set to 1 so that the ambient
636 +         * tree will be rebuilt with the new accuracy parameter.
637 +         */
638 +        if (tracktime) {                /* allocate pointer arrays to sort */
639 +                avlist2 = (AMBVAL **)malloc(nambvals*sizeof(AMBVAL *));
640 +                avlist1 = (struct avl *)malloc(nambvals*sizeof(struct avl));
641 +        } else {
642 +                avlist2 = NULL;
643 +                avlist1 = NULL;
644 +        }
645 +        if (avlist1 == NULL) {          /* no time tracking -- rebuild tree? */
646 +                if (avlist2 != NULL)
647 +                        free((char *)avlist2);
648 +                if (always) {           /* rebuild without sorting */
649 +                        copystruct(&oldatrunk, &atrunk);
650 +                        atrunk.alist = NULL;
651 +                        atrunk.kid = NULL;
652 +                        unloadatree(&oldatrunk, avinsert);
653 +                }
654 +        } else {                        /* sort memory by last access time */
655 +                /*
656 +                 * Sorting memory is tricky because it isn't contiguous.
657 +                 * We have to sort an array of pointers by MRA and also
658 +                 * by memory position.  We then copy values in "loops"
659 +                 * to minimize memory hits.  Nevertheless, we will visit
660 +                 * everyone at least twice, and this is an expensive process
661 +                 * when we're thrashing, which is when we need to do it.
662 +                 */
663 + #ifdef DEBUG
664 +                sprintf(errmsg, "sorting %u ambient values at ambclock=%lu...",
665 +                                nambvals, ambclock);
666 +                eputs(errmsg);
667 + #endif
668 +                i_avlist = 0;
669 +                unloadatree(&atrunk, av2list);  /* empty current tree */
670 + #ifdef DEBUG
671 +                if (i_avlist < nambvals)
672 +                        error(CONSISTENCY, "missing ambient values in sortambvals");
673 + #endif
674 +                qsort((char *)avlist1, nambvals, sizeof(struct avl), alatcmp);
675 +                qsort((char *)avlist2, nambvals, sizeof(AMBVAL *), aposcmp);
676 +                for (i = 0; i < nambvals; i++) {
677 +                        if (avlist1[i].p == NULL)
678 +                                continue;
679 +                        tap = avlist2[i];
680 +                        copystruct(&tav, tap);
681 +                        for (j = i; (pnext = avlist1[j].p) != tap;
682 +                                        j = avlmemi(pnext)) {
683 +                                copystruct(avlist2[j], pnext);
684 +                                avinsert(avlist2[j]);
685 +                                avlist1[j].p = NULL;
686 +                        }
687 +                        copystruct(avlist2[j], &tav);
688 +                        avinsert(avlist2[j]);
689 +                        avlist1[j].p = NULL;
690 +                }
691 +                free((char *)avlist1);
692 +                free((char *)avlist2);
693 +                                                /* compute new sort interval */
694 +                sortintvl = ambclock - lastsort;
695 +                if (sortintvl >= MAX_SORT_INTVL/2)
696 +                        sortintvl = MAX_SORT_INTVL;
697 +                else
698 +                        sortintvl <<= 1;        /* wait twice as long next */
699 + #ifdef DEBUG
700 +                eputs("done\n");
701 + #endif
702 +        }
703 +        if (ambclock >= MAXACLOCK)
704 +                ambclock = MAXACLOCK/2;
705 +        lastsort = ambclock;
706 + }
707 +
708 +
709 + #ifdef  F_SETLKW
710 +
711 + static
712 + aflock(typ)                     /* lock/unlock ambient file */
713 + int  typ;
714 + {
715 +        static struct flock  fls;       /* static so initialized to zeroes */
716 +
717 +        fls.l_type = typ;
718 +        if (fcntl(fileno(ambfp), F_SETLKW, &fls) < 0)
719 +                error(SYSTEM, "cannot (un)lock ambient file");
720 + }
721 +
722 +
723 + int
724 + ambsync()                       /* synchronize ambient file */
725 + {
726 +        static FILE  *ambinp = NULL;
727 +        static long  lastpos = -1;
728 +        long  flen;
729 +        AMBVAL  avs;
730 +        register int  n;
731 +
732 +        if (nunflshed == 0)
733 +                return(0);
734 +        if (lastpos < 0)        /* initializing (locked in initambfile) */
735 +                goto syncend;
736 +                                /* gain exclusive access */
737 +        aflock(F_WRLCK);
738 +                                /* see if file has grown */
739 +        if ((flen = lseek(fileno(ambfp), 0L, 2)) < 0)
740 +                goto seekerr;
741 +        if (n = flen - lastpos) {               /* file has grown */
742 +                if (ambinp == NULL) {           /* use duplicate filedes */
743 +                        ambinp = fdopen(dup(fileno(ambfp)), "r");
744 +                        if (ambinp == NULL)
745 +                                error(SYSTEM, "fdopen failed in ambsync");
746 +                }
747 +                if (fseek(ambinp, lastpos, 0) < 0)
748 +                        goto seekerr;
749 +                while (n >= AMBVALSIZ) {        /* load contributed values */
750 +                        if (!readambval(&avs, ambinp)) {
751 +                                sprintf(errmsg,
752 +                                "ambient file corrupted near character %ld",
753 +                                                flen - n);
754 +                                error(WARNING, errmsg);
755 +                                break;
756 +                        }
757 +                        avinsert(avstore(&avs));
758 +                        n -= AMBVALSIZ;
759 +                }
760 +                /*** seek always as safety measure
761 +                if (n) ***/                     /* alignment */
762 +                        if (lseek(fileno(ambfp), flen-n, 0) < 0)
763 +                                goto seekerr;
764 +        }
765 + #ifdef  DEBUG
766 +        if (ambfp->_ptr - ambfp->_base != nunflshed*AMBVALSIZ) {
767 +                sprintf(errmsg, "ambient file buffer at %d rather than %d",
768 +                                ambfp->_ptr - ambfp->_base,
769 +                                nunflshed*AMBVALSIZ);
770 +                error(CONSISTENCY, errmsg);
771 +        }
772 + #endif
773 + syncend:
774 +        n = fflush(ambfp);                      /* calls write() at last */
775 +        if ((lastpos = lseek(fileno(ambfp), 0L, 1)) < 0)
776 +                goto seekerr;
777 +        aflock(F_UNLCK);                        /* release file */
778 +        nunflshed = 0;
779 +        return(n);
780 + seekerr:
781 +        error(SYSTEM, "seek failed in ambsync");
782 + }
783 +
784 + #else
785 +
786 + int
787 + ambsync()                       /* flush ambient file */
788 + {
789 +        if (nunflshed == 0)
790 +                return(0);
791 +        nunflshed = 0;
792 +        return(fflush(ambfp));
793 + }
794 +
795 + #endif

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines