29af071bd4f52a55f6b7caa20626f98ee4e65dfd
[sbcl.git] / src / pcl / cache.lisp
1 ;;;; the basics of the PCL wrapper cache mechanism
2
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
5
6 ;;;; This software is derived from software originally released by Xerox
7 ;;;; Corporation. Copyright and release statements follow. Later modifications
8 ;;;; to the software are in the public domain and are provided with
9 ;;;; absolutely no warranty. See the COPYING and CREDITS files for more
10 ;;;; information.
11
12 ;;;; copyright information from original PCL sources:
13 ;;;;
14 ;;;; Copyright (c) 1985, 1986, 1987, 1988, 1989, 1990 Xerox Corporation.
15 ;;;; All rights reserved.
16 ;;;;
17 ;;;; Use and copying of this software and preparation of derivative works based
18 ;;;; upon this software are permitted. Any distribution of this software or
19 ;;;; derivative works must comply with all applicable United States export
20 ;;;; control laws.
21 ;;;;
22 ;;;; This software is made available AS IS, and Xerox Corporation makes no
23 ;;;; warranty about the software, its performance or its conformity to any
24 ;;;; specification.
25
26 (in-package "SB-PCL")
27 \f
28 ;;; Ye olde CMUCL comment follows, but it seems likely that the paper
29 ;;; that would be inserted would resemble Kiczales and Rodruigez,
30 ;;; Efficient Method Dispatch in PCL, ACM 1990.  Some of the details
31 ;;; changed between that paper and "May Day PCL" of 1992; some other
32 ;;; details have changed since, but reading that paper gives the broad
33 ;;; idea.
34 ;;;
35 ;;; The caching algorithm implemented:
36 ;;;
37 ;;; << put a paper here >>
38 ;;;
39 ;;; For now, understand that as far as most of this code goes, a cache
40 ;;; has two important properties. The first is the number of wrappers
41 ;;; used as keys in each cache line. Throughout this code, this value
42 ;;; is always called NKEYS. The second is whether or not the cache
43 ;;; lines of a cache store a value. Throughout this code, this always
44 ;;; called VALUEP.
45 ;;;
46 ;;; Depending on these values, there are three kinds of caches.
47 ;;;
48 ;;; NKEYS = 1, VALUEP = NIL
49 ;;;
50 ;;; In this kind of cache, each line is 1 word long. No cache locking
51 ;;; is needed since all read's in the cache are a single value.
52 ;;; Nevertheless line 0 (location 0) is reserved, to ensure that
53 ;;; invalid wrappers will not get a first probe hit.
54 ;;;
55 ;;; To keep the code simpler, a cache lock count does appear in
56 ;;; location 0 of these caches, that count is incremented whenever
57 ;;; data is written to the cache. But, the actual lookup code (see
58 ;;; make-dlap) doesn't need to do locking when reading the cache.
59 ;;;
60 ;;; NKEYS = 1, VALUEP = T
61 ;;;
62 ;;; In this kind of cache, each line is 2 words long. Cache locking
63 ;;; must be done to ensure the synchronization of cache reads. Line 0
64 ;;; of the cache (location 0) is reserved for the cache lock count.
65 ;;; Location 1 of the cache is unused (in effect wasted).
66 ;;;
67 ;;; NKEYS > 1
68 ;;;
69 ;;; In this kind of cache, the 0 word of the cache holds the lock
70 ;;; count. The 1 word of the cache is line 0. Line 0 of these caches
71 ;;; is not reserved.
72 ;;;
73 ;;; This is done because in this sort of cache, the overhead of doing
74 ;;; the cache probe is high enough that the 1+ required to offset the
75 ;;; location is not a significant cost. In addition, because of the
76 ;;; larger line sizes, the space that would be wasted by reserving
77 ;;; line 0 to hold the lock count is more significant.
78 \f
79 ;;; caches
80 ;;;
81 ;;; A cache is essentially just a vector. The use of the individual
82 ;;; `words' in the vector depends on particular properties of the
83 ;;; cache as described above.
84 ;;;
85 ;;; This defines an abstraction for caches in terms of their most
86 ;;; obvious implementation as simple vectors. But, please notice that
87 ;;; part of the implementation of this abstraction, is the function
88 ;;; lap-out-cache-ref. This means that most port-specific
89 ;;; modifications to the implementation of caches will require
90 ;;; corresponding port-specific modifications to the lap code
91 ;;; assembler.
92 (defmacro cache-vector-ref (cache-vector location)
93   `(svref (the simple-vector ,cache-vector)
94           (sb-ext:truly-the fixnum ,location)))
95
96 (defmacro cache-vector-size (cache-vector)
97   `(array-dimension (the simple-vector ,cache-vector) 0))
98
99 (defmacro cache-vector-lock-count (cache-vector)
100   `(cache-vector-ref ,cache-vector 0))
101
102 (defun flush-cache-vector-internal (cache-vector)
103   ;; FIXME: To my eye this PCL-LOCK implies we should be holding the
104   ;; lock whenever we play with any cache vector, which doesn't seem
105   ;; to be true. On the other hand that would be too expensive as
106   ;; well, since it would mean serialization across all GFs.
107   (with-pcl-lock
108     (fill (the simple-vector cache-vector) nil)
109     (setf (cache-vector-lock-count cache-vector) 0))
110   cache-vector)
111
112 ;;; Return an empty cache vector
113 (defun get-cache-vector (size)
114   (declare (type (and unsigned-byte fixnum) size))
115   (let ((cv (make-array size :initial-element nil)))
116     (setf (cache-vector-lock-count cv) 0)
117     cv))
118
119 (defmacro modify-cache (cache-vector &body body)
120   `(with-pcl-lock
121      ;; This locking scheme is less the sufficient, and not what the
122      ;; PCL implementors had planned: apparently we should increment
123      ;; the lock count atomically, and all cache users should check
124      ;; the count before and after they touch cache: if the counts
125      ;; match the cache was not altered, if they don't match the
126      ;; work needs to be redone.
127      ;;
128      ;; We probably want to re-engineer things so that the whole
129      ;; cache vector gets replaced atomically when we do things
130      ;; to it that could affect others.
131      (multiple-value-prog1
132        (progn ,@body)
133        (let ((old-count (cache-vector-lock-count ,cache-vector)))
134          (declare (fixnum old-count))
135          (setf (cache-vector-lock-count ,cache-vector)
136                (if (= old-count most-positive-fixnum)
137                    1
138                    (1+ old-count)))))))
139
140 (eval-when (:compile-toplevel :load-toplevel :execute)
141   (declaim (ftype (function (fixnum) (values (and unsigned-byte fixnum) &optional))
142                   power-of-two-ceiling))
143   (defun power-of-two-ceiling (x)
144     ;; (expt 2 (ceiling (log x 2)))
145     (ash 1 (integer-length (1- x)))))
146
147 ;;; FIXME: We should probably keep just one of these -- or at least use just
148 ;;; one.
149 (declaim (inline compute-line-size))
150 (defun compute-line-size (x)
151   (power-of-two-ceiling x))
152
153 (defconstant +nkeys-limit+ 256)
154
155 (defstruct (cache (:constructor make-cache ())
156                   (:copier copy-cache-internal))
157   (owner nil)
158   (nkeys 1 :type (integer 1 #.+nkeys-limit+))
159   (valuep nil :type (member nil t))
160   (nlines 0 :type fixnum)
161   (limit-fn #'default-limit-fn :type function)
162   (mask 0 :type fixnum)
163   (size 0 :type fixnum)
164   (line-size 1 :type (integer 1 #.(power-of-two-ceiling (1+ +nkeys-limit+))))
165   (max-location 0 :type fixnum)
166   (vector #() :type simple-vector)
167   (overflow nil :type list))
168
169 #-sb-fluid (declaim (sb-ext:freeze-type cache))
170 \f
171 ;;;; wrapper cache numbers
172
173 ;;; The constant WRAPPER-CACHE-NUMBER-ADDS-OK controls the number of
174 ;;; non-zero bits wrapper cache numbers will have.
175 ;;;
176 ;;; The value of this constant is the number of wrapper cache numbers
177 ;;; which can be added and still be certain the result will be a
178 ;;; fixnum. This is used by all the code that computes primary cache
179 ;;; locations from multiple wrappers.
180 ;;;
181 ;;; The value of this constant is used to derive the next two which
182 ;;; are the forms of this constant which it is more convenient for the
183 ;;; runtime code to use.
184 (defconstant wrapper-cache-number-length
185   (integer-length (1- layout-clos-hash-limit)))
186 (defconstant wrapper-cache-number-mask (1- layout-clos-hash-limit))
187 (defconstant wrapper-cache-number-adds-ok
188   (truncate most-positive-fixnum (1- layout-clos-hash-limit)))
189 \f
190 ;;;; wrappers themselves
191
192 ;;; FIXME: delete this comment, possibly replacing it with a reference
193 ;;; to Kiczales and Rodruigez
194 ;;;
195 ;;; This caching algorithm requires that wrappers have more than one
196 ;;; wrapper cache number. You should think of these multiple numbers
197 ;;; as being in columns. That is, for a given cache, the same column
198 ;;; of wrapper cache numbers will be used.
199 ;;;
200 ;;; If at some point the cache distribution of a cache gets bad, the
201 ;;; cache can be rehashed by switching to a different column.
202 ;;;
203 ;;; The columns are referred to by field number which is that number
204 ;;; which, when used as a second argument to wrapper-ref, will return
205 ;;; that column of wrapper cache number.
206 ;;;
207 ;;; This code is written to allow flexibility as to how many wrapper
208 ;;; cache numbers will be in each wrapper, and where they will be
209 ;;; located. It is also set up to allow port specific modifications to
210 ;;; `pack' the wrapper cache numbers on machines where the addressing
211 ;;; modes make that a good idea.
212
213 (unless (boundp '*the-class-t*)
214   (setq *the-class-t* nil))
215
216 (defun get-cache (nkeys valuep limit-fn nlines)
217   (let ((cache (make-cache)))
218     (declare (type cache cache))
219     (multiple-value-bind (cache-mask actual-size line-size nlines)
220         (compute-cache-parameters nkeys valuep nlines)
221       (setf (cache-nkeys cache) nkeys
222             (cache-valuep cache) valuep
223             (cache-nlines cache) nlines
224             (cache-limit-fn cache) limit-fn
225             (cache-mask cache) cache-mask
226             (cache-size cache) actual-size
227             (cache-line-size cache) line-size
228             (cache-max-location cache) (let ((line (1- nlines)))
229                                          (if (= nkeys 1)
230                                              (* line line-size)
231                                              (1+ (* line line-size))))
232             (cache-vector cache) (get-cache-vector actual-size)
233             (cache-overflow cache) nil)
234       cache)))
235
236 (defun get-cache-from-cache (old-cache new-nlines)
237   (let ((nkeys (cache-nkeys old-cache))
238         (valuep (cache-valuep old-cache))
239         (cache (make-cache)))
240     (declare (type cache cache))
241     (multiple-value-bind (cache-mask actual-size line-size nlines)
242         (if (= new-nlines (cache-nlines old-cache))
243             (values (cache-mask old-cache) (cache-size old-cache)
244                     (cache-line-size old-cache) (cache-nlines old-cache))
245             (compute-cache-parameters nkeys valuep new-nlines))
246       (setf (cache-owner cache) (cache-owner old-cache)
247             (cache-nkeys cache) nkeys
248             (cache-valuep cache) valuep
249             (cache-nlines cache) nlines
250             (cache-limit-fn cache) (cache-limit-fn old-cache)
251             (cache-mask cache) cache-mask
252             (cache-size cache) actual-size
253             (cache-line-size cache) line-size
254             (cache-max-location cache) (let ((line (1- nlines)))
255                                          (if (= nkeys 1)
256                                              (* line line-size)
257                                              (1+ (* line line-size))))
258             (cache-vector cache) (get-cache-vector actual-size)
259             (cache-overflow cache) nil)
260       cache)))
261
262 (defun copy-cache (old-cache)
263   (let* ((new-cache (copy-cache-internal old-cache))
264          (size (cache-size old-cache))
265          (old-vector (cache-vector old-cache))
266          (new-vector (get-cache-vector size)))
267     (declare (simple-vector old-vector new-vector))
268     (dotimes-fixnum (i size)
269       (setf (svref new-vector i) (svref old-vector i)))
270     (setf (cache-vector new-cache) new-vector)
271     new-cache))
272
273 (defun compute-cache-parameters (nkeys valuep nlines-or-cache-vector)
274   ;;(declare (values cache-mask actual-size line-size nlines))
275   (declare (fixnum nkeys))
276   (if (= nkeys 1)
277       (let* ((line-size (if valuep 2 1))
278              (cache-size (etypecase nlines-or-cache-vector
279                            (fixnum
280                             (* line-size
281                                (power-of-two-ceiling nlines-or-cache-vector)))
282                            (vector
283                             (cache-vector-size nlines-or-cache-vector)))))
284         (declare (type (and unsigned-byte fixnum) line-size cache-size))
285         (values (logxor (1- cache-size) (1- line-size))
286                 cache-size
287                 line-size
288                 (floor cache-size line-size)))
289       (let* ((line-size (power-of-two-ceiling (if valuep (1+ nkeys) nkeys)))
290              (cache-size (etypecase nlines-or-cache-vector
291                            (fixnum
292                             (* line-size
293                                 (power-of-two-ceiling nlines-or-cache-vector)))
294                            (vector
295                              (1- (cache-vector-size nlines-or-cache-vector))))))
296         (declare (fixnum line-size cache-size))
297         (values (logxor (1- cache-size) (1- line-size))
298                 (1+ cache-size)
299                 line-size
300                 (floor cache-size line-size)))))
301 \f
302 ;;; the various implementations of computing a primary cache location from
303 ;;; wrappers. Because some implementations of this must run fast there are
304 ;;; several implementations of the same algorithm.
305 ;;;
306 ;;; The algorithm is:
307 ;;;
308 ;;;  SUM       over the wrapper cache numbers,
309 ;;;  ENSURING  that the result is a fixnum
310 ;;;  MASK      the result against the mask argument.
311
312 ;;; The basic functional version. This is used by the cache miss code to
313 ;;; compute the primary location of an entry.
314 (defun compute-primary-cache-location (mask wrappers)
315   (declare (fixnum mask))
316   (if (not (listp wrappers))
317       (logand mask (layout-clos-hash wrappers))
318       (let ((location 0)
319             (i 0))
320         (declare (fixnum location i))
321         (dolist (wrapper wrappers)
322           ;; First add the cache number of this wrapper to location.
323           (let ((wrapper-cache-number (layout-clos-hash wrapper)))
324             (if (zerop wrapper-cache-number)
325                 (return-from compute-primary-cache-location 0)
326                 (incf location wrapper-cache-number)))
327           ;; Then, if we are working with lots of wrappers, deal with
328           ;; the wrapper-cache-number-mask stuff.
329           (when (and (not (zerop i))
330                      (zerop (mod i wrapper-cache-number-adds-ok)))
331             (setq location
332                   (logand location wrapper-cache-number-mask)))
333           (incf i))
334         (1+ (logand mask location)))))
335
336 ;;; This version is called on a cache line. It fetches the wrappers
337 ;;; from the cache line and determines the primary location. Various
338 ;;; parts of the cache filling code call this to determine whether it
339 ;;; is appropriate to displace a given cache entry.
340 ;;;
341 ;;; If this comes across a wrapper whose CACHE-NO is 0, it returns the
342 ;;; symbol invalid to suggest to its caller that it would be provident
343 ;;; to blow away the cache line in question.
344 (defun compute-primary-cache-location-from-location (to-cache
345                                                      from-location
346                                                      &optional
347                                                      (from-cache to-cache))
348   (declare (type cache to-cache from-cache) (fixnum from-location))
349   (let ((result 0)
350         (cache-vector (cache-vector from-cache))
351         (mask (cache-mask to-cache))
352         (nkeys (cache-nkeys to-cache)))
353     (declare (fixnum result mask nkeys)
354              (simple-vector cache-vector))
355     (dotimes-fixnum (i nkeys)
356       ;; FIXME: Sometimes we get NIL here as wrapper, apparently because
357       ;; another thread has stomped on the cache-vector.
358       (let* ((wrapper (cache-vector-ref cache-vector (+ i from-location)))
359              (wcn (layout-clos-hash wrapper)))
360         (incf result wcn))
361       (when (and (not (zerop i))
362                  (zerop (mod i wrapper-cache-number-adds-ok)))
363         (setq result (logand result wrapper-cache-number-mask))))
364     (if (= nkeys 1)
365         (logand mask result)
366         (1+ (logand mask result)))))
367 \f
368 (defmacro with-local-cache-functions ((cache) &body body)
369   `(let ((.cache. ,cache))
370      (declare (type cache .cache.))
371      (labels ((cache () .cache.)
372               (nkeys () (cache-nkeys .cache.))
373               (line-size () (cache-line-size .cache.))
374               (c-vector () (cache-vector .cache.))
375               (valuep () (cache-valuep .cache.))
376               (nlines () (cache-nlines .cache.))
377               (max-location () (cache-max-location .cache.))
378               (limit-fn () (cache-limit-fn .cache.))
379               (size () (cache-size .cache.))
380               (mask () (cache-mask .cache.))
381               (overflow () (cache-overflow .cache.))
382               ;;
383               ;; Return T IFF this cache location is reserved.  The
384               ;; only time this is true is for line number 0 of an
385               ;; nkeys=1 cache.
386               ;;
387               (line-reserved-p (line)
388                 (declare (fixnum line))
389                 (and (= (nkeys) 1)
390                      (= line 0)))
391               ;;
392               (location-reserved-p (location)
393                 (declare (fixnum location))
394                 (and (= (nkeys) 1)
395                      (= location 0)))
396               ;;
397               ;; Given a line number, return the cache location.
398               ;; This is the value that is the second argument to
399               ;; cache-vector-ref.  Basically, this deals with the
400               ;; offset of nkeys>1 caches and multiplies by line
401               ;; size.
402               ;;
403               (line-location (line)
404                 (declare (fixnum line))
405                 (when (line-reserved-p line)
406                   (error "line is reserved"))
407                 (if (= (nkeys) 1)
408                     (the fixnum (* line (line-size)))
409                     (the fixnum (1+ (the fixnum (* line (line-size)))))))
410               ;;
411               ;; Given a cache location, return the line.  This is
412               ;; the inverse of LINE-LOCATION.
413               ;;
414               (location-line (location)
415                 (declare (fixnum location))
416                 (if (= (nkeys) 1)
417                     (floor location (line-size))
418                     (floor (the fixnum (1- location)) (line-size))))
419               ;;
420               ;; Given a line number, return the wrappers stored at
421               ;; that line.  As usual, if nkeys=1, this returns a
422               ;; single value.  Only when nkeys>1 does it return a
423               ;; list.  An error is signalled if the line is
424               ;; reserved.
425               ;;
426               (line-wrappers (line)
427                 (declare (fixnum line))
428                 (when (line-reserved-p line) (error "Line is reserved."))
429                 (location-wrappers (line-location line)))
430               ;;
431               (location-wrappers (location) ; avoid multiplies caused by line-location
432                 (declare (fixnum location))
433                 (if (= (nkeys) 1)
434                     (cache-vector-ref (c-vector) location)
435                     (let ((list (make-list (nkeys)))
436                           (vector (c-vector)))
437                       (declare (simple-vector vector))
438                       (dotimes (i (nkeys) list)
439                         (declare (fixnum i))
440                         (setf (nth i list)
441                               (cache-vector-ref vector (+ location i)))))))
442               ;;
443               ;; Given a line number, return true IFF the line's
444               ;; wrappers are the same as wrappers.
445               ;;
446               (line-matches-wrappers-p (line wrappers)
447                 (declare (fixnum line))
448                 (and (not (line-reserved-p line))
449                      (location-matches-wrappers-p (line-location line)
450                                                   wrappers)))
451               ;;
452               (location-matches-wrappers-p (loc wrappers) ; must not be reserved
453                 (declare (fixnum loc))
454                 (let ((cache-vector (c-vector)))
455                   (declare (simple-vector cache-vector))
456                   (if (= (nkeys) 1)
457                       (eq wrappers (cache-vector-ref cache-vector loc))
458                       (dotimes (i (nkeys) t)
459                         (declare (fixnum i))
460                         (unless (eq (pop wrappers)
461                                     (cache-vector-ref cache-vector (+ loc i)))
462                           (return nil))))))
463               ;;
464               ;; Given a line number, return the value stored at that line.
465               ;; If valuep is NIL, this returns NIL.  As with line-wrappers,
466               ;; an error is signalled if the line is reserved.
467               ;;
468               (line-value (line)
469                 (declare (fixnum line))
470                 (when (line-reserved-p line) (error "Line is reserved."))
471                 (location-value (line-location line)))
472               ;;
473               (location-value (loc)
474                 (declare (fixnum loc))
475                 (and (valuep)
476                      (cache-vector-ref (c-vector) (+ loc (nkeys)))))
477               ;;
478               ;; Given a line number, return true IFF that line has data in
479               ;; it.  The state of the wrappers stored in the line is not
480               ;; checked.  An error is signalled if line is reserved.
481               (line-full-p (line)
482                 (when (line-reserved-p line) (error "Line is reserved."))
483                 (not (null (cache-vector-ref (c-vector) (line-location line)))))
484               ;;
485               ;; Given a line number, return true IFF the line is full and
486               ;; there are no invalid wrappers in the line, and the line's
487               ;; wrappers are different from wrappers.
488               ;; An error is signalled if the line is reserved.
489               ;;
490               (line-valid-p (line wrappers)
491                 (declare (fixnum line))
492                 (when (line-reserved-p line) (error "Line is reserved."))
493                 (location-valid-p (line-location line) wrappers))
494               ;;
495               (location-valid-p (loc wrappers)
496                 (declare (fixnum loc))
497                 (let ((cache-vector (c-vector))
498                       (wrappers-mismatch-p (null wrappers)))
499                   (declare (simple-vector cache-vector))
500                   (dotimes (i (nkeys) wrappers-mismatch-p)
501                     (declare (fixnum i))
502                     (let ((wrapper (cache-vector-ref cache-vector (+ loc i))))
503                       (when (or (null wrapper)
504                                 (invalid-wrapper-p wrapper))
505                         (return nil))
506                       (unless (and wrappers
507                                    (eq wrapper
508                                        (if (consp wrappers)
509                                            (pop wrappers)
510                                            wrappers)))
511                         (setq wrappers-mismatch-p t))))))
512               ;;
513               ;; How many unreserved lines separate line-1 and line-2.
514               ;;
515               (line-separation (line-1 line-2)
516                 (declare (fixnum line-1 line-2))
517                 (let ((diff (the fixnum (- line-2 line-1))))
518                   (declare (fixnum diff))
519                   (when (minusp diff)
520                     (setq diff (+ diff (nlines)))
521                     (when (line-reserved-p 0)
522                       (setq diff (1- diff))))
523                   diff))
524               ;;
525               ;; Given a cache line, get the next cache line.  This will not
526               ;; return a reserved line.
527               ;;
528               (next-line (line)
529                 (declare (fixnum line))
530                 (if (= line (the fixnum (1- (nlines))))
531                     (if (line-reserved-p 0) 1 0)
532                     (the fixnum (1+ line))))
533               ;;
534               (next-location (loc)
535                 (declare (fixnum loc))
536                 (if (= loc (max-location))
537                     (if (= (nkeys) 1)
538                         (line-size)
539                         1)
540                     (the fixnum (+ loc (line-size)))))
541               ;;
542               ;; Given a line which has a valid entry in it, this
543               ;; will return the primary cache line of the wrappers
544               ;; in that line.  We just call
545               ;; COMPUTE-PRIMARY-CACHE-LOCATION-FROM-LOCATION, this
546               ;; is an easier packaging up of the call to it.
547               ;;
548               (line-primary (line)
549                 (declare (fixnum line))
550                 (location-line (line-primary-location line)))
551               ;;
552               (line-primary-location (line)
553                 (declare (fixnum line))
554                 (compute-primary-cache-location-from-location
555                  (cache) (line-location line))))
556        (declare (ignorable #'cache #'nkeys #'line-size #'c-vector #'valuep
557                            #'nlines #'max-location #'limit-fn #'size
558                            #'mask #'overflow #'line-reserved-p
559                            #'location-reserved-p #'line-location
560                            #'location-line #'line-wrappers #'location-wrappers
561                            #'line-matches-wrappers-p
562                            #'location-matches-wrappers-p
563                            #'line-value #'location-value #'line-full-p
564                            #'line-valid-p #'location-valid-p
565                            #'line-separation #'next-line #'next-location
566                            #'line-primary #'line-primary-location))
567        ,@body)))
568 \f
569 ;;; Here is where we actually fill, recache and expand caches.
570 ;;;
571 ;;; The functions FILL-CACHE and PROBE-CACHE are the ONLY external
572 ;;; entrypoints into this code.
573 ;;;
574 ;;; FILL-CACHE returns 1 value: a new cache
575 ;;;
576 ;;;   a wrapper field number
577 ;;;   a cache
578 ;;;   a mask
579 ;;;   an absolute cache size (the size of the actual vector)
580 ;;; It tries to re-adjust the cache every time it makes a new fill.
581 ;;; The intuition here is that we want uniformity in the number of
582 ;;; probes needed to find an entry. Furthermore, adjusting has the
583 ;;; nice property of throwing out any entries that are invalid.
584 (defvar *cache-expand-threshold* 1.25)
585
586 (defun fill-cache (cache wrappers value)
587   ;; FILL-CACHE won't return if WRAPPERS is nil, might as well check..
588   (aver wrappers)
589   (or (fill-cache-p nil cache wrappers value)
590       (expand-cache cache wrappers value)))
591
592 (defvar *check-cache-p* nil)
593
594 (defmacro maybe-check-cache (cache)
595   `(progn
596      (when *check-cache-p*
597        (check-cache ,cache))
598      ,cache))
599
600 (defun check-cache (cache)
601   (with-local-cache-functions (cache)
602     (let ((location (if (= (nkeys) 1) 0 1))
603           (limit (funcall (limit-fn) (nlines))))
604       (dotimes-fixnum (i (nlines) cache)
605         (when (and (not (location-reserved-p location))
606                    (line-full-p i))
607           (let* ((home-loc (compute-primary-cache-location-from-location
608                             cache location))
609                  (home (location-line (if (location-reserved-p home-loc)
610                                           (next-location home-loc)
611                                           home-loc)))
612                  (sep (when home (line-separation home i))))
613             (when (and sep (> sep limit))
614               (error "bad cache ~S ~@
615                       value at location ~W: ~W lines from its home. The limit is ~W."
616                      cache location sep limit))))
617         (setq location (next-location location))))))
618
619 (defun probe-cache (cache wrappers &optional default limit-fn)
620   (aver wrappers)
621   (with-local-cache-functions (cache)
622     (let* ((location (compute-primary-cache-location (mask) wrappers))
623            (limit (funcall (or limit-fn (limit-fn)) (nlines))))
624       (declare (fixnum location limit))
625       (when (location-reserved-p location)
626         (setq location (next-location location)))
627       (dotimes-fixnum (i (1+ limit))
628         (when (location-matches-wrappers-p location wrappers)
629           (return-from probe-cache (or (not (valuep))
630                                        (location-value location))))
631         (setq location (next-location location)))
632       (dolist (entry (overflow))
633         (when (equal (car entry) wrappers)
634           (return-from probe-cache (or (not (valuep))
635                                        (cdr entry)))))
636       default)))
637
638 (defun map-cache (function cache &optional set-p)
639   (with-local-cache-functions (cache)
640     (let ((set-p (and set-p (valuep))))
641       (dotimes-fixnum (i (nlines) cache)
642         (unless (or (line-reserved-p i) (not (line-valid-p i nil)))
643           (let ((value (funcall function (line-wrappers i) (line-value i))))
644             (when set-p
645               ;; FIXME: Cache modification: should we not be holding a lock?
646               (setf (cache-vector-ref (c-vector) (+ (line-location i) (nkeys)))
647                     value)))))
648       (dolist (entry (overflow))
649         (let ((value (funcall function (car entry) (cdr entry))))
650           (when set-p
651             (setf (cdr entry) value))))))
652   cache)
653
654 (defun cache-count (cache)
655   (with-local-cache-functions (cache)
656     (let ((count 0))
657       (declare (fixnum count))
658       (dotimes-fixnum (i (nlines) count)
659         (unless (line-reserved-p i)
660           (when (line-full-p i)
661             (incf count)))))))
662
663 (defun entry-in-cache-p (cache wrappers value)
664   (declare (ignore value))
665   (with-local-cache-functions (cache)
666     (dotimes-fixnum (i (nlines))
667       (unless (line-reserved-p i)
668         (when (equal (line-wrappers i) wrappers)
669           (return t))))))
670
671 ;;; returns T or NIL
672 ;;;
673 ;;; FIXME: Deceptive name as this has side-effects.
674 (defun fill-cache-p (forcep cache wrappers value)
675   (with-local-cache-functions (cache)
676     (let* ((location (compute-primary-cache-location (mask) wrappers))
677            (primary (location-line location)))
678       (declare (fixnum location primary))
679       ;; FIXME: I tried (aver (> location 0)) and (aver (not
680       ;; (location-reserved-p location))) here, on the basis that
681       ;; particularly passing a LOCATION of 0 for a cache with more
682       ;; than one key would cause PRIMARY to be -1.  However, the
683       ;; AVERs triggered during the bootstrap, and removing them
684       ;; didn't cause anything to break, so I've left them removed.
685       ;; I'm still confused as to what is right.  -- CSR, 2006-04-20
686       (multiple-value-bind (free emptyp)
687           (find-free-cache-line primary cache wrappers)
688         (when (or forcep emptyp)
689           (when (not emptyp)
690             (push (cons (line-wrappers free) (line-value free))
691                   (cache-overflow cache)))
692           ;; (fill-line free wrappers value)
693           (let ((line free))
694             (declare (fixnum line))
695             (when (line-reserved-p line)
696               (error "attempt to fill a reserved line"))
697             (let ((loc (line-location line))
698                   (cache-vector (c-vector)))
699               (declare (fixnum loc) (simple-vector cache-vector))
700               ;; FIXME: Cache modifications: should we not be holding
701               ;; a lock?
702               (cond ((= (nkeys) 1)
703                      (setf (cache-vector-ref cache-vector loc) wrappers)
704                      (when (valuep)
705                        (setf (cache-vector-ref cache-vector (1+ loc)) value)))
706                     (t
707                      (let ((i 0))
708                        (declare (fixnum i))
709                        (dolist (w wrappers)
710                          (setf (cache-vector-ref cache-vector (+ loc i)) w)
711                          (setq i (the fixnum (1+ i)))))
712                      (when (valuep)
713                        (setf (cache-vector-ref cache-vector (+ loc (nkeys)))
714                              value))))
715               (maybe-check-cache cache))))))))
716
717 ;;; FIXME: Deceptive name as this has side-effects
718 (defun fill-cache-from-cache-p (forcep cache from-cache from-line)
719   (declare (fixnum from-line))
720   (with-local-cache-functions (cache)
721     (let ((primary (location-line
722                     (compute-primary-cache-location-from-location
723                      cache (line-location from-line) from-cache))))
724       (declare (fixnum primary))
725       (multiple-value-bind (free emptyp)
726           (find-free-cache-line primary cache)
727         (when (or forcep emptyp)
728           (when (not emptyp)
729             (push (cons (line-wrappers free) (line-value free))
730                   (cache-overflow cache)))
731           ;;(transfer-line from-cache-vector from-line cache-vector free)
732           (let ((from-cache-vector (cache-vector from-cache))
733                 (to-cache-vector (c-vector))
734                 (to-line free))
735             (declare (fixnum to-line))
736             (if (line-reserved-p to-line)
737                 (error "transferring something into a reserved cache line")
738                 (let ((from-loc (line-location from-line))
739                       (to-loc (line-location to-line)))
740                   (declare (fixnum from-loc to-loc))
741                   (modify-cache to-cache-vector
742                                 (dotimes-fixnum (i (line-size))
743                                   (setf (cache-vector-ref to-cache-vector
744                                                           (+ to-loc i))
745                                         (cache-vector-ref from-cache-vector
746                                                           (+ from-loc i)))))))
747             (maybe-check-cache cache)))))))
748
749 ;;; returns: (values <cache>)
750 (defun expand-cache (cache wrappers value)
751   ;;(declare (values cache))
752   (with-local-cache-functions (cache)
753     (let ((ncache (get-cache-from-cache cache (* (nlines) 2))))
754       (labels ((do-one-fill-from-line (line)
755                  (unless (fill-cache-from-cache-p nil ncache cache line)
756                    (do-one-fill (line-wrappers line) (line-value line))))
757                (do-one-fill (wrappers value)
758                  (setq ncache (fill-cache-p t ncache wrappers value)))
759                (try-one-fill (wrappers value)
760                  (fill-cache-p nil ncache wrappers value)))
761         (dotimes-fixnum (i (nlines))
762           (when (and (null (line-reserved-p i))
763                      (line-valid-p i wrappers))
764             (do-one-fill-from-line i)))
765         (dolist (wrappers+value (cache-overflow cache))
766           (unless (try-one-fill (car wrappers+value) (cdr wrappers+value))
767             (do-one-fill (car wrappers+value) (cdr wrappers+value))))
768         (unless (try-one-fill wrappers value)
769           (do-one-fill wrappers value))
770         (maybe-check-cache ncache)))))
771 \f
772 (defvar *pcl-misc-random-state* (make-random-state))
773
774 ;;; This is the heart of the cache filling mechanism. It implements
775 ;;; the decisions about where entries are placed.
776 ;;;
777 ;;; Find a line in the cache at which a new entry can be inserted.
778 ;;;
779 ;;;   <line>
780 ;;;   <empty?>     is <line> in fact empty?
781 (defun find-free-cache-line (primary cache &optional wrappers)
782   ;;(declare (values line empty?))
783   (declare (fixnum primary))
784   (with-local-cache-functions (cache)
785     (when (line-reserved-p primary) (setq primary (next-line primary)))
786     (let ((limit (funcall (limit-fn) (nlines)))
787           (wrappedp nil)
788           (lines nil)
789           (p primary) (s primary))
790       (declare (fixnum p s limit))
791       (block find-free
792         (loop
793          ;; Try to find a free line starting at <s>. <p> is the
794          ;; primary line of the entry we are finding a free
795          ;; line for, it is used to compute the separations.
796          (do* ((line s (next-line line))
797                (nsep (line-separation p s) (1+ nsep)))
798               (())
799            (declare (fixnum line nsep))
800            (when (null (line-valid-p line wrappers)) ;If this line is empty or
801              (push line lines)          ;invalid, just use it.
802              (return-from find-free))
803            (when (and wrappedp (>= line primary))
804              ;; have gone all the way around the cache, time to quit
805              (return-from find-free-cache-line (values primary nil)))
806            (let ((osep (line-separation (line-primary line) line)))
807              (when (>= osep limit)
808                (return-from find-free-cache-line (values primary nil)))
809              (when (cond ((= nsep limit) t)
810                          ((= nsep osep)
811                           (zerop (random 2 *pcl-misc-random-state*)))
812                          ((> nsep osep) t)
813                          (t nil))
814                ;; See whether we can displace what is in this line so that we
815                ;; can use the line.
816                (when (= line (the fixnum (1- (nlines)))) (setq wrappedp t))
817                (setq p (line-primary line))
818                (setq s (next-line line))
819                (push line lines)
820                (return nil)))
821            (when (= line (the fixnum (1- (nlines)))) (setq wrappedp t)))))
822       ;; Do all the displacing.
823       (loop
824        (when (null (cdr lines)) (return nil))
825        (let ((dline (pop lines))
826              (line (car lines)))
827          (declare (fixnum dline line))
828          ;;Copy from line to dline (dline is known to be free).
829          (let ((from-loc (line-location line))
830                (to-loc (line-location dline))
831                (cache-vector (c-vector)))
832            (declare (fixnum from-loc to-loc) (simple-vector cache-vector))
833            (modify-cache cache-vector
834                          (dotimes-fixnum (i (line-size))
835                            (setf (cache-vector-ref cache-vector
836                                                    (+ to-loc i))
837                                  (cache-vector-ref cache-vector
838                                                    (+ from-loc i)))
839                            (setf (cache-vector-ref cache-vector
840                                                    (+ from-loc i))
841                                  nil))))))
842       (values (car lines) t))))
843
844 (defun default-limit-fn (nlines)
845   (case nlines
846     ((1 2 4) 1)
847     ((8 16)  4)
848     (otherwise 6)))