ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/radiance/ray/src/rt/ambient.c
Revision: 2.38
Committed: Tue Jul 9 13:32:35 1996 UTC (27 years, 9 months ago) by greg
Content type: text/plain
Branch: MAIN
Changes since 2.37: +4 -3 lines
Log Message:
fixed potential problem with alatcmp() function on 16-bit machines
made error-reporting version of avlmemi() the default

File Contents

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