f2a05dff623949eb1912456dd6e4079bfa485117
[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 (deftype field-type ()
141   '(mod #.layout-clos-hash-length))
142
143 (eval-when (:compile-toplevel :load-toplevel :execute)
144   (declaim (ftype (function (fixnum) (values (and unsigned-byte fixnum) &optional))
145                   power-of-two-ceiling))
146   (defun power-of-two-ceiling (x)
147     ;; (expt 2 (ceiling (log x 2)))
148     (ash 1 (integer-length (1- x)))))
149
150 ;;; FIXME: We should probably keep just one of these -- or at least use just
151 ;;; one.
152 (declaim (inline compute-line-size))
153 (defun compute-line-size (x)
154   (power-of-two-ceiling x))
155
156 (defconstant +nkeys-limit+ 256)
157
158 (defstruct (cache (:constructor make-cache ())
159                   (:copier copy-cache-internal))
160   (owner nil)
161   (nkeys 1 :type (integer 1 #.+nkeys-limit+))
162   (valuep nil :type (member nil t))
163   (nlines 0 :type fixnum)
164   (field 0 :type field-type)
165   (limit-fn #'default-limit-fn :type function)
166   (mask 0 :type fixnum)
167   (size 0 :type fixnum)
168   (line-size 1 :type (integer 1 #.(power-of-two-ceiling (1+ +nkeys-limit+))))
169   (max-location 0 :type fixnum)
170   (vector #() :type simple-vector)
171   (overflow nil :type list))
172
173 #-sb-fluid (declaim (sb-ext:freeze-type cache))
174 \f
175 ;;;; wrapper cache numbers
176
177 ;;; The constant WRAPPER-CACHE-NUMBER-ADDS-OK controls the number of
178 ;;; non-zero bits wrapper cache numbers will have.
179 ;;;
180 ;;; The value of this constant is the number of wrapper cache numbers
181 ;;; which can be added and still be certain the result will be a
182 ;;; fixnum. This is used by all the code that computes primary cache
183 ;;; locations from multiple wrappers.
184 ;;;
185 ;;; The value of this constant is used to derive the next two which
186 ;;; are the forms of this constant which it is more convenient for the
187 ;;; runtime code to use.
188 (defconstant wrapper-cache-number-length
189   (integer-length layout-clos-hash-max))
190 (defconstant wrapper-cache-number-mask layout-clos-hash-max)
191 (defconstant wrapper-cache-number-adds-ok
192   (truncate most-positive-fixnum layout-clos-hash-max))
193 \f
194 ;;;; wrappers themselves
195
196 ;;; This caching algorithm requires that wrappers have more than one
197 ;;; wrapper cache number. You should think of these multiple numbers
198 ;;; as being in columns. That is, for a given cache, the same column
199 ;;; of wrapper cache numbers will be used.
200 ;;;
201 ;;; If at some point the cache distribution of a cache gets bad, the
202 ;;; cache can be rehashed by switching to a different column.
203 ;;;
204 ;;; The columns are referred to by field number which is that number
205 ;;; which, when used as a second argument to wrapper-ref, will return
206 ;;; that column of wrapper cache number.
207 ;;;
208 ;;; This code is written to allow flexibility as to how many wrapper
209 ;;; cache numbers will be in each wrapper, and where they will be
210 ;;; located. It is also set up to allow port specific modifications to
211 ;;; `pack' the wrapper cache numbers on machines where the addressing
212 ;;; modes make that a good idea.
213
214 ;;; In SBCL, as in CMU CL, we want to do type checking as early as
215 ;;; possible; structures help this. The structures are hard-wired to
216 ;;; have a fixed number of cache hash values, and that number must
217 ;;; correspond to the number of cache lines we use.
218 (defconstant wrapper-cache-number-vector-length
219   layout-clos-hash-length)
220
221 (unless (boundp '*the-class-t*)
222   (setq *the-class-t* nil))
223
224 (defconstant +first-wrapper-cache-number-index+ 0)
225
226 (declaim (inline next-wrapper-cache-number-index))
227 (defun next-wrapper-cache-number-index (field-number)
228   (and (< field-number #.(1- wrapper-cache-number-vector-length))
229        (1+ field-number)))
230 \f
231
232 (defun get-cache (nkeys valuep limit-fn nlines)
233   (let ((cache (make-cache)))
234     (declare (type cache cache))
235     (multiple-value-bind (cache-mask actual-size line-size nlines)
236         (compute-cache-parameters nkeys valuep nlines)
237       (setf (cache-nkeys cache) nkeys
238             (cache-valuep cache) valuep
239             (cache-nlines cache) nlines
240             (cache-field cache) +first-wrapper-cache-number-index+
241             (cache-limit-fn cache) limit-fn
242             (cache-mask cache) cache-mask
243             (cache-size cache) actual-size
244             (cache-line-size cache) line-size
245             (cache-max-location cache) (let ((line (1- nlines)))
246                                          (if (= nkeys 1)
247                                              (* line line-size)
248                                              (1+ (* line line-size))))
249             (cache-vector cache) (get-cache-vector actual-size)
250             (cache-overflow cache) nil)
251       cache)))
252
253 (defun get-cache-from-cache (old-cache new-nlines
254                              &optional (new-field +first-wrapper-cache-number-index+))
255   (let ((nkeys (cache-nkeys old-cache))
256         (valuep (cache-valuep old-cache))
257         (cache (make-cache)))
258     (declare (type cache cache))
259     (multiple-value-bind (cache-mask actual-size line-size nlines)
260         (if (= new-nlines (cache-nlines old-cache))
261             (values (cache-mask old-cache) (cache-size old-cache)
262                     (cache-line-size old-cache) (cache-nlines old-cache))
263             (compute-cache-parameters nkeys valuep new-nlines))
264       (setf (cache-owner cache) (cache-owner old-cache)
265             (cache-nkeys cache) nkeys
266             (cache-valuep cache) valuep
267             (cache-nlines cache) nlines
268             (cache-field cache) new-field
269             (cache-limit-fn cache) (cache-limit-fn old-cache)
270             (cache-mask cache) cache-mask
271             (cache-size cache) actual-size
272             (cache-line-size cache) line-size
273             (cache-max-location cache) (let ((line (1- nlines)))
274                                          (if (= nkeys 1)
275                                              (* line line-size)
276                                              (1+ (* line line-size))))
277             (cache-vector cache) (get-cache-vector actual-size)
278             (cache-overflow cache) nil)
279       cache)))
280
281 (defun copy-cache (old-cache)
282   (let* ((new-cache (copy-cache-internal old-cache))
283          (size (cache-size old-cache))
284          (old-vector (cache-vector old-cache))
285          (new-vector (get-cache-vector size)))
286     (declare (simple-vector old-vector new-vector))
287     (dotimes-fixnum (i size)
288       (setf (svref new-vector i) (svref old-vector i)))
289     (setf (cache-vector new-cache) new-vector)
290     new-cache))
291
292 (defun compute-cache-parameters (nkeys valuep nlines-or-cache-vector)
293   ;;(declare (values cache-mask actual-size line-size nlines))
294   (declare (fixnum nkeys))
295   (if (= nkeys 1)
296       (let* ((line-size (if valuep 2 1))
297              (cache-size (etypecase nlines-or-cache-vector
298                            (fixnum
299                             (* line-size
300                                (power-of-two-ceiling nlines-or-cache-vector)))
301                            (vector
302                             (cache-vector-size nlines-or-cache-vector)))))
303         (declare (type (and unsigned-byte fixnum) line-size cache-size))
304         (values (logxor (1- cache-size) (1- line-size))
305                 cache-size
306                 line-size
307                 (floor cache-size line-size)))
308       (let* ((line-size (power-of-two-ceiling (if valuep (1+ nkeys) nkeys)))
309              (cache-size (etypecase nlines-or-cache-vector
310                            (fixnum
311                             (* line-size
312                                 (power-of-two-ceiling nlines-or-cache-vector)))
313                            (vector
314                              (1- (cache-vector-size nlines-or-cache-vector))))))
315         (declare (fixnum line-size cache-size))
316         (values (logxor (1- cache-size) (1- line-size))
317                 (1+ cache-size)
318                 line-size
319                 (floor cache-size line-size)))))
320 \f
321 ;;; the various implementations of computing a primary cache location from
322 ;;; wrappers. Because some implementations of this must run fast there are
323 ;;; several implementations of the same algorithm.
324 ;;;
325 ;;; The algorithm is:
326 ;;;
327 ;;;  SUM       over the wrapper cache numbers,
328 ;;;  ENSURING  that the result is a fixnum
329 ;;;  MASK      the result against the mask argument.
330
331 ;;; The basic functional version. This is used by the cache miss code to
332 ;;; compute the primary location of an entry.
333 (defun compute-primary-cache-location (field mask wrappers)
334   (declare (type field-type field) (fixnum mask))
335   (if (not (listp wrappers))
336       (logand mask (layout-clos-hash wrappers field))
337       (let ((location 0)
338             (i 0))
339         (declare (fixnum location i))
340         (dolist (wrapper wrappers)
341           ;; First add the cache number of this wrapper to location.
342           (let ((wrapper-cache-number (layout-clos-hash wrapper field)))
343             (declare (fixnum wrapper-cache-number))
344             (if (zerop wrapper-cache-number)
345                 (return-from compute-primary-cache-location 0)
346                 (incf location wrapper-cache-number)))
347           ;; Then, if we are working with lots of wrappers, deal with
348           ;; the wrapper-cache-number-mask stuff.
349           (when (and (not (zerop i))
350                      (zerop (mod i wrapper-cache-number-adds-ok)))
351             (setq location
352                   (logand location wrapper-cache-number-mask)))
353           (incf i))
354         (1+ (logand mask location)))))
355
356 ;;; This version is called on a cache line. It fetches the wrappers
357 ;;; from the cache line and determines the primary location. Various
358 ;;; parts of the cache filling code call this to determine whether it
359 ;;; is appropriate to displace a given cache entry.
360 ;;;
361 ;;; If this comes across a wrapper whose CACHE-NO is 0, it returns the
362 ;;; symbol invalid to suggest to its caller that it would be provident
363 ;;; to blow away the cache line in question.
364 (defun compute-primary-cache-location-from-location (to-cache
365                                                      from-location
366                                                      &optional
367                                                      (from-cache to-cache))
368   (declare (type cache to-cache from-cache) (fixnum from-location))
369   (let ((result 0)
370         (cache-vector (cache-vector from-cache))
371         (field (cache-field to-cache))
372         (mask (cache-mask to-cache))
373         (nkeys (cache-nkeys to-cache)))
374     (declare (type field-type field) (fixnum result mask nkeys)
375              (simple-vector cache-vector))
376     (dotimes-fixnum (i nkeys)
377       ;; FIXME: Sometimes we get NIL here as wrapper, apparently because
378       ;; another thread has stomped on the cache-vector.
379       (let* ((wrapper (cache-vector-ref cache-vector (+ i from-location)))
380              (wcn (layout-clos-hash wrapper field)))
381         (declare (fixnum wcn))
382         (incf result wcn))
383       (when (and (not (zerop i))
384                  (zerop (mod i wrapper-cache-number-adds-ok)))
385         (setq result (logand result wrapper-cache-number-mask))))
386     (if (= nkeys 1)
387         (logand mask result)
388         (1+ (logand mask result)))))
389 \f
390 (defmacro with-local-cache-functions ((cache) &body body)
391   `(let ((.cache. ,cache))
392      (declare (type cache .cache.))
393      (labels ((cache () .cache.)
394               (nkeys () (cache-nkeys .cache.))
395               (line-size () (cache-line-size .cache.))
396               (c-vector () (cache-vector .cache.))
397               (valuep () (cache-valuep .cache.))
398               (nlines () (cache-nlines .cache.))
399               (max-location () (cache-max-location .cache.))
400               (limit-fn () (cache-limit-fn .cache.))
401               (size () (cache-size .cache.))
402               (mask () (cache-mask .cache.))
403               (field () (cache-field .cache.))
404               (overflow () (cache-overflow .cache.))
405               ;;
406               ;; Return T IFF this cache location is reserved.  The
407               ;; only time this is true is for line number 0 of an
408               ;; nkeys=1 cache.
409               ;;
410               (line-reserved-p (line)
411                 (declare (fixnum line))
412                 (and (= (nkeys) 1)
413                      (= line 0)))
414               ;;
415               (location-reserved-p (location)
416                 (declare (fixnum location))
417                 (and (= (nkeys) 1)
418                      (= location 0)))
419               ;;
420               ;; Given a line number, return the cache location.
421               ;; This is the value that is the second argument to
422               ;; cache-vector-ref.  Basically, this deals with the
423               ;; offset of nkeys>1 caches and multiplies by line
424               ;; size.
425               ;;
426               (line-location (line)
427                 (declare (fixnum line))
428                 (when (line-reserved-p line)
429                   (error "line is reserved"))
430                 (if (= (nkeys) 1)
431                     (the fixnum (* line (line-size)))
432                     (the fixnum (1+ (the fixnum (* line (line-size)))))))
433               ;;
434               ;; Given a cache location, return the line.  This is
435               ;; the inverse of LINE-LOCATION.
436               ;;
437               (location-line (location)
438                 (declare (fixnum location))
439                 (if (= (nkeys) 1)
440                     (floor location (line-size))
441                     (floor (the fixnum (1- location)) (line-size))))
442               ;;
443               ;; Given a line number, return the wrappers stored at
444               ;; that line.  As usual, if nkeys=1, this returns a
445               ;; single value.  Only when nkeys>1 does it return a
446               ;; list.  An error is signalled if the line is
447               ;; reserved.
448               ;;
449               (line-wrappers (line)
450                 (declare (fixnum line))
451                 (when (line-reserved-p line) (error "Line is reserved."))
452                 (location-wrappers (line-location line)))
453               ;;
454               (location-wrappers (location) ; avoid multiplies caused by line-location
455                 (declare (fixnum location))
456                 (if (= (nkeys) 1)
457                     (cache-vector-ref (c-vector) location)
458                     (let ((list (make-list (nkeys)))
459                           (vector (c-vector)))
460                       (declare (simple-vector vector))
461                       (dotimes (i (nkeys) list)
462                         (declare (fixnum i))
463                         (setf (nth i list)
464                               (cache-vector-ref vector (+ location i)))))))
465               ;;
466               ;; Given a line number, return true IFF the line's
467               ;; wrappers are the same as wrappers.
468               ;;
469               (line-matches-wrappers-p (line wrappers)
470                 (declare (fixnum line))
471                 (and (not (line-reserved-p line))
472                      (location-matches-wrappers-p (line-location line)
473                                                   wrappers)))
474               ;;
475               (location-matches-wrappers-p (loc wrappers) ; must not be reserved
476                 (declare (fixnum loc))
477                 (let ((cache-vector (c-vector)))
478                   (declare (simple-vector cache-vector))
479                   (if (= (nkeys) 1)
480                       (eq wrappers (cache-vector-ref cache-vector loc))
481                       (dotimes (i (nkeys) t)
482                         (declare (fixnum i))
483                         (unless (eq (pop wrappers)
484                                     (cache-vector-ref cache-vector (+ loc i)))
485                           (return nil))))))
486               ;;
487               ;; Given a line number, return the value stored at that line.
488               ;; If valuep is NIL, this returns NIL.  As with line-wrappers,
489               ;; an error is signalled if the line is reserved.
490               ;;
491               (line-value (line)
492                 (declare (fixnum line))
493                 (when (line-reserved-p line) (error "Line is reserved."))
494                 (location-value (line-location line)))
495               ;;
496               (location-value (loc)
497                 (declare (fixnum loc))
498                 (and (valuep)
499                      (cache-vector-ref (c-vector) (+ loc (nkeys)))))
500               ;;
501               ;; Given a line number, return true IFF that line has data in
502               ;; it.  The state of the wrappers stored in the line is not
503               ;; checked.  An error is signalled if line is reserved.
504               (line-full-p (line)
505                 (when (line-reserved-p line) (error "Line is reserved."))
506                 (not (null (cache-vector-ref (c-vector) (line-location line)))))
507               ;;
508               ;; Given a line number, return true IFF the line is full and
509               ;; there are no invalid wrappers in the line, and the line's
510               ;; wrappers are different from wrappers.
511               ;; An error is signalled if the line is reserved.
512               ;;
513               (line-valid-p (line wrappers)
514                 (declare (fixnum line))
515                 (when (line-reserved-p line) (error "Line is reserved."))
516                 (location-valid-p (line-location line) wrappers))
517               ;;
518               (location-valid-p (loc wrappers)
519                 (declare (fixnum loc))
520                 (let ((cache-vector (c-vector))
521                       (wrappers-mismatch-p (null wrappers)))
522                   (declare (simple-vector cache-vector))
523                   (dotimes (i (nkeys) wrappers-mismatch-p)
524                     (declare (fixnum i))
525                     (let ((wrapper (cache-vector-ref cache-vector (+ loc i))))
526                       (when (or (null wrapper)
527                                 (invalid-wrapper-p wrapper))
528                         (return nil))
529                       (unless (and wrappers
530                                    (eq wrapper
531                                        (if (consp wrappers)
532                                            (pop wrappers)
533                                            wrappers)))
534                         (setq wrappers-mismatch-p t))))))
535               ;;
536               ;; How many unreserved lines separate line-1 and line-2.
537               ;;
538               (line-separation (line-1 line-2)
539                 (declare (fixnum line-1 line-2))
540                 (let ((diff (the fixnum (- line-2 line-1))))
541                   (declare (fixnum diff))
542                   (when (minusp diff)
543                     (setq diff (+ diff (nlines)))
544                     (when (line-reserved-p 0)
545                       (setq diff (1- diff))))
546                   diff))
547               ;;
548               ;; Given a cache line, get the next cache line.  This will not
549               ;; return a reserved line.
550               ;;
551               (next-line (line)
552                 (declare (fixnum line))
553                 (if (= line (the fixnum (1- (nlines))))
554                     (if (line-reserved-p 0) 1 0)
555                     (the fixnum (1+ line))))
556               ;;
557               (next-location (loc)
558                 (declare (fixnum loc))
559                 (if (= loc (max-location))
560                     (if (= (nkeys) 1)
561                         (line-size)
562                         1)
563                     (the fixnum (+ loc (line-size)))))
564               ;;
565               ;; Given a line which has a valid entry in it, this
566               ;; will return the primary cache line of the wrappers
567               ;; in that line.  We just call
568               ;; COMPUTE-PRIMARY-CACHE-LOCATION-FROM-LOCATION, this
569               ;; is an easier packaging up of the call to it.
570               ;;
571               (line-primary (line)
572                 (declare (fixnum line))
573                 (location-line (line-primary-location line)))
574               ;;
575               (line-primary-location (line)
576                 (declare (fixnum line))
577                 (compute-primary-cache-location-from-location
578                  (cache) (line-location line))))
579        (declare (ignorable #'cache #'nkeys #'line-size #'c-vector #'valuep
580                            #'nlines #'max-location #'limit-fn #'size
581                            #'mask #'field #'overflow #'line-reserved-p
582                            #'location-reserved-p #'line-location
583                            #'location-line #'line-wrappers #'location-wrappers
584                            #'line-matches-wrappers-p
585                            #'location-matches-wrappers-p
586                            #'line-value #'location-value #'line-full-p
587                            #'line-valid-p #'location-valid-p
588                            #'line-separation #'next-line #'next-location
589                            #'line-primary #'line-primary-location))
590        ,@body)))
591 \f
592 ;;; Here is where we actually fill, recache and expand caches.
593 ;;;
594 ;;; The functions FILL-CACHE and PROBE-CACHE are the ONLY external
595 ;;; entrypoints into this code.
596 ;;;
597 ;;; FILL-CACHE returns 1 value: a new cache
598 ;;;
599 ;;;   a wrapper field number
600 ;;;   a cache
601 ;;;   a mask
602 ;;;   an absolute cache size (the size of the actual vector)
603 ;;; It tries to re-adjust the cache every time it makes a new fill.
604 ;;; The intuition here is that we want uniformity in the number of
605 ;;; probes needed to find an entry. Furthermore, adjusting has the
606 ;;; nice property of throwing out any entries that are invalid.
607 (defvar *cache-expand-threshold* 1.25)
608
609 (defun fill-cache (cache wrappers value)
610   ;; FILL-CACHE won't return if WRAPPERS is nil, might as well check..
611   (aver wrappers)
612   (or (fill-cache-p nil cache wrappers value)
613       (and (< (ceiling (* (cache-count cache) *cache-expand-threshold*))
614               (if (= (cache-nkeys cache) 1)
615                   (1- (cache-nlines cache))
616                   (cache-nlines cache)))
617            (adjust-cache cache wrappers value))
618       (expand-cache cache wrappers value)))
619
620 (defvar *check-cache-p* nil)
621
622 (defmacro maybe-check-cache (cache)
623   `(progn
624      (when *check-cache-p*
625        (check-cache ,cache))
626      ,cache))
627
628 (defun check-cache (cache)
629   (with-local-cache-functions (cache)
630     (let ((location (if (= (nkeys) 1) 0 1))
631           (limit (funcall (limit-fn) (nlines))))
632       (dotimes-fixnum (i (nlines) cache)
633         (when (and (not (location-reserved-p location))
634                    (line-full-p i))
635           (let* ((home-loc (compute-primary-cache-location-from-location
636                             cache location))
637                  (home (location-line (if (location-reserved-p home-loc)
638                                           (next-location home-loc)
639                                           home-loc)))
640                  (sep (when home (line-separation home i))))
641             (when (and sep (> sep limit))
642               (error "bad cache ~S ~@
643                       value at location ~W: ~W lines from its home. The limit is ~W."
644                      cache location sep limit))))
645         (setq location (next-location location))))))
646
647 (defun probe-cache (cache wrappers &optional default limit-fn)
648   (aver wrappers)
649   (with-local-cache-functions (cache)
650     (let* ((location (compute-primary-cache-location (field) (mask) wrappers))
651            (limit (funcall (or limit-fn (limit-fn)) (nlines))))
652       (declare (fixnum location limit))
653       (when (location-reserved-p location)
654         (setq location (next-location location)))
655       (dotimes-fixnum (i (1+ limit))
656         (when (location-matches-wrappers-p location wrappers)
657           (return-from probe-cache (or (not (valuep))
658                                        (location-value location))))
659         (setq location (next-location location)))
660       (dolist (entry (overflow))
661         (when (equal (car entry) wrappers)
662           (return-from probe-cache (or (not (valuep))
663                                        (cdr entry)))))
664       default)))
665
666 (defun map-cache (function cache &optional set-p)
667   (with-local-cache-functions (cache)
668     (let ((set-p (and set-p (valuep))))
669       (dotimes-fixnum (i (nlines) cache)
670         (unless (or (line-reserved-p i) (not (line-valid-p i nil)))
671           (let ((value (funcall function (line-wrappers i) (line-value i))))
672             (when set-p
673               ;; FIXME: Cache modification: should we not be holding a lock?
674               (setf (cache-vector-ref (c-vector) (+ (line-location i) (nkeys)))
675                     value)))))
676       (dolist (entry (overflow))
677         (let ((value (funcall function (car entry) (cdr entry))))
678           (when set-p
679             (setf (cdr entry) value))))))
680   cache)
681
682 (defun cache-count (cache)
683   (with-local-cache-functions (cache)
684     (let ((count 0))
685       (declare (fixnum count))
686       (dotimes-fixnum (i (nlines) count)
687         (unless (line-reserved-p i)
688           (when (line-full-p i)
689             (incf count)))))))
690
691 (defun entry-in-cache-p (cache wrappers value)
692   (declare (ignore value))
693   (with-local-cache-functions (cache)
694     (dotimes-fixnum (i (nlines))
695       (unless (line-reserved-p i)
696         (when (equal (line-wrappers i) wrappers)
697           (return t))))))
698
699 ;;; returns T or NIL
700 ;;;
701 ;;; FIXME: Deceptive name as this has side-effects.
702 (defun fill-cache-p (forcep cache wrappers value)
703   (with-local-cache-functions (cache)
704     (let* ((location (compute-primary-cache-location (field) (mask) wrappers))
705            (primary (location-line location)))
706       (declare (fixnum location primary))
707       ;; FIXME: I tried (aver (> location 0)) and (aver (not
708       ;; (location-reserved-p location))) here, on the basis that
709       ;; particularly passing a LOCATION of 0 for a cache with more
710       ;; than one key would cause PRIMARY to be -1.  However, the
711       ;; AVERs triggered during the bootstrap, and removing them
712       ;; didn't cause anything to break, so I've left them removed.
713       ;; I'm still confused as to what is right.  -- CSR, 2006-04-20
714       (multiple-value-bind (free emptyp)
715           (find-free-cache-line primary cache wrappers)
716         (when (or forcep emptyp)
717           (when (not emptyp)
718             (push (cons (line-wrappers free) (line-value free))
719                   (cache-overflow cache)))
720           ;; (fill-line free wrappers value)
721           (let ((line free))
722             (declare (fixnum line))
723             (when (line-reserved-p line)
724               (error "attempt to fill a reserved line"))
725             (let ((loc (line-location line))
726                   (cache-vector (c-vector)))
727               (declare (fixnum loc) (simple-vector cache-vector))
728               ;; FIXME: Cache modifications: should we not be holding
729               ;; a lock?
730               (cond ((= (nkeys) 1)
731                      (setf (cache-vector-ref cache-vector loc) wrappers)
732                      (when (valuep)
733                        (setf (cache-vector-ref cache-vector (1+ loc)) value)))
734                     (t
735                      (let ((i 0))
736                        (declare (fixnum i))
737                        (dolist (w wrappers)
738                          (setf (cache-vector-ref cache-vector (+ loc i)) w)
739                          (setq i (the fixnum (1+ i)))))
740                      (when (valuep)
741                        (setf (cache-vector-ref cache-vector (+ loc (nkeys)))
742                              value))))
743               (maybe-check-cache cache))))))))
744
745 ;;; FIXME: Deceptive name as this has side-effects
746 (defun fill-cache-from-cache-p (forcep cache from-cache from-line)
747   (declare (fixnum from-line))
748   (with-local-cache-functions (cache)
749     (let ((primary (location-line
750                     (compute-primary-cache-location-from-location
751                      cache (line-location from-line) from-cache))))
752       (declare (fixnum primary))
753       (multiple-value-bind (free emptyp)
754           (find-free-cache-line primary cache)
755         (when (or forcep emptyp)
756           (when (not emptyp)
757             (push (cons (line-wrappers free) (line-value free))
758                   (cache-overflow cache)))
759           ;;(transfer-line from-cache-vector from-line cache-vector free)
760           (let ((from-cache-vector (cache-vector from-cache))
761                 (to-cache-vector (c-vector))
762                 (to-line free))
763             (declare (fixnum to-line))
764             (if (line-reserved-p to-line)
765                 (error "transferring something into a reserved cache line")
766                 (let ((from-loc (line-location from-line))
767                       (to-loc (line-location to-line)))
768                   (declare (fixnum from-loc to-loc))
769                   (modify-cache to-cache-vector
770                                 (dotimes-fixnum (i (line-size))
771                                   (setf (cache-vector-ref to-cache-vector
772                                                           (+ to-loc i))
773                                         (cache-vector-ref from-cache-vector
774                                                           (+ from-loc i)))))))
775             (maybe-check-cache cache)))))))
776
777 ;;; Returns NIL or (values <field> <cache-vector>)
778 ;;;
779 ;;; This is only called when it isn't possible to put the entry in the
780 ;;; cache the easy way. That is, this function assumes that
781 ;;; FILL-CACHE-P has been called as returned NIL.
782 ;;;
783 ;;; If this returns NIL, it means that it wasn't possible to find a
784 ;;; wrapper field for which all of the entries could be put in the
785 ;;; cache (within the limit).
786 (defun adjust-cache (cache wrappers value)
787   (with-local-cache-functions (cache)
788     (let ((ncache (get-cache-from-cache cache (nlines) (field))))
789       (do ((nfield (cache-field ncache)
790                    (next-wrapper-cache-number-index nfield)))
791           ((null nfield) nil)
792         (setf (cache-field ncache) nfield)
793         (labels ((try-one-fill-from-line (line)
794                    (fill-cache-from-cache-p nil ncache cache line))
795                  (try-one-fill (wrappers value)
796                    (fill-cache-p nil ncache wrappers value)))
797           (if (and (dotimes-fixnum (i (nlines) t)
798                      (when (and (null (line-reserved-p i))
799                                 (line-valid-p i wrappers))
800                        (unless (try-one-fill-from-line i) (return nil))))
801                    (dolist (wrappers+value (cache-overflow cache) t)
802                      (unless (try-one-fill (car wrappers+value) (cdr wrappers+value))
803                        (return nil)))
804                    (try-one-fill wrappers value))
805               (return (maybe-check-cache ncache))
806               (flush-cache-vector-internal (cache-vector ncache))))))))
807
808 ;;; returns: (values <cache>)
809 (defun expand-cache (cache wrappers value)
810   ;;(declare (values cache))
811   (with-local-cache-functions (cache)
812     (let ((ncache (get-cache-from-cache cache (* (nlines) 2))))
813       (labels ((do-one-fill-from-line (line)
814                  (unless (fill-cache-from-cache-p nil ncache cache line)
815                    (do-one-fill (line-wrappers line) (line-value line))))
816                (do-one-fill (wrappers value)
817                  (setq ncache (or (adjust-cache ncache wrappers value)
818                                   (fill-cache-p t ncache wrappers value))))
819                (try-one-fill (wrappers value)
820                  (fill-cache-p nil ncache wrappers value)))
821         (dotimes-fixnum (i (nlines))
822           (when (and (null (line-reserved-p i))
823                      (line-valid-p i wrappers))
824             (do-one-fill-from-line i)))
825         (dolist (wrappers+value (cache-overflow cache))
826           (unless (try-one-fill (car wrappers+value) (cdr wrappers+value))
827             (do-one-fill (car wrappers+value) (cdr wrappers+value))))
828         (unless (try-one-fill wrappers value)
829           (do-one-fill wrappers value))
830         (maybe-check-cache ncache)))))
831 \f
832 (defvar *pcl-misc-random-state* (make-random-state))
833
834 ;;; This is the heart of the cache filling mechanism. It implements
835 ;;; the decisions about where entries are placed.
836 ;;;
837 ;;; Find a line in the cache at which a new entry can be inserted.
838 ;;;
839 ;;;   <line>
840 ;;;   <empty?>     is <line> in fact empty?
841 (defun find-free-cache-line (primary cache &optional wrappers)
842   ;;(declare (values line empty?))
843   (declare (fixnum primary))
844   (with-local-cache-functions (cache)
845     (when (line-reserved-p primary) (setq primary (next-line primary)))
846     (let ((limit (funcall (limit-fn) (nlines)))
847           (wrappedp nil)
848           (lines nil)
849           (p primary) (s primary))
850       (declare (fixnum p s limit))
851       (block find-free
852         (loop
853          ;; Try to find a free line starting at <s>. <p> is the
854          ;; primary line of the entry we are finding a free
855          ;; line for, it is used to compute the separations.
856          (do* ((line s (next-line line))
857                (nsep (line-separation p s) (1+ nsep)))
858               (())
859            (declare (fixnum line nsep))
860            (when (null (line-valid-p line wrappers)) ;If this line is empty or
861              (push line lines)          ;invalid, just use it.
862              (return-from find-free))
863            (when (and wrappedp (>= line primary))
864              ;; have gone all the way around the cache, time to quit
865              (return-from find-free-cache-line (values primary nil)))
866            (let ((osep (line-separation (line-primary line) line)))
867              (when (>= osep limit)
868                (return-from find-free-cache-line (values primary nil)))
869              (when (cond ((= nsep limit) t)
870                          ((= nsep osep)
871                           (zerop (random 2 *pcl-misc-random-state*)))
872                          ((> nsep osep) t)
873                          (t nil))
874                ;; See whether we can displace what is in this line so that we
875                ;; can use the line.
876                (when (= line (the fixnum (1- (nlines)))) (setq wrappedp t))
877                (setq p (line-primary line))
878                (setq s (next-line line))
879                (push line lines)
880                (return nil)))
881            (when (= line (the fixnum (1- (nlines)))) (setq wrappedp t)))))
882       ;; Do all the displacing.
883       (loop
884        (when (null (cdr lines)) (return nil))
885        (let ((dline (pop lines))
886              (line (car lines)))
887          (declare (fixnum dline line))
888          ;;Copy from line to dline (dline is known to be free).
889          (let ((from-loc (line-location line))
890                (to-loc (line-location dline))
891                (cache-vector (c-vector)))
892            (declare (fixnum from-loc to-loc) (simple-vector cache-vector))
893            (modify-cache cache-vector
894                          (dotimes-fixnum (i (line-size))
895                            (setf (cache-vector-ref cache-vector
896                                                    (+ to-loc i))
897                                  (cache-vector-ref cache-vector
898                                                    (+ from-loc i)))
899                            (setf (cache-vector-ref cache-vector
900                                                    (+ from-loc i))
901                                  nil))))))
902       (values (car lines) t))))
903
904 (defun default-limit-fn (nlines)
905   (case nlines
906     ((1 2 4) 1)
907     ((8 16)  4)
908     (otherwise 6)))