source: trunk/source/level-1/l1-lisp-threads.lisp @ 12219

Last change on this file since 12219 was 12219, checked in by gz, 10 years ago

Rename nx-the-typechecks to nx-declarations-typecheck, and typecheck all declarations when it's on.
Merged from r11819 r11820 r11822 r11823 r11824 r11836 r11836 r11837 r11850 r11851 r11852 r11853

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 36.8 KB
RevLine 
[657]1;;; -*- Mode: LISP; Package: CCL -*-
[6]2;;;
3;;;   Copyright (C) 1994-2001 Digitool, Inc
[657]4;;;   This file is part of OpenMCL. 
[6]5;;;
[657]6;;;   OpenMCL is licensed under the terms of the Lisp Lesser GNU Public
7;;;   License , known as the LLGPL and distributed with OpenMCL as the
8;;;   file "LICENSE".  The LLGPL consists of a preamble and the LGPL,
9;;;   which is distributed with OpenMCL as the file "LGPL".  Where these
10;;;   conflict, the preamble takes precedence. 
[6]11;;;
[657]12;;;   OpenMCL is referenced in the preamble as the "LIBRARY."
[6]13;;;
[657]14;;;   The LLGPL is also available online at
15;;;   http://opensource.franz.com/preamble.html
[6]16
17;; l1-lisp-threads.lisp
18
[657]19(in-package "CCL")
[6]20
21(defvar *bind-io-control-vars-per-process* nil
22  "If true, bind I/O control variables per process")
23
[4884]24
[6]25             
26(defun lisp-thread-p (thing)
[4884]27  (istruct-typep thing 'lisp-thread))
[6]28
29(setf (type-predicate 'lisp-thread) 'lisp-thread-p)
30
31(defloadvar *ticks-per-second*
[10632]32    #+windows-target 1000
33    #-windows-target
[6]34    (#_sysconf #$_SC_CLK_TCK))
35
36(defloadvar *ns-per-tick*
37    (floor 1000000000 *ticks-per-second*))
38
[10632]39#-windows-target
[6]40(defun %nanosleep (seconds nanoseconds)
[10460]41  (with-process-whostate ("Sleep")
42    (rlet ((a :timespec)
43           (b :timespec))
44      (setf (pref a :timespec.tv_sec) seconds
45            (pref a :timespec.tv_nsec) nanoseconds)
46      (let* ((aptr a)
47             (bptr b))
48        (loop
49          (let* ((result 
50                  (external-call #+darwin-target "_nanosleep"
51                                 #-darwin-target "nanosleep"
52                                 :address aptr
53                                 :address bptr
54                                 :signed-fullword)))
55            (declare (type (signed-byte 32) result))
56            (if (and (< result 0)
57                     (eql (%get-errno) (- #$EINTR)))
58              ;; x86-64 Leopard bug.
59              (let* ((asec (pref aptr :timespec.tv_sec))
60                     (bsec (pref bptr :timespec.tv_sec)))
61                (if (and (>= bsec 0)
62                         (or (< bsec asec)
63                             (and (= bsec asec)
64                                  (< (pref bptr :timespec.tv_nsec)
65                                     (pref aptr :timespec.tv_nsec)))))
66                  (psetq aptr bptr bptr aptr)
67                  (return)))
68              (return))))))))
[6]69
70
71(defun timeval->ticks (tv)
72  (+ (* *ticks-per-second* (pref tv :timeval.tv_sec))
73     (round (pref tv :timeval.tv_usec) (floor 1000000 *ticks-per-second*))))
74
[10822]75
[10895]76(defun gettimeofday (ptimeval &optional ptz)
[10822]77  (int-errno-ffcall (%kernel-import target::kernel-import-lisp-gettimeofday)
78                    :address ptimeval
[10895]79                    :address (or ptz (%null-ptr))
[10822]80                    :int))
81
[6]82(defloadvar *lisp-start-timeval*
83    (progn
84      (let* ((r (make-record :timeval)))
[10895]85        (gettimeofday r)
[6]86        r)))
87
88
[3490]89(defloadvar *internal-real-time-session-seconds* nil)
[6]90
91
[3490]92(defun get-internal-real-time ()
93  "Return the real time in the internal time format. (See
94  INTERNAL-TIME-UNITS-PER-SECOND.) This is useful for finding elapsed time."
95  (rlet ((tv :timeval))
[10822]96    (gettimeofday tv)
[7948]97    (let* ((units (truncate (the fixnum (pref tv :timeval.tv_usec)) (/ 1000000 internal-time-units-per-second)))
[3490]98           (initial *internal-real-time-session-seconds*))
99      (if initial
100        (locally
101            (declare (type (unsigned-byte 32) initial))
[7948]102          (+ (* internal-time-units-per-second
103                (the (unsigned-byte 32)
104                  (- (the (unsigned-byte 32) (pref tv :timeval.tv_sec))
105                     initial)))
106             units))
[3490]107        (progn
108          (setq *internal-real-time-session-seconds*
109                (pref tv :timeval.tv_sec))
[10822]110          units)))))
[6]111
[3490]112(defun get-tick-count ()
113  (values (floor (get-internal-real-time)
114                 (floor internal-time-units-per-second
115                        *ticks-per-second*))))
[6]116
117
118
119
120(defun %kernel-global-offset (name-or-offset)
121  (if (fixnump name-or-offset)
122    name-or-offset
[1663]123    (target::%kernel-global name-or-offset)))
[6]124
[3635]125
[6]126(defun %kernel-global-offset-form (name-or-offset-form)
[3808]127  (cond ((quoted-form-p name-or-offset-form)
128         `(%target-kernel-global ,name-or-offset-form))
[6]129        ((fixnump name-or-offset-form)
130         name-or-offset-form)
[3808]131        (t `(%target-kernel-global ',name-or-offset-form))))
[6]132
133
134
135(defmacro %set-kernel-global (name-or-offset new-value)
136  `(%set-kernel-global-from-offset
137    ,(%kernel-global-offset-form name-or-offset)
138    ,new-value))
139
140
141
142; The number of bytes in a consing (or stack) area
143(defun %area-size (area)
[1663]144  (ash (- (%fixnum-ref area target::area.high)
145          (%fixnum-ref area target::area.low))
146       target::fixnumshift))
[6]147
148(defun %stack-area-usable-size (area)
[1663]149  (ash (- (%fixnum-ref area target::area.high)
150          (%fixnum-ref area target::area.softlimit))
[691]151       target::fixnum-shift))
[6]152
153(defun %cons-lisp-thread (name &optional tcr)
[4884]154  (%istruct 'lisp-thread
[6]155            tcr
156            name
157            0
158            0
159            0
160            nil
161            nil
162            (make-lock)
163            nil
164            :reset
[11744]165            (make-lock)))
[6]166
167(defvar *current-lisp-thread*
168  (%cons-lisp-thread "Initial" (%current-tcr)))
169
[6491]170(defstatic *initial-lisp-thread* *current-lisp-thread*)
[6]171
172(defun thread-change-state (thread oldstate newstate)
173  (with-lock-grabbed ((lisp-thread.state-change-lock thread))
174    (when (eq (lisp-thread.state thread) oldstate)
175      (setf (lisp-thread.state thread) newstate))))
176
177(thread-change-state *initial-lisp-thread* :reset :run)
178
179(defun thread-state (thread)
180  (with-lock-grabbed ((lisp-thread.state-change-lock thread))
181    (lisp-thread.state thread)))
182 
183(defun thread-make-startup-function (thread tcr)
184  #'(lambda ()
185      (thread-change-state thread :reset :run)
186      (let* ((*current-lisp-thread* thread)
187             (initial-function (lisp-thread.initial-function.args thread)))
188        (tcr-clear-preset-state tcr)
189        (%set-tcr-toplevel-function tcr nil)
190        (setf (interrupt-level) 0)
191        (apply (car initial-function) (cdr initial-function))
192        (cleanup-thread-tcr thread tcr))))
193
194(defun init-thread-from-tcr (tcr thread)
[2604]195  (let* ((cs-area (%fixnum-ref tcr target::tcr.cs-area))
196         (vs-area (%fixnum-ref tcr target::tcr.vs-area))
197         (ts-area (%fixnum-ref tcr target::tcr.ts-area)))
198    (when (or (zerop cs-area)
199              (zerop vs-area)
200              (zerop ts-area))
201      (error "Can't allocate new thread"))
202    (setf (lisp-thread.tcr thread) tcr
203          (lisp-thread.cs-size thread)
204          (%stack-area-usable-size cs-area)
205          (lisp-thread.vs-size thread)
206          (%stack-area-usable-size vs-area)
207          (lisp-thread.ts-size thread)
208          (%stack-area-usable-size ts-area)
209          (lisp-thread.startup-function thread)
210          (thread-make-startup-function thread tcr)))
[8167]211  (thread-change-state thread :exit :reset)
[6]212  thread)
213
[3307]214(defun default-allocation-quantum ()
215  (ash 1 (%get-kernel-global 'default-allocation-quantum)))
216
[6]217(defun new-lisp-thread-from-tcr (tcr name)
218  (let* ((thread (%cons-lisp-thread name tcr)))   
219    (init-thread-from-tcr tcr thread)
220    (push thread (population-data *lisp-thread-population*))
221    thread))
222
223(def-ccl-pointers initial-thread ()
224  (init-thread-from-tcr (%current-tcr) *initial-lisp-thread*))
225
226(defmethod print-object ((thread lisp-thread) stream)
227  (print-unreadable-object (thread stream :type t :identity t)
228    (format stream "~a" (lisp-thread.name thread))
229    (let* ((tcr (lisp-thread.tcr thread)))
230      (if (and tcr (not (eql 0 tcr)))
[691]231        (format stream " [tcr @ #x~x]" (ash tcr target::fixnumshift))))))
[6]232
233
234(defvar *lisp-thread-population*
[602]235  (%cons-population (list *initial-lisp-thread*) $population_weak-list nil))
[6]236
237
238
239
[602]240
[3490]241(defparameter *default-control-stack-size*
242  #+32-bit-target (ash 1 20)
243  #+64-bit-target (ash 2 20))
244(defparameter *default-value-stack-size*
245  #+32-bit-target (ash 1 20)
246  #+64-bit-target (ash 2 20))
247(defparameter *default-temp-stack-size*
248  #+32-bit-target (ash 1 19)
249  #+64-bit-target (ash 2 19))
[6]250
[3525]251
[6491]252(defstatic *initial-listener-default-control-stack-size* *default-control-stack-size*)
253(defstatic *initial-listener-default-value-stack-size* *default-value-stack-size*)
254(defstatic *initial-listener-default-temp-stack-size* *default-temp-stack-size*)
[3525]255
256
257(def-ccl-pointers listener-stack-sizes ()
258  (let* ((size (%get-kernel-global 'stack-size))) ; set by --thread-stack-size
[3504]259    (declare (fixnum size))
260    (when (> size 0)
[3525]261      (setq *initial-listener-default-control-stack-size* size
262            *initial-listener-default-value-stack-size* size
263            *initial-listener-default-temp-stack-size* (floor size 2)))))
[6]264
[3504]265
[6]266(defmacro with-area-macptr ((var area) &body body)
267  `(with-macptrs (,var)
268     (%setf-macptr-to-object ,var ,area)
269     ,@body))
270
271
272(defun gc-area.return-sp (area)
[1663]273  (%fixnum-ref area target::area.gc-count))
[6]274
275
276(defun (setf gc-area.return-sp) (return-sp area)
[1663]277  (setf (%fixnum-ref area target::area.gc-count) return-sp))
[6]278
279
[1663]280
[6]281(defun shutdown-lisp-threads ()
282  )
283
284(defun %current-xp ()
[1479]285  (let ((xframe (%fixnum-ref (%current-tcr) target::tcr.xframe)))
[6]286    (when (eql xframe 0)
287      (error "No current exception frame"))
288    (%fixnum-ref xframe
289                 (get-field-offset :xframe-list.this))))
290
291(defun new-tcr (cs-size vs-size ts-size)
[2604]292  (let* ((tcr (macptr->fixnum
293               (ff-call
294                (%kernel-import target::kernel-import-newthread)
[9787]295                #+64-bit-target :unsigned-doubleword
296                #+32-bit-target :unsigned-fullword cs-size
297                #+64-bit-target :unsigned-doubleword
298                #+32-bit-target :unsigned-fullword vs-size
299                #+64-bit-target :unsigned-doubleword
300                #+32-bit-target :unsigned-fullword ts-size
[2604]301                :address))))
[11958]302    (declare (fixnum tcr))
[2604]303    (if (zerop tcr)
304      (error "Can't create thread")
305      tcr)))
[6]306
307(defun new-thread (name cstack-size vstack-size tstack-size)
308  (new-lisp-thread-from-tcr (new-tcr cstack-size vstack-size tstack-size) name))
309
310(defun new-tcr-for-thread (thread)
311  (let* ((tcr (new-tcr
312               (lisp-thread.cs-size thread)
313               (lisp-thread.vs-size thread)
314               (lisp-thread.ts-size thread))))
315    (setf (lisp-thread.tcr thread) tcr
316          (lisp-thread.startup-function thread)
317          (thread-make-startup-function thread tcr))
[8167]318    (thread-change-state thread :exit :reset)
[6]319    tcr))
320 
321         
322
323
[7624]324
[6]325(defconstant cstack-hardprot (ash 100 10))
326(defconstant cstack-softprot (ash 100 10))
327
328
329
330(defun tcr-flags (tcr)
[1663]331  (%fixnum-ref tcr target::tcr.flags))
[6]332
333
[10460]334
[11659]335(defun %tcr-frame-ptr (tcr)
336  (with-macptrs (p)
337    (%setf-macptr-to-object p tcr)
338    (%fixnum-from-macptr
339     (ff-call (%kernel-import target::kernel-import-tcr-frame-ptr)
340              :address p
341              :address))))
342 
[6]343(defun thread-exhausted-p (thread)
344  (or (null thread)
[10460]345      (null (lisp-thread.tcr thread))))
[6]346
347(defun thread-total-run-time (thread)
348  (unless (thread-exhausted-p thread)
349    nil))
350
[3490]351(defun %tcr-interrupt (tcr)
[6193]352  ;; The other thread's interrupt-pending flag might get cleared
353  ;; right after we look and see it set, but since this is called
354  ;; with the lock on the thread's interrupt queue held, the
355  ;; pending interrupt won't have been taken yet.
356  ;; When a thread dies, it should try to clear its interrupt-pending
357  ;; flag.
[8579]358  (if (eql 0 (%fixnum-ref tcr target::tcr.interrupt-pending))
359    (%%tcr-interrupt tcr)
360    0))
[6]361
[3490]362
[6193]363
[3490]364     
365     
366
[6]367(defun thread-interrupt (thread process function &rest args)
368  (with-lock-grabbed ((lisp-thread.state-change-lock thread))
369    (case (lisp-thread.state thread)
370      (:run 
371       (with-lock-grabbed ((lisp-thread.interrupt-lock thread))
[3490]372         (let ((tcr (lisp-thread.tcr thread)))
373           (when tcr
[6]374             (push (cons function args)
375                   (lisp-thread.interrupt-functions thread))
[3490]376             (eql 0 (%tcr-interrupt tcr))))))
[6]377      (:reset
378       ;; Preset the thread with a function that'll return to the :reset
379       ;; state
380       (let* ((pif (process-initial-form process))
381              (pif-f (car pif))
382              (pif-args (cdr pif)))
383         (process-preset process #'(lambda ()
384                                     (%rplaca pif pif-f)
385                                     (%rplacd pif pif-args)
386                                     (apply function args)
387                                     ;; If function returns normally,
388                                     ;; return to the reset state
389                                     (%process-reset nil)))
[3307]390         (thread-enable thread (process-termination-semaphore process) (1- (integer-length (process-allocation-quantum process))) 0)
[2613]391         t)))))
[6]392
393(defun thread-handle-interrupts ()
394  (let* ((thread *current-lisp-thread*))
[2343]395    (with-process-whostate ("Active")
396      (loop
397        (let* ((f (with-lock-grabbed ((lisp-thread.interrupt-lock thread))
398                    (pop (lisp-thread.interrupt-functions thread)))))
399          (if f
400            (apply (car f) (cdr f))
401            (return)))))))
[6]402
403
404       
[11744]405(defun  thread-preset (thread function &rest args)
[6]406  (setf (lisp-thread.initial-function.args thread)
407        (cons function args)))
408
[10210]409(defun thread-enable (thread termination-semaphore allocation-quantum &optional (timeout (* 60 60 24)))
[6]410  (let* ((tcr (or (lisp-thread.tcr thread) (new-tcr-for-thread thread))))
[4690]411    (with-macptrs (s)
412      (%setf-macptr-to-object s (%fixnum-ref tcr target::tcr.reset-completion))
413      (when (%timed-wait-on-semaphore-ptr s timeout nil)
414        (%set-tcr-toplevel-function
415         tcr
416         (lisp-thread.startup-function thread))
[5607]417        (%activate-tcr tcr termination-semaphore allocation-quantum)
[4690]418        thread))))
[6]419                             
420
421(defun cleanup-thread-tcr (thread tcr)
[1663]422  (let* ((flags (%fixnum-ref tcr target::tcr.flags)))
[6]423    (declare (fixnum flags))
[212]424    (if (logbitp arch::tcr-flag-bit-awaiting-preset flags)
[6]425      (thread-change-state thread :run :reset)
426      (progn
427        (thread-change-state thread :run :exit)
428        (setf (lisp-thread.tcr thread) nil)))))
429
430(defun kill-lisp-thread (thread)
[5620]431  (unless (eq thread *initial-lisp-thread*)
[11151]432    (let* ((tcr (lisp-thread.tcr thread)))
433      (when tcr
[5607]434        (setf (lisp-thread.tcr thread) nil
435              (lisp-thread.state thread) :exit)
[11151]436        (%kill-tcr tcr)))))
[6]437
[11744]438;;; This returns the underlying pthread, whatever that is, as an
439;;; unsigned integer.
[6]440(defun lisp-thread-os-thread (thread)
441  (with-macptrs (tcrp)
442    (%setf-macptr-to-object tcrp (lisp-thread.tcr thread))
443    (unless (%null-ptr-p tcrp)
[11744]444      (let* ((natural (%get-natural tcrp target::tcr.osid)))
445        (unless (zerop natural) natural)))))
446
447
[6]448                         
449;;; This returns something lower-level than the pthread, if that
450;;; concept makes sense.  On current versions of Linux, it returns
451;;; the pid of the clone()d process; on Darwin, it returns a Mach
452;;; thread.  On some (near)future version of Linux, the concept
453;;; may not apply.
[2199]454;;; The future is here: on Linux systems using NPTL, this returns
455;;; exactly the same thing that (getpid) does.
456;;; This should probably be retired; even if it does something
457;;; interesting, is the value it returns useful ?
[6]458
459(defun lisp-thread-native-thread (thread)
460  (with-macptrs (tcrp)
461    (%setf-macptr-to-object tcrp (lisp-thread.tcr thread))
462    (unless (%null-ptr-p tcrp)
[3307]463      (#+32-bit-target %get-unsigned-long
464       #+64-bit-target %%get-unsigned-longlong tcrp target::tcr.native-thread-id))))
[6]465
466(defun lisp-thread-suspend-count (thread)
467  (with-macptrs (tcrp)
468    (%setf-macptr-to-object tcrp (lisp-thread.tcr thread))
469    (unless (%null-ptr-p tcrp)
[3307]470      (#+32-bit-target %get-unsigned-long
471       #+64-bit-target %%get-unsigned-longlong tcrp target::tcr.suspend-count))))
[6]472
473(defun tcr-clear-preset-state (tcr)
[1663]474  (let* ((flags (%fixnum-ref tcr target::tcr.flags)))
[6]475    (declare (fixnum flags))
[1663]476    (setf (%fixnum-ref tcr target::tcr.flags)
[212]477          (bitclr arch::tcr-flag-bit-awaiting-preset flags))))
[6]478
479(defun tcr-set-preset-state (tcr)
[1663]480  (let* ((flags (%fixnum-ref tcr target::tcr.flags)))
[6]481    (declare (fixnum flags))
[1663]482    (setf (%fixnum-ref tcr target::tcr.flags)
[212]483          (bitset arch::tcr-flag-bit-awaiting-preset flags)))) 
[6]484
[11744]485;;; This doesn't quite activate the thread; see PROCESS-TCR-ENABLE.
[3307]486(defun %activate-tcr (tcr termination-semaphore allocation-quantum)
[6]487  (if (and tcr (not (eql 0 tcr)))
[11744]488    (with-macptrs (tcrp)
[2704]489      (%setf-macptr-to-object tcrp tcr)
[11744]490      (setf (%get-natural tcrp target::tcr.log2-allocation-quantum)
491            (or allocation-quantum (default-allocation-quantum)))
492      (setf (%get-ptr tcrp target::tcr.termination-semaphore)
493            (if termination-semaphore
494              (semaphore-value termination-semaphore)
495              (%null-ptr)))
496      t)))
[6]497                         
498(defvar *canonical-error-value*
499  '(*canonical-error-value*))
500
501
502(defun symbol-value-in-tcr (sym tcr)
[2655]503  (if (eq tcr (%current-tcr))
504    (%sym-value sym)
505    (unwind-protect
506         (progn
507           (%suspend-tcr tcr)
508           (let* ((loc (%tcr-binding-location tcr sym)))
509             (if loc
510               (%fixnum-ref loc)
511               (%sym-global-value sym))))
512      (%resume-tcr tcr))))
[6]513
514(defun (setf symbol-value-in-tcr) (value sym tcr)
[2655]515  (if (eq tcr (%current-tcr))
516    (%set-sym-value sym value)
517    (unwind-protect
518         (progn
519           (%suspend-tcr tcr)
520           (let* ((loc (%tcr-binding-location tcr sym)))
521             (if loc
522               (setf (%fixnum-ref loc) value)
523               (%set-sym-global-value sym value))))
524      (%resume-tcr tcr))))
[6]525
526;;; Backtrace support
527;;;
528
529
[784]530
[6]531(defmacro do-db-links ((db-link &optional var value) &body body)
532  (let ((thunk (gensym))
533        (var-var (or var (gensym)))
534        (value-var (or value (gensym))))
535    `(block nil
536       (let ((,thunk #'(lambda (,db-link ,var-var ,value-var)
537                         (declare (ignorable ,db-link))
538                         ,@(unless var (list `(declare (ignore ,var-var))))
539                         ,@(unless value (list `(declare (ignore ,value-var))))
540                         ,@body)))
541         (declare (dynamic-extent ,thunk))
542         (map-db-links ,thunk)))))
543
544
545
[85]546
[6]547(defun map-db-links (f)
548  (without-interrupts
[1663]549   (let ((db-link (%current-db-link)))
[6]550     (loop
551       (when (eql 0 db-link) (return))
[1663]552       (funcall f db-link (%fixnum-ref db-link (* 1 target::node-size)) (%fixnum-ref db-link (* 2 target::node-size)))
[6]553       (setq db-link (%fixnum-ref db-link))))))
554
[784]555(defun %get-frame-ptr ()
556  (%current-frame-ptr))
[6]557
558
[784]559
[6]560
561
562
563
[4447]564
[6]565(defun next-catch (catch)
[1663]566  (let ((next-catch (uvref catch target::catch-frame.link-cell)))
[6]567    (unless (eql next-catch 0) next-catch)))
568
569
570
[4447]571
[6]572; @@@ this needs to load early so errors can work
[784]573(defun next-lisp-frame (p context)
[6]574  (let ((frame p))
575    (loop
[784]576      (let ((parent (%frame-backlink frame context)))
577        (multiple-value-bind (lisp-frame-p bos-p) (lisp-frame-p parent context)
[6]578          (if lisp-frame-p
579            (return parent)
580            (if bos-p
581              (return nil))))
582        (setq frame parent)))))
583
[784]584(defun parent-frame (p context)
[6]585  (loop
[784]586    (let ((parent (next-lisp-frame p context)))
[6]587      (when (or (null parent)
[784]588                (not (catch-csp-p parent context)))
[6]589        (return parent))
590      (setq p parent))))
591
592
593
[4447]594
595
[11659]596(defun last-frame-ptr (&optional context origin)
597  (let* ((current (or origin
598                      (if context (bt.current context) (%current-frame-ptr))))
[6]599         (last current))
600    (loop
[784]601      (setq current (parent-frame current context))
[6]602      (if current
603        (setq last current)
604        (return last)))))
605
606
607
[784]608(defun child-frame (p context )
609  (let* ((current (if context (bt.current context) (%current-frame-ptr)))
[6]610         (last nil))
611    (loop
612      (when (null current)
613        (return nil))
614      (when (eq current p) (return last))
615      (setq last current
[784]616            current (parent-frame current context)))))
[6]617
618
619
620
[4447]621
[6]622; This returns the current head of the db-link chain.
[784]623(defun db-link (&optional context)
624  (if context
625    (bt.db-link context)
[1663]626    (%fixnum-ref (%current-tcr)  target::tcr.db-link)))
[6]627
[657]628(defun previous-db-link (db-link start )
[6]629  (declare (fixnum db-link start))
[657]630  (let ((prev nil))
631    (loop
632      (when (or (eql db-link start) (eql 0 start))
633        (return prev))
634      (setq prev start
635            start (%fixnum-ref start 0)))))
[6]636
[784]637(defun count-db-links-in-frame (vsp parent-vsp &optional context)
[6]638  (declare (fixnum vsp parent-vsp))
[784]639  (let ((db (db-link context))
[6]640        (count 0)
641        (first nil)
[657]642        (last nil))
[6]643    (declare (fixnum db count))
644    (loop
645      (cond ((eql db 0)
646             (return (values count (or first 0) (or last 0))))
647            ((and (>= db vsp) (< db parent-vsp))
648             (unless first (setq first db))
649             (setq last db)
650             (incf count)))
651      (setq db (%fixnum-ref db)))))
652
653;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
654;;;
655;;; bogus-thing-p support
656;;;
657
658(defun %ptr-in-area-p (ptr area)
[12219]659  (declare (optimize (speed 3) (safety 0)) (fixnum ptr area))           ; lie, maybe
[1663]660  (and (<= (the fixnum (%fixnum-ref area target::area.low)) ptr)
661       (> (the fixnum (%fixnum-ref area target::area.high)) ptr)))
[6]662
663(defun %active-area (area active)
[1663]664  (or (do ((a area (%fixnum-ref a target::area.older)))
[6]665          ((eql a 0))
666        (when (%ptr-in-area-p active a)
667          (return a)))
[1663]668      (do ((a (%fixnum-ref area target::area.younger) (%fixnum-ref a target::area.younger)))
[6]669          ((eql a 0))
670        (when (%ptr-in-area-p active a)
671          (return a)))))
672
673(defun %ptr-to-vstack-p (tcr idx)
[1663]674  (%ptr-in-area-p idx (%fixnum-ref tcr target::tcr.vs-area)))
[6]675
676(defun %on-tsp-stack (tcr object)
[1663]677  (%ptr-in-area-p object (%fixnum-ref tcr target::tcr.ts-area)))
[6]678
[4563]679(defun %on-csp-stack (tcr object)
680  (%ptr-in-area-p object (%fixnum-ref tcr target::tcr.cs-area)))
681
[657]682(defparameter *aux-tsp-ranges* ())
683(defparameter *aux-vsp-ranges* ())
[4563]684(defparameter *aux-csp-ranges* ())
685
[657]686(defun object-in-range-p (object range)
687  (declare (fixnum object))
688  (when range
689    (destructuring-bind (active . high) range
690      (declare (fixnum active high))
691      (and (< active object)
692           (< object high)))))
693
694(defun object-in-some-range (object ranges)
695  (dolist (r ranges)
696    (when (object-in-range-p object r)
697      (return t))))
698
699
[6]700(defun on-any-tsp-stack (object)
[657]701  (or (%on-tsp-stack (%current-tcr) object)
702      (object-in-some-range object *aux-tsp-ranges*)))
[6]703
704(defun on-any-vstack (idx)
[657]705  (or (%ptr-to-vstack-p (%current-tcr) idx)
706      (object-in-some-range idx *aux-vsp-ranges*)))
[6]707
[4563]708(defun on-any-csp-stack (object)
709  (or (%on-csp-stack (%current-tcr) object)
710      (object-in-some-range object *aux-csp-ranges*)))
711
[4534]712;;; This MUST return either T or NIL.
[6]713(defun temporary-cons-p (x)
714  (and (consp x)
715       (not (null (or (on-any-vstack x)
716                      (on-any-tsp-stack x))))))
717
718
719
720
721
[3747]722
[4005]723
[6]724(defun %value-cell-header-at-p (cur-vsp)
[1663]725  (eql target::value-cell-header (%fixnum-address-of (%fixnum-ref cur-vsp))))
[6]726
727(defun count-stack-consed-value-cells-in-frame (vsp parent-vsp)
728  (let ((cur-vsp vsp)
729        (count 0))
730    (declare (fixnum cur-vsp count))
731    (loop
732      (when (>= cur-vsp parent-vsp) (return))
733      (when (and (evenp cur-vsp) (%value-cell-header-at-p cur-vsp))
734        (incf count)
735        (incf cur-vsp))                 ; don't need to check value after header
736      (incf cur-vsp))
737    count))
738
[3307]739;;; stack consed value cells are one of two forms:
[4244]740;;; Well, they were of two forms.  When they existed, that is.
[3307]741;;;
742;;; nil             ; n-4
743;;; header          ; n = even address (multiple of 8)
744;;; value           ; n+4
745;;;
746;;; header          ; n = even address (multiple of 8)
747;;; value           ; n+4
748;;; nil             ; n+8
[6]749
750(defun in-stack-consed-value-cell-p (arg-vsp vsp parent-vsp)
751  (declare (fixnum arg-vsp vsp parent-vsp))
752  (if (evenp arg-vsp)
753    (%value-cell-header-at-p arg-vsp)
754    (or (and (> arg-vsp vsp)
755             (%value-cell-header-at-p (the fixnum (1- arg-vsp))))
756        (let ((next-vsp (1+ arg-vsp)))
757          (declare (fixnum next-vsp))
758          (and (< next-vsp parent-vsp)
759               (%value-cell-header-at-p next-vsp))))))
760
761
[4244]762
[784]763(defun count-values-in-frame (p context &optional child)
[6]764  (declare (ignore child))
[784]765  (multiple-value-bind (vsp parent-vsp) (vsp-limits p context)
[6]766    (values
767     (- parent-vsp 
768        vsp
[4244]769        (* 2 (count-db-links-in-frame vsp parent-vsp context))))))
[6]770
[4250]771(defun nth-value-in-frame-loc (sp n context lfun pc vsp parent-vsp)
[6]772  (declare (fixnum sp))
773  (setq n (require-type n 'fixnum))
774  (unless (or (null vsp) (fixnump vsp))
775    (setq vsp (require-type vsp '(or null fixnum))))
776  (unless (or (null parent-vsp) (fixnump parent-vsp))
777    (setq parent-vsp (require-type parent-vsp '(or null fixnum))))
778  (unless (and vsp parent-vsp)
[784]779    (multiple-value-setq (vsp parent-vsp) (vsp-limits sp context)))
[6]780  (locally (declare (fixnum n vsp parent-vsp))
781    (multiple-value-bind (db-count first-db last-db)
[784]782                         (count-db-links-in-frame vsp parent-vsp context)
[6]783      (declare (ignore db-count))
784      (declare (fixnum first-db last-db))
785      (let ((arg-vsp (1- parent-vsp))
786            (cnt n)
787            (phys-cell 0)
788            db-link-p)
789        (declare (fixnum arg-vsp cnt phys-cell))
790        (loop
791          (if (eql (the fixnum (- arg-vsp 2)) last-db)
792            (setq db-link-p t
793                  arg-vsp last-db
[657]794                  last-db (previous-db-link last-db first-db)
[6]795                  phys-cell (+ phys-cell 2))
796            (setq db-link-p nil))
797            (when (< (decf cnt) 0)
798              (return
799               (if db-link-p
800                 (values (+ 2 arg-vsp)
801                         :saved-special
[2666]802                         (binding-index-symbol (%fixnum-ref (1+ arg-vsp))))
[6]803                 (multiple-value-bind (type name) (find-local-name phys-cell lfun pc)
[4244]804                   (values arg-vsp type name)))))
[6]805          (incf phys-cell)
806          (when (< (decf arg-vsp) vsp)
[5978]807            (error "~d out of range" n)))))))
[6]808
[49]809
[85]810
[4250]811(defun nth-value-in-frame (sp n context &optional lfun pc vsp parent-vsp)
[6]812  (multiple-value-bind (loc type name)
[4250]813                       (nth-value-in-frame-loc sp n context lfun pc vsp parent-vsp)
[49]814    (let* ((val (%fixnum-ref loc)))
815      (when (and (eq type :saved-special)
816                 (eq val (%no-thread-local-binding-marker))
817                 name)
818        (setq val (%sym-global-value name)))
819      (values val  type name))))
[6]820
[4250]821(defun set-nth-value-in-frame (sp n context new-value &optional vsp parent-vsp)
[49]822  (multiple-value-bind (loc type name)
[4250]823      (nth-value-in-frame-loc sp n context nil nil vsp parent-vsp)
[49]824    (let* ((old-value (%fixnum-ref loc)))
825      (if (and (eq type :saved-special)
826               (eq old-value (%no-thread-local-binding-marker))
827               name)
828        ;; Setting the (shallow-bound) value of the outermost
829        ;; thread-local binding of NAME.  Hmm.
830        (%set-sym-global-value name new-value)
831        (setf (%fixnum-ref loc) new-value)))))
[6]832
[784]833(defun nth-raw-frame (n start-frame context)
[6]834  (declare (fixnum n))
[784]835  (do* ((p start-frame (parent-frame p context))
[6]836        (i 0 (1+ i))
[784]837        (q (last-frame-ptr context)))
838       ((or (null p) (eq p q) (%stack< q p context)))
[6]839    (declare (fixnum i))
840    (if (= i n)
841      (return p))))
842
[4244]843;;; True if the object is in one of the heap areas
[6]844(defun %in-consing-area-p (x area)
[12210]845  (declare (optimize (speed 3) (safety 0)) (fixnum x))       ; lie
[1663]846  (let* ((low (%fixnum-ref area target::area.low))
847         (high (%fixnum-ref area target::area.high))
[6]848)
849    (declare (fixnum low high))
850    (and (<= low x) (< x high))))
851
852
853
854(defun in-any-consing-area-p (x)
855  (do-consing-areas (area)
856    (when (%in-consing-area-p x area)
857      (return t))))
858
859
860
861
862
863
864
865
[1697]866
[6]867;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
868;;;
869;;; terminate-when-unreachable
870;;;
871
872#|
873Message-Id: <v02130502ad3e6a2f1542@[205.231.144.48]>
874Mime-Version: 1.0
875Content-Type: text/plain; charset="us-ascii"
876Date: Wed, 7 Feb 1996 10:32:55 -0500
877To: pmcldev@digitool.com
878From: bitCraft@taconic.net (Bill St. Clair)
879Subject: terminate-when-unreachable
880
881I propose that we add a general termination mechanism to PPC MCL.
882We need it to properly terminate stack groups, it would be
883a nicer way to do the termination for macptrs than the current
884ad-hoc mechanism (which BTW is not yet part of PPC MCL), and
885it is a nice addition to MCL. I don't think it's hard to make
886the garbage collector support this, and I volunteer to do the
887work unless Gary really wants to.
888
889I see two ways to support termination:
890
8911) Do termination for hash tables. This was our plan for
892   2.0, but Gary got confused about how to mark the objects at
893   the right time (or so I remember).
894
8952) Resurrect weak alists (they're not part of the PPC garbage
896   collector) and add a termination bit to the population type.
897   This allows for termination of weak lists and weak alists,
898   though the termination mechanism really only needs termination
899   for a single weak alist.
900
901I prefer option 2, weak alists, since it avoids the overhead
902necessary to grow and rehash a hash table. It also uses less space,
903since a finalizeable hash table needs to allocate two cons cells
904for each entry so that the finalization code has some place to
905put the deleted entry.
906
907I propose the following interface (slightly modified from what
908Apple Dylan provides):
909
910terminate-when-unreachable object &optional (function 'terminate)
911  When OBJECT becomes unreachable, funcall FUNCTION with OBJECT
912  as a single argument. Each call of terminate-when-unreachable
913  on a single (EQ) object registers a new termination function.
914  All will be called when the object becomes unreachable.
915
916terminate object                                         [generic function]
917  The default termination function
918
919terminate (object t)                                     [method]
920  The default method. Ignores object. Returns nil.
921
922drain-termination-queue                                  [function]
923  Drain the termination queue. I.e. call the termination function
924  for every object that has become unreachable.
925
926*enable-automatic-termination*                           [variable]
927  If true, the default, drain-termination-queue will be automatically
928  called on the first event check after the garbage collector runs.
929  If you set this to false, you are responsible for calling
930  drain-termination-queue.
931
932cancel-terminate-when-unreachable object &optional function
933  Removes the effect of the last call to terminate-when-unreachable
934  for OBJECT & FUNCTION (both tested with EQ). Returns true if
935  it found a match (which it won't if the object has been moved
936  to the termination queue since terminate-when-unreachable was called).
937  If FUNCTION is NIL or unspecified, then it will not be used; the
938  last call to terminate-when-unreachable with the given OBJECT will
939  be undone.
940
941termination-function object
942  Return the function passed to the last call of terminate-when-unreachable
943  for OBJECT. Will be NIL if the object has been put in the
944  termination queue since terminate-when-unreachable was called.
945
946|#
947
948
[7624]949(defstatic *termination-population*
[6]950  (%cons-terminatable-alist))
951
[7624]952(defstatic *termination-population-lock* (make-lock))
[6]953
[422]954
[6]955(defvar *enable-automatic-termination* t)
956
957(defun terminate-when-unreachable (object &optional (function 'terminate))
[2442]958  "The termination mechanism is a way to have the garbage collector run a
959function right before an object is about to become garbage. It is very
960similar to the finalization mechanism which Java has. It is not standard
961Common Lisp, although other Lisp implementations have similar features.
962It is useful when there is some sort of special cleanup, deallocation,
963or releasing of resources which needs to happen when a certain object is
964no longer being used."
[7624]965  (let ((new-cell (cons object function))
[6]966        (population *termination-population*))
[465]967    (without-interrupts
968     (with-lock-grabbed (*termination-population-lock*)
[7624]969       (atomic-push-uvector-cell population population.data new-cell)))
[6]970    function))
971
972(defmethod terminate ((object t))
973  nil)
974
975(defun drain-termination-queue ()
[7624]976  (with-lock-grabbed (*termination-population-lock*)
977    (let* ((population *termination-population*))
978      (loop
979        (multiple-value-bind (cell existed)
980            (atomic-pop-uvector-cell population population.termination-list)
981          (if (not existed)
982            (return)
983          (funcall (cdr cell) (car cell))))))))
[6]984
985(defun cancel-terminate-when-unreachable (object &optional (function nil function-p))
[7624]986  (let* ((found nil))
987    (with-lock-grabbed (*termination-population-lock*)
988      ;; Have to defer GCing, e.g., defer responding to a GC
989      ;; suspend request here (that also defers interrupts)
990      ;; We absolutely, positively can't take an exception
991      ;; in here, so don't even bother to typecheck on
992      ;; car/cdr etc.
993      (with-deferred-gc
994          (do ((spine (population-data *termination-population*) (cdr spine))
995               (prev nil spine))
996              ((null spine))
997            (declare (optimize (speed 3) (safety 0)))
998            (let* ((head (car spine))
999                   (tail (cdr spine))
1000                   (o (car head))
1001                   (f (cdr head)))
1002              (when (and (eq o object)
1003                         (or (null function-p)
1004                             (eq function f)))
1005                (if prev
1006                  (setf (cdr prev) tail)
1007                  (setf (population-data *termination-population*) tail))
1008                (setq found t)
1009                (return)))))
1010      found)))
[6]1011
[7624]1012
[6]1013(defun termination-function (object)
[465]1014  (without-interrupts
1015   (with-lock-grabbed (*termination-population-lock*)
1016     (cdr (assq object (population-data *termination-population*))))))
[6]1017
1018(defun do-automatic-termination ()
1019  (when *enable-automatic-termination*
1020    (drain-termination-queue)))
1021
1022(queue-fixup
1023 (add-gc-hook 'do-automatic-termination :post-gc))
1024
[4563]1025;;; A callback to handle foreign thread preparation, initialization,
1026;;; and termination.
1027;;; "preparation" involves telling the kernel to reserve space for
1028;;; some initial thread-specific special bindings.  The kernel
1029;;; needs to reserve this space on the foreign thread's vstack;
1030;;; it needs us to tell it how much space to reserve (enough
1031;;; for bindings of *current-thread*, *current-process*, and
1032;;; the default initial bindings of *PACKAGE*, etc.)
1033;;;
1034;;; "initialization" involves making those special bindings in
1035;;; the vstack space reserved by the kernel, and setting the
1036;;; values of *current-thread* and *current-process* to newly
1037;;; created values.
1038;;;
1039;;; "termination" involves removing the current thread and
1040;;; current process from the global thread/process lists.
1041;;; "preparation" and "initialization" happen when the foreign
1042;;; thread first tries to call lisp code.  "termination" happens
1043;;; via the pthread thread-local-storage cleanup mechanism.
1044(defcallback %foreign-thread-control (:without-interrupts t :int param :int)
1045  (declare (fixnum param))
1046  (cond ((< param 0) (%foreign-thread-prepare))
1047        ((= param 0) (%foreign-thread-initialize) 0)
1048        (t (%foreign-thread-terminate) 0)))
1049
1050
1051
1052(defun %foreign-thread-prepare ()
1053  (let* ((initial-bindings (standard-initial-bindings)))
1054    (%save-standard-binding-list initial-bindings)
1055    (* 3 (+ 2 (length initial-bindings)))))
1056
1057
1058(defun %foreign-thread-initialize ()
1059  ;; Recover the initial-bindings alist.
1060  (let* ((bsp (%saved-bindings-address))
1061         (initial-bindings (%fixnum-ref bsp )))
1062    (declare (fixnum bsp))
1063    ;; Um, this is a little more complicated now that we use
1064    ;; thread-local shallow binding
1065    (flet ((save-binding (new-value sym prev)
[11242]1066             (let* ((idx (symbol-binding-index sym))
[4563]1067                    (byte-idx (ash idx target::fixnum-shift))
1068                    (binding-vector (%fixnum-ref (%current-tcr) target::tcr.tlb-pointer))
1069                    (old-value (%fixnum-ref  binding-vector byte-idx)))
1070             (setf (%fixnum-ref binding-vector byte-idx) new-value
1071                   (%fixnum-ref bsp (ash -1 target::word-shift)) old-value
1072                   (%fixnum-ref bsp (ash -2 target::word-shift)) idx
1073                   (%fixnum-ref bsp (ash -3 target::word-shift)) prev
1074                   bsp (- bsp 3)))))
1075      (save-binding nil '*current-lisp-thread* 0)
1076      (save-binding nil '*current-process* bsp)
1077      (dolist (pair initial-bindings)
1078        (save-binding (funcall (cdr pair)) (car pair) bsp))
1079      ;; These may (or may not) be the most recent special bindings.
1080      ;; If they are, just set the current tcr's db-link to point
1081      ;; to BSP; if not, "append" them to the end of the current
1082      ;; linked list.
1083      (let* ((current-db-link (%fixnum-ref (%current-tcr) target::tcr.db-link)))
1084        (declare (fixnum current-db-link))
1085        (if (zerop current-db-link)
1086          (setf (%fixnum-ref (%current-tcr) target::tcr.db-link) bsp)
1087          (do* ((binding current-db-link)
1088                (next (%fixnum-ref binding 0)
1089                      (%fixnum-ref binding 0)))
1090               ()
1091            (if (zerop next)
1092              (return (setf (%fixnum-ref binding 0) bsp))
1093              (setq binding next)))))
1094      ;; Ensure that pending unwind-protects (for WITHOUT-INTERRUPTS
1095      ;; on the callback) don't try to unwind the binding stack beyond
1096      ;; where it was just set.
1097      (do* ((catch (%fixnum-ref (%current-tcr) target::tcr.catch-top)
1098                   (%fixnum-ref catch target::catch-frame.link)))
1099           ((zerop catch))
1100        (declare (fixnum catch))
1101        (when (eql 0 (%fixnum-ref catch target::catch-frame.db-link))
1102          (setf (%fixnum-ref catch target::catch-frame.db-link) bsp)))))
1103  (let* ((thread (new-lisp-thread-from-tcr (%current-tcr) "foreign")))
1104    (setq *current-lisp-thread* thread
1105          *current-process*
[7948]1106          (make-process "foreign" :thread thread)
1107          *whostate* "Foreign thread callback")))
[4563]1108   
1109;;; Remove the foreign thread's lisp-thread and lisp process from
1110;;; the global lists.
1111(defun %foreign-thread-terminate ()
1112  (let* ((proc *current-process*))
1113    (when proc (remove-from-all-processes proc))))
Note: See TracBrowser for help on using the repository browser.