97a147b717cec8dddef6284da01060f5af104b6c
[sbcl.git] / src / code / deadline.lisp
1 ;;;; global deadlines for blocking functions: a threadsafe alternative
2 ;;;; to asynch timeouts
3
4 ;;;; This software is part of the SBCL system. See the README file for
5 ;;;; more information.
6 ;;;;
7 ;;;; This software is derived from the CMU CL system, which was
8 ;;;; written at Carnegie Mellon University and released into the
9 ;;;; public domain. The software is in the public domain and is
10 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
11 ;;;; files for more information.
12
13 (in-package "SB!IMPL")
14
15 ;;; Current deadline as internal time units or NIL.
16 (defvar *deadline* nil)
17 (declaim (type (or unsigned-byte null) *deadline*))
18
19 ;;; The relative number of seconds the current deadline corresponds
20 ;;; to. Used for continuing from TIMEOUT conditions.
21 (defvar *deadline-seconds* nil)
22
23 (declaim (inline seconds-to-internal-time))
24 (defun seconds-to-internal-time (seconds)
25   (truncate (* seconds sb!xc:internal-time-units-per-second)))
26
27 (defmacro with-deadline ((&key seconds override)
28                          &body body)
29   "Arranges for a TIMEOUT condition to be signalled if an operation
30 respecting deadlines occurs either after the deadline has passed, or
31 would take longer than the time left to complete.
32
33 Currently only blocking IO operations, GET-MUTEX, and CONDITION-WAIT
34 respect deadlines, but this includes their implicit uses inside SBCL
35 itself.
36
37 Unless OVERRIDE is true, existing deadlines can only be restricted,
38 not extended. Deadlines are per thread: children are unaffected by
39 their parent's deadlines.
40
41 Experimental."
42   (with-unique-names (deadline-seconds deadline)
43     ;; We're operating on a millisecond precision, so a single-float
44     ;; is enough, and is an immediate on 64bit platforms.
45     `(let* ((,deadline-seconds (coerce ,seconds 'single-float))
46             (,deadline
47              (+ (seconds-to-internal-time ,deadline-seconds)
48                 (get-internal-real-time))))
49        (multiple-value-bind (*deadline* *deadline-seconds*)
50            (if ,override
51                (values ,deadline ,deadline-seconds)
52                (let ((old *deadline*))
53                  (if (and old (< old ,deadline))
54                      (values old *deadline-seconds*)
55                      (values ,deadline ,deadline-seconds))))
56          ,@body))))
57
58 (declaim (inline decode-internal-time))
59 (defun decode-internal-time (time)
60   #!+sb-doc
61   "Returns internal time value TIME decoded into seconds and microseconds."
62   (multiple-value-bind (sec frac)
63       (truncate time sb!xc:internal-time-units-per-second)
64     (values sec (* frac sb!unix::micro-seconds-per-internal-time-unit))))
65
66 (defun signal-timeout (datum &rest arguments)
67   #!+sb-doc
68   "Signals a timeout condition while inhibiting further timeouts due to
69 deadlines while the condition is being handled."
70   ;; FIXME: Maybe we should make ERROR do WITH-INTERRUPTS instead of
71   ;; putting it all over the place (now that we have ALLOW-WITH-INTERRUPTS.)
72   (with-interrupts
73     ;; Don't signal a deadline while handling a non-deadline timeout.
74     (let ((*deadline* nil))
75       (apply #'error datum arguments))))
76
77 (defun signal-deadline ()
78   #!+sb-doc
79   "Signal a DEADLINE-TIMEOUT condition, and associate a DEFER-DEADLINE
80 restart with it. Implementors of blocking functions are responsible
81 for calling this when a deadline is reached."
82   ;; Make sure we don't signal the same deadline twice. LET is not good
83   ;; enough: we might catch the same deadline again while unwinding.
84   (when *deadline*
85     (setf *deadline* nil))
86   (with-interrupts
87     (restart-case
88         (error 'deadline-timeout :seconds *deadline-seconds*)
89       (defer-deadline (&optional (seconds *deadline-seconds*))
90         :report "Defer the deadline for SECONDS more."
91         :interactive (lambda ()
92                        (sb!int:read-evaluated-form
93                         "By how many seconds shall the deadline ~
94                          be deferred?: "))
95         (let* ((new-deadline-seconds (coerce seconds 'single-float))
96                (new-deadline (+ (seconds-to-internal-time new-deadline-seconds)
97                                 (get-internal-real-time))))
98           (setf *deadline* new-deadline
99                 *deadline-seconds* new-deadline-seconds)))
100       (cancel-deadline ()
101         :report "Cancel the deadline and continue."
102         (setf *deadline* nil *deadline-seconds* nil))))
103   nil)
104
105 (defun defer-deadline (seconds &optional condition)
106   "Find the DEFER-DEADLINE restart associated with CONDITION, and
107 invoke it with SECONDS as argument (deferring the deadline by that many
108 seconds.) Otherwise return NIL if the restart is not found."
109   (try-restart 'defer-deadline condition seconds))
110
111 (defun cancel-deadline (&optional condition)
112   "Find and invoke the CANCEL-DEADLINE restart associated with
113 CONDITION, or return NIL if the restart is not found."
114   (try-restart 'cancel-deadline condition))
115
116 ;;; Returns TIMEOUT-SEC, TIMEOUT-USEC, DEADLINE-SEC, DEADLINE-USEC, SIGNALP
117 ;;;
118 ;;; Takes *DEADLINE* into account: if it occurs before given SECONDS,
119 ;;; the values are based on it, and DEADLINEP is true -- and the
120 ;;; receipent of the values should call SIGNAL-TIMEOUT if the decoded
121 ;;; timeout is reached.
122 ;;;
123 ;;; If SECONDS is NIL and there is no *DEADLINE* all returned values
124 ;;; are NIL.
125 (defun decode-timeout (seconds)
126   #!+sb-doc
127   "Decodes a relative timeout in SECONDS into five values, taking any
128 global deadlines into account: TO-SEC, TO-USEC, STOP-SEC, STOP-USEC,
129 DEADLINEP.
130
131 TO-SEC and TO-USEC indicate the relative timeout in seconds and microsconds.
132 STOP-SEC and STOP-USEC indicate the absolute timeout in seconds and
133 microseconds. DEADLINEP is true if the returned values reflect a global
134 deadline instead of the local timeout indicated by SECONDS.
135
136 If SECONDS is null and there is no global timeout all returned values will be
137 null. If a global deadline has already passed when DECODE-TIMEOUT is called,
138 it will signal a timeout condition."
139   (tagbody
140    :restart
141      (let* ((timeout (when seconds (seconds-to-internal-time seconds)))
142             (now (get-internal-real-time))
143             (deadline *deadline*)
144             (deadline-timeout
145              (when deadline
146                (let ((time-left (- deadline now)))
147                  (if (plusp time-left)
148                      time-left
149                      (progn
150                        (signal-deadline)
151                        (go :restart)))))))
152        (return-from decode-timeout
153          (multiple-value-bind (final-timeout final-deadline signalp)
154              ;; Use either *DEADLINE* or TIMEOUT to produce both a timeout
155              ;; and deadline in internal-time units
156              (cond ((and deadline timeout)
157                     (if (< timeout deadline-timeout)
158                         (values timeout (+ timeout now) nil)
159                         (values deadline-timeout deadline t)))
160                    (deadline
161                     (values deadline-timeout deadline t))
162                    (timeout
163                     (values timeout (+ timeout now) nil))
164                    (t
165                     (values nil nil nil)))
166            (if final-timeout
167                (multiple-value-bind (to-sec to-usec)
168                    (decode-internal-time final-timeout)
169                  (multiple-value-bind (stop-sec stop-usec)
170                      (decode-internal-time final-deadline)
171                    (values to-sec to-usec stop-sec stop-usec signalp)))
172                (values nil nil nil nil nil)))))))
173