1.0.19.33: Improved interrupt handling on darwin/x86[-64]
[sbcl/eslaughter.git] / src / pcl / cache.lisp
blob73c197bda28c097824ad77ab3572bc10f0a969dd
1 ;;;; the basics of the PCL wrapper cache mechanism
3 ;;;; This software is part of the SBCL system. See the README file for
4 ;;;; more information.
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.
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.
26 ;;;; Note: as of SBCL 1.0.6.3 it is questionable if cache.lisp can
27 ;;;; anymore be considered to be "derived from software originally
28 ;;;; released by Xerox Corporation", as at that time the whole cache
29 ;;;; implementation was essentially redone from scratch.
31 (in-package "SB-PCL")
33 ;;;; Public API:
34 ;;;;
35 ;;;; fill-cache
36 ;;;; probe-cache
37 ;;;; make-cache
38 ;;;; map-cache
39 ;;;; emit-cache-lookup
40 ;;;; copy-cache
41 ;;;; hash-table-to-cache
42 ;;;;
43 ;;;; This is a thread and interrupt safe reimplementation loosely
44 ;;;; based on the original PCL cache by Kickzales and Rodrigues,
45 ;;;; as described in "Efficient Method Dispatch in PCL".
46 ;;;;
47 ;;;; * Writes to cache are made atomic using compare-and-swap on
48 ;;;; wrappers. Wrappers are never moved or deleted after they have
49 ;;;; been written: to clean them out the cache need to be copied.
50 ;;;;
51 ;;;; * Copying or expanding the cache drops out incomplete and invalid
52 ;;;; lines.
53 ;;;;
54 ;;;; * Since the cache is used for memoization only we don't need to
55 ;;;; worry about which of simultaneous replacements (when expanding
56 ;;;; the cache) takes place: the loosing one will have its work
57 ;;;; redone later. This also allows us to drop entries when the
58 ;;;; cache is about to grow insanely huge.
59 ;;;;
60 ;;;; The cache is essentially a specialized hash-table for layouts, used
61 ;;;; for memoization of effective methods, slot locations, and constant
62 ;;;; return values.
63 ;;;;
64 ;;;; Subsequences of the cache vector are called cache lines.
65 ;;;;
66 ;;;; The cache vector uses the symbol SB-PCL::..EMPTY.. as a sentinel
67 ;;;; value, to allow storing NILs in the vector as well.
69 (defstruct (cache (:constructor %make-cache)
70 (:copier %copy-cache))
71 ;; Number of keys the cache uses.
72 (key-count 1 :type (integer 1 (#.call-arguments-limit)))
73 ;; True if we store values in the cache.
74 (value)
75 ;; Number of vector elements a single cache line uses in the vector.
76 ;; This is always a power of two, so that the vector length can be both
77 ;; an exact multiple of this and a power of two.
78 (line-size 1 :type (integer 1 #.most-positive-fixnum))
79 ;; Cache vector, its length is always both a multiple of line-size
80 ;; and a power of two. This is so that we can calculate
81 ;; (mod index (length vector))
82 ;; using a bitmask.
83 (vector #() :type simple-vector)
84 ;; The bitmask used to calculate
85 ;; (mod (* line-size line-hash) (length vector))).
86 (mask 0 :type fixnum)
87 ;; Current probe-depth needed in the cache.
88 (depth 0 :type index)
89 ;; Maximum allowed probe-depth before the cache needs to expand.
90 (limit 0 :type index))
92 (defun compute-cache-mask (vector-length line-size)
93 ;; Since both vector-length and line-size are powers of two, we
94 ;; can compute a bitmask such that
96 ;; (logand <mask> <combined-layout-hash>)
98 ;; is "morally equal" to
100 ;; (mod (* <line-size> <combined-layout-hash>) <vector-length>)
102 ;; This is it: (1- vector-length) is #b111... of the approriate size
103 ;; to get the MOD, and (- line-size) gives right the number of zero
104 ;; bits at the low end.
105 (logand (1- vector-length) (- line-size)))
107 (defun cache-statistics (cache)
108 (let* ((vector (cache-vector cache))
109 (size (length vector))
110 (line-size (cache-line-size cache))
111 (total-lines (/ size line-size))
112 (free-lines (loop for i from 0 by line-size below size
113 unless (eq (svref vector i) '..empty..)
114 count t)))
115 (values (- total-lines free-lines) total-lines
116 (cache-depth cache) (cache-limit cache))))
118 ;;; Don't allocate insanely huge caches: this is 4096 lines for a
119 ;;; value cache with 8-15 keys -- probably "big enough for anyone",
120 ;;; and 16384 lines for a commonplace 2-key value cache.
121 (defconstant +cache-vector-max-length+ (expt 2 16))
123 ;;; Compute the maximum allowed probe depth as a function of cache size.
124 ;;; Cache size refers to number of cache lines, not the length of the
125 ;;; cache vector.
127 ;;; FIXME: It would be nice to take the generic function optimization
128 ;;; policy into account here (speed vs. space.)
129 (declaim (inline compute-limit))
130 (defun compute-limit (size)
131 (ceiling (sqrt (sqrt size))))
133 ;;; Returns VALUE if it is not ..EMPTY.., otherwise executes ELSE:
134 (defmacro non-empty-or (value else)
135 (with-unique-names (n-value)
136 `(let ((,n-value ,value))
137 (if (eq ,n-value '..empty..)
138 ,else
139 ,n-value))))
141 ;;; Fast way to check if a thing found at the position of a cache key is one:
142 ;;; it is always either a wrapper, or the ..EMPTY.. symbol.
143 (declaim (inline cache-key-p))
144 (defun cache-key-p (thing)
145 (not (symbolp thing)))
147 ;;; Atomically update the current probe depth of a cache.
148 (defun note-cache-depth (cache depth)
149 (loop for old = (cache-depth cache)
150 while (and (< old depth)
151 (not (eq old (compare-and-swap (cache-depth cache)
152 old depth))))))
154 ;;; Compute the starting index of the next cache line in the cache vector.
155 (declaim (inline next-cache-index))
156 (defun next-cache-index (mask index line-size)
157 (declare (type (unsigned-byte #.sb-vm:n-word-bits) index line-size mask))
158 (logand mask (+ index line-size)))
160 ;;; Returns the hash-value for layout, or executes ELSE if the layout
161 ;;; is invalid.
162 (defmacro hash-layout-or (layout else)
163 (with-unique-names (n-hash)
164 `(let ((,n-hash (layout-clos-hash ,layout)))
165 (if (zerop ,n-hash)
166 ,else
167 ,n-hash))))
169 ;;; Compute cache index for the cache and a list of layouts.
170 (declaim (inline compute-cache-index))
171 (defun compute-cache-index (cache layouts)
172 (let ((index (hash-layout-or (car layouts)
173 (return-from compute-cache-index nil))))
174 (declare (fixnum index))
175 (dolist (layout (cdr layouts))
176 (mixf index (hash-layout-or layout (return-from compute-cache-index nil))))
177 ;; align with cache lines
178 (logand index (cache-mask cache))))
180 ;;; Emit code that does lookup in cache bound to CACHE-VAR using
181 ;;; layouts bound to LAYOUT-VARS. Go to MISS-TAG on event of a miss or
182 ;;; invalid layout. Otherwise, if VALUE-VAR is non-nil, set it to the
183 ;;; value found. (VALUE-VAR is non-nil only when CACHE-VALUE is true.)
185 ;;; In other words, produces inlined code for COMPUTE-CACHE-INDEX when
186 ;;; number of keys and presence of values in the cache is known
187 ;;; beforehand.
188 (defun emit-cache-lookup (cache-var layout-vars miss-tag value-var)
189 (let ((line-size (power-of-two-ceiling (+ (length layout-vars)
190 (if value-var 1 0)))))
191 (with-unique-names (n-index n-vector n-depth n-pointer n-mask
192 MATCH-WRAPPERS EXIT-WITH-HIT)
193 `(let* ((,n-index (hash-layout-or ,(car layout-vars) (go ,miss-tag)))
194 (,n-vector (cache-vector ,cache-var))
195 (,n-mask (cache-mask ,cache-var)))
196 (declare (index ,n-index))
197 ,@(mapcar (lambda (layout-var)
198 `(mixf ,n-index (hash-layout-or ,layout-var (go ,miss-tag))))
199 (cdr layout-vars))
200 ;; align with cache lines
201 (setf ,n-index (logand ,n-index ,n-mask))
202 (let ((,n-depth (cache-depth ,cache-var))
203 (,n-pointer ,n-index))
204 (declare (index ,n-depth ,n-pointer))
205 (tagbody
206 ,MATCH-WRAPPERS
207 (when (and ,@(mapcar
208 (lambda (layout-var)
209 `(prog1
210 (eq ,layout-var (svref ,n-vector ,n-pointer))
211 (incf ,n-pointer)))
212 layout-vars))
213 ,@(when value-var
214 `((setf ,value-var (non-empty-or (svref ,n-vector ,n-pointer)
215 (go ,miss-tag)))))
216 (go ,EXIT-WITH-HIT))
217 (if (zerop ,n-depth)
218 (go ,miss-tag)
219 (decf ,n-depth))
220 (setf ,n-index (next-cache-index ,n-mask ,n-index ,line-size)
221 ,n-pointer ,n-index)
222 (go ,MATCH-WRAPPERS)
223 ,EXIT-WITH-HIT))))))
225 ;;; Probes CACHE for LAYOUTS.
227 ;;; Returns two values: a boolean indicating a hit or a miss, and a secondary
228 ;;; value that is the value that was stored in the cache if any.
229 (defun probe-cache (cache layouts)
230 (declare (optimize speed))
231 (unless (consp layouts)
232 (setf layouts (list layouts)))
233 (let ((vector (cache-vector cache))
234 (key-count (cache-key-count cache))
235 (line-size (cache-line-size cache))
236 (mask (cache-mask cache)))
237 (flet ((probe-line (base)
238 (declare (optimize (sb-c::type-check 0)))
239 (tagbody
240 (loop for offset of-type index from 0 below key-count
241 for layout in layouts do
242 (unless (eq layout (svref vector (+ base offset)))
243 ;; missed
244 (go :miss)))
245 ;; all layouts match!
246 (let ((value (when (cache-value cache)
247 (non-empty-or (svref vector (+ base key-count))
248 (go :miss)))))
249 (return-from probe-cache (values t value)))
250 :miss
251 (return-from probe-line (next-cache-index mask base line-size)))))
252 (declare (ftype (function (index) (values index &optional)) probe-line))
253 (let ((index (compute-cache-index cache layouts)))
254 (when index
255 (loop repeat (1+ (cache-depth cache))
256 do (setf index (probe-line index)))))))
257 (values nil nil))
259 ;;; Tries to write LAYOUTS and VALUE at the cache line starting at
260 ;;; the index BASE. Returns true on success, and false on failure.
261 (defun try-update-cache-line (cache base layouts value)
262 (declare (index base))
263 (let ((vector (cache-vector cache))
264 (new (pop layouts)))
265 ;; If we unwind from here, we will be left with an incomplete
266 ;; cache line, but that is OK: next write using the same layouts
267 ;; will fill it, and reads will treat an incomplete line as a
268 ;; miss -- causing it to be filled.
269 (loop for old = (compare-and-swap (svref vector base) '..empty.. new) do
270 (when (and (cache-key-p old) (not (eq old new)))
271 ;; The place was already taken, and doesn't match our key.
272 (return-from try-update-cache-line nil))
273 (unless layouts
274 ;; All keys match or succesfully saved, save our value --
275 ;; just smash it in. Until the first time it is written
276 ;; there is ..EMPTY.. here, which probes look for, so we
277 ;; don't get bogus hits. This is necessary because we want
278 ;; to be able store arbitrary values here for use with
279 ;; constant-value dispatch functions.
280 (when (cache-value cache)
281 (setf (svref vector (1+ base)) value))
282 (return-from try-update-cache-line t))
283 (setf new (pop layouts))
284 (incf base))))
286 ;;; Tries to write LAYOUTS and VALUE somewhere in the cache. Returns
287 ;;; true on success and false on failure, meaning the cache is too
288 ;;; full.
289 (defun try-update-cache (cache layouts value)
290 (let ((index (or (compute-cache-index cache layouts)
291 ;; At least one of the layouts was invalid: just
292 ;; pretend we updated the cache, and let the next
293 ;; read pick up the mess.
294 (return-from try-update-cache t)))
295 (line-size (cache-line-size cache))
296 (mask (cache-mask cache)))
297 (declare (index index))
298 (loop for depth from 0 upto (cache-limit cache) do
299 (when (try-update-cache-line cache index layouts value)
300 (note-cache-depth cache depth)
301 (return-from try-update-cache t))
302 (setf index (next-cache-index mask index line-size)))))
304 ;;; Constructs a new cache.
305 (defun make-cache (&key (key-count (missing-arg)) (value (missing-arg))
306 (size 1))
307 (let* ((line-size (power-of-two-ceiling (+ key-count (if value 1 0))))
308 (adjusted-size (power-of-two-ceiling size))
309 (length (* adjusted-size line-size)))
310 (if (<= length +cache-vector-max-length+)
311 (%make-cache :key-count key-count
312 :line-size line-size
313 :vector (make-array length :initial-element '..empty..)
314 :value value
315 :mask (compute-cache-mask length line-size)
316 :limit (compute-limit adjusted-size))
317 ;; Make a smaller one, then
318 (make-cache :key-count key-count :value value :size (ceiling size 2)))))
320 (defconstant n-fixnum-bits #.(integer-length most-positive-fixnum))
322 ;;;; Copies and expands the cache, dropping any invalidated or
323 ;;;; incomplete lines.
324 (defun copy-and-expand-cache (cache layouts value)
325 (let ((copy (%copy-cache cache))
326 (length (length (cache-vector cache)))
327 (drop-random-entries nil))
328 (declare (index length))
329 (when (< length +cache-vector-max-length+)
330 (setf length (* 2 length)))
331 (tagbody
332 :again
333 ;; Blow way the old vector first, so a GC potentially triggered by
334 ;; MAKE-ARRAY can collect it.
335 (setf (cache-vector copy) #()
336 (cache-vector copy) (make-array length :initial-element '..empty..)
337 (cache-depth copy) 0
338 (cache-mask copy) (compute-cache-mask length (cache-line-size cache))
339 (cache-limit copy) (compute-limit (/ length (cache-line-size cache))))
340 ;; First insert the new one -- if we don't do this first and
341 ;; the cache has reached it's maximum size we may end up
342 ;; looping in FILL-CACHE.
343 (unless (try-update-cache copy layouts value)
344 (bug "Could not insert ~S:~S to supposedly empty ~S." layouts value copy))
345 (map-cache (if drop-random-entries
346 ;; The cache is at maximum size, and all entries
347 ;; do not fit in. Drop a random ~50% of entries,
348 ;; to make space for new ones. This needs to be
349 ;; random, since otherwise we might get in a
350 ;; rut: add A causing B to drop, then add B
351 ;; causing A to drop... repeat ad nauseam,
352 ;; spending most of the time here instead of
353 ;; doing real work. 50% because if we drop to
354 ;; few we need to do this almost right away
355 ;; again, and if we drop to many, we need to
356 ;; recompute more then we'd like.
357 ;; _Experimentally_ 50% seems to perform the
358 ;; best, but it would be nice to have a proper
359 ;; analysis...
360 (flet ((random-fixnum ()
361 (random (1+ most-positive-fixnum))))
362 (let ((drops (random-fixnum))
363 (drop-pos n-fixnum-bits))
364 (declare (fixnum drops)
365 (type (integer 0 #.n-fixnum-bits) drop-pos))
366 (lambda (layouts value)
367 (when (logbitp (the unsigned-byte (decf drop-pos)) drops)
368 (try-update-cache copy layouts value))
369 (when (zerop drop-pos)
370 (setf drops (random-fixnum)
371 drop-pos n-fixnum-bits)))))
372 (lambda (layouts value)
373 (unless (try-update-cache copy layouts value)
374 ;; Didn't fit -- expand the cache, or drop
375 ;; a few unlucky ones.
376 (if (< length +cache-vector-max-length+)
377 (setf length (* 2 length))
378 (setf drop-random-entries t))
379 (go :again))))
380 cache))
381 copy))
383 (defun cache-has-invalid-entries-p (cache)
384 (let ((vector (cache-vector cache))
385 (line-size (cache-line-size cache))
386 (key-count (cache-key-count cache))
387 (mask (cache-mask cache))
388 (index 0))
389 (loop
390 ;; Check if the line is in use, and check validity of the keys.
391 (let ((key1 (svref vector index)))
392 (when (cache-key-p key1)
393 (if (zerop (layout-clos-hash key1))
394 ;; First key invalid.
395 (return-from cache-has-invalid-entries-p t)
396 ;; Line is in use and the first key is valid: check the rest.
397 (loop for offset from 1 below key-count
398 do (let ((thing (svref vector (+ index offset))))
399 (when (or (not (cache-key-p thing))
400 (zerop (layout-clos-hash thing)))
401 ;; Incomplete line or invalid layout.
402 (return-from cache-has-invalid-entries-p t)))))))
403 ;; Line empty of valid, onwards.
404 (setf index (next-cache-index mask index line-size))
405 (when (zerop index)
406 ;; wrapped around
407 (return-from cache-has-invalid-entries-p nil)))))
409 (defun hash-table-to-cache (table &key value key-count)
410 (let ((cache (make-cache :key-count key-count :value value
411 :size (hash-table-count table))))
412 (maphash (lambda (class value)
413 (setq cache (fill-cache cache (class-wrapper class) value)))
414 table)
415 cache))
417 ;;; Inserts VALUE to CACHE keyd by LAYOUTS. Expands the cache if
418 ;;; necessary, and returns the new cache.
419 (defun fill-cache (cache layouts value)
420 (labels
421 ((%fill-cache (cache layouts value expand)
422 (cond ((try-update-cache cache layouts value)
423 cache)
424 ((and (not expand) (cache-has-invalid-entries-p cache))
425 ;; Don't expand yet: maybe there will be enough space if
426 ;; we just drop the invalid entries.
427 (%fill-cache (copy-cache cache) layouts value t))
429 (copy-and-expand-cache cache layouts value)))))
430 (if (listp layouts)
431 (%fill-cache cache layouts value nil)
432 (%fill-cache cache (list layouts) value nil))))
434 ;;; Calls FUNCTION with all layouts and values in cache.
435 (defun map-cache (function cache)
436 (let* ((vector (cache-vector cache))
437 (key-count (cache-key-count cache))
438 (valuep (cache-value cache))
439 (line-size (cache-line-size cache))
440 (mask (cache-mask cache))
441 (fun (if (functionp function)
442 function
443 (fdefinition function)))
444 (index 0))
445 (tagbody
446 :map
447 (let ((layouts
448 (loop for offset from 0 below key-count
449 collect (non-empty-or (svref vector (+ offset index))
450 (go :next)))))
451 (let ((value (when valuep
452 (non-empty-or (svref vector (+ index key-count))
453 (go :next)))))
454 ;; Let the callee worry about invalid layouts
455 (funcall fun layouts value)))
456 :next
457 (setf index (next-cache-index mask index line-size))
458 (unless (zerop index)
459 (go :map))))
460 cache)
462 ;;; Copying a cache without expanding it is very much like mapping it:
463 ;;; we need to be carefull because there may be updates while we are
464 ;;; copying it, and we don't want to copy incomplete entries or invalid
465 ;;; ones.
466 (defun copy-cache (cache)
467 (let* ((vector (cache-vector cache))
468 (copy (make-array (length vector) :initial-element '..empty..))
469 (line-size (cache-line-size cache))
470 (key-count (cache-key-count cache))
471 (valuep (cache-value cache))
472 (mask (cache-mask cache))
473 (size (/ (length vector) line-size))
474 (index 0)
475 (depth 0))
476 (tagbody
477 :copy
478 (let ((layouts (loop for offset from 0 below key-count
479 collect (non-empty-or (svref vector (+ index offset))
480 (go :next)))))
481 ;; Check validity & compute primary index.
482 (let ((primary (or (compute-cache-index cache layouts)
483 (go :next))))
484 ;; Check & copy value.
485 (when valuep
486 (setf (svref copy (+ index key-count))
487 (non-empty-or (svref vector (+ index key-count))
488 (go :next))))
489 ;; Copy layouts.
490 (loop for offset from 0 below key-count do
491 (setf (svref copy (+ index offset)) (pop layouts)))
492 ;; Update probe depth.
493 (let ((distance (/ (- index primary) line-size)))
494 (setf depth (max depth (if (minusp distance)
495 ;; account for wrap-around
496 (+ distance size)
497 distance))))))
498 :next
499 (setf index (next-cache-index mask index line-size))
500 (unless (zerop index)
501 (go :copy)))
502 (%make-cache :vector copy
503 :depth depth
504 :key-count (cache-key-count cache)
505 :line-size line-size
506 :value valuep
507 :mask mask
508 :limit (cache-limit cache))))
510 ;;;; For debugging & collecting statistics.
512 (defun map-all-caches (function)
513 (dolist (p (list-all-packages))
514 (do-symbols (s p)
515 (when (eq p (symbol-package s))
516 (dolist (name (list s
517 `(setf ,s)
518 (slot-reader-name s)
519 (slot-writer-name s)
520 (slot-boundp-name s)))
521 (when (fboundp name)
522 (let ((fun (fdefinition name)))
523 (when (typep fun 'generic-function)
524 (let ((cache (gf-dfun-cache fun)))
525 (when cache
526 (funcall function name cache)))))))))))
528 (defun check-cache-consistency (cache)
529 (let ((table (make-hash-table :test 'equal)))
530 (map-cache (lambda (layouts value)
531 (declare (ignore value))
532 (if (gethash layouts table)
533 (cerror "Check futher."
534 "Multiple appearances of ~S." layouts)
535 (setf (gethash layouts table) t)))
536 cache)))