769f10da5490150cdfc2d2c13d0a891189243bb2
[sbcl.git] / src / runtime / x86-assem.S
1 /*
2  * very-low-level utilities for runtime support
3  */
4
5 /*
6  * This software is part of the SBCL system. See the README file for
7  * more information.
8  *
9  * This software is derived from the CMU CL system, which was
10  * written at Carnegie Mellon University and released into the
11  * public domain. The software is in the public domain and is
12  * provided with absolutely no warranty. See the COPYING and CREDITS
13  * files for more information.
14  */
15 \f
16 #define LANGUAGE_ASSEMBLY
17 #include "sbcl.h"
18 #include "validate.h"
19 #include "genesis/closure.h"
20 #include "genesis/funcallable-instance.h"
21 #include "genesis/fdefn.h"
22 #include "genesis/static-symbols.h"
23 #include "genesis/symbol.h"
24 #include "genesis/thread.h"
25         
26 /* Minimize conditionalization for different OS naming schemes. 
27  *
28  * (As of sbcl-0.8.10, this seems no longer to be much of an issue, 
29  * since everyone has converged on ELF. If this generality really 
30  * turns out not to matter, perhaps it's just clutter we could get
31  * rid of? -- WHN 2004-04-18)
32  *
33  * (Except Win32, which is unlikely ever to be ELF, sorry. -- AB 2005-12-08)
34  */
35 #if defined __linux__  || defined __FreeBSD__ || defined __NetBSD__ || defined __OpenBSD__ || defined __sun
36 #define GNAME(var) var
37 #else
38 #define GNAME(var) _##var
39 #endif
40
41 /* Get the right type of alignment. Linux, FreeBSD and NetBSD (but not OpenBSD)
42  * want alignment in bytes. 
43  *
44  * (As in the GNAME() definitions above, as of sbcl-0.8.10, this seems 
45  * no longer to be much of an issue, since everyone has converged on
46  * the same value. If this generality really turns out not to 
47  * matter any more, perhaps it's just clutter we could get
48  * rid of? -- WHN 2004-04-18)
49  */
50 #if defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__sun) || defined(LISP_FEATURE_WIN32)
51 #define align_4byte     4
52 #define align_8byte     8
53 #define align_16byte    16
54 #define align_page      4096
55 #else
56 #define align_4byte     2
57 #define align_8byte     3
58 #define align_16byte    4       
59 #define align_page      12
60 #endif                  
61
62 /*
63  * The assembler used for win32 doesn't like .type or .size directives,
64  * so we want to conditionally kill them out. So let's wrap them in macros
65  * that are defined to be no-ops on win32. Hopefully this still works on
66  * other platforms.
67  */
68 #if !defined(LISP_FEATURE_WIN32) && !defined(LISP_FEATURE_DARWIN)
69 #define TYPE(name) .type name,@function
70 #define SIZE(name) .size name,.-name
71 #else
72 #define TYPE(name)
73 #define SIZE(name)
74 #endif
75
76 /* Helper macros for access to thread-locals slots for both OS types:
77  * ------------------------------------------------------------------------
78  *
79  *                          Windows TEB block
80  * ==================        __________
81  * | Win32 %FS base | ---->  |        | 0
82  * ==================        |        | 1
83  *                           z        z
84  *     TLS slots start here> |XXXXXXXX| e10 = TEB_STATIC_TLS_SLOTS_OFFSET
85  *                           |XXXXXXXX| e11
86  *                           z   ...  z
87  *                           |XXXXXXXX| e4e
88  *     TLS ends here>     ,- |XXXXXXXX| e4f = TEB_STATIC_TLS_SLOTS_OFFSET+63
89  *                       /   z        z
90  *                       |   ----------
91  *                       |
92  *                       |   big blob of SBCL-specific thread-local data
93  *                       |     |----------------------------------------|
94  *                       |     |   CONTROL, BINDING, ALIEN STACK        |
95  *                       |     z                                        z
96  * ==================    |     |----------------------------------------|
97  * | Linux %FS base | -->|     |   FFI stack pointer                    |
98  * ==================    |     |    (extra page for mprotect)           |
99  *                        \    |----------------------------------------|
100  *   (union p_t_d) ----->  \-> | struct thread {   | dynamic_values[0]  |
101  *   .                         |   ...             |               [1]  |
102  *   .                         z   ...             z               ...  z
103  *   [tls data begins]         | }                 |               ...  | <-
104  *   [declared end of p_t_d]   |----------------------------------------| . |
105  *   .                         |                                   ...  | . |
106  *   .                         |                           [TLS_SIZE-1] | <-|
107  *   [tls data actually ends]  |----------------------------------------|   |
108  *   .                         | ALTSTACK                               |   |
109  *   .                         |----------------------------------------|   |
110  *   .                         | struct nonpointer_thread_data { }      |   |
111  *   .                         ------------------------------------------   |
112  *   [blob actually ends]                                                   |
113  *                                                                         /
114  *                                                                        /
115  *                                                                       /
116  *          ______________________                                      /
117  *          | struct symbol {    |                                     /
118  *          z   ...              z                                    /
119  *          |   fixnum tls_index;  // fixnum value relative to union /
120  *          | }                  |           (< TLS_SIZE = 4096)
121  *          ---------------------|
122  */
123 #ifdef LISP_FEATURE_WIN32
124 # define TEB_STATIC_TLS_SLOTS_OFFSET 0xE10
125 # define TEB_SBCL_THREAD_BASE_OFFSET (TEB_STATIC_TLS_SLOTS_OFFSET+(63*4))
126 # define SBCL_THREAD_BASE_EA %fs:TEB_SBCL_THREAD_BASE_OFFSET
127 # define MAYBE_FS(addr) addr
128 # define LoadTlSymbolValueAddress(symbol,reg) ;         \
129         movl    SBCL_THREAD_BASE_EA, reg ;              \
130         addl    (symbol+SYMBOL_TLS_INDEX_OFFSET), reg ;
131 # define LoadCurrentThreadSlot(offset,reg);     \
132         movl    SBCL_THREAD_BASE_EA, reg ;      \
133         movl    offset(reg), reg ;
134 #elif defined(LISP_FEATURE_LINUX) || defined(LISP_FEATURE_SUNOS)
135   /* see comment in arch_os_thread_init */
136 # define SBCL_THREAD_BASE_EA %fs:THREAD_SELFPTR_OFFSET
137 # define MAYBE_FS(addr) addr
138 #else
139   /* perhaps there's an OS out there that actually supports %fs without
140    * jumping through hoops, so just in case, here a default definition: */
141 # define SBCL_THREAD_BASE_EA $0
142 # define MAYBE_FS(addr) %fs:addr
143 #endif
144
145 /* gas can't parse 4096LU; redefine */
146 #if BACKEND_PAGE_BYTES == 4096
147 # undef BACKEND_PAGE_BYTES
148 # define BACKEND_PAGE_BYTES 4096
149 #elif BACKEND_PAGE_BYTES == 32768
150 # undef BACKEND_PAGE_BYTES
151 # define BACKEND_PAGE_BYTES 32768
152 #else
153 # error BACKEND_PAGE_BYTES mismatch
154 #endif
155
156 /* OAOOM because we don't have the C headers here */
157 #define THREAD_CSP_PAGE_SIZE BACKEND_PAGE_BYTES
158
159 /* the CSP page sits right before the thread */
160 #define THREAD_SAVED_CSP_OFFSET (-THREAD_CSP_PAGE_SIZE)
161
162 /*
163  * x86/darwin (as of MacOS X 10.4.5) doesn't reliably file signal
164  * handlers (SIGTRAP or Mach exception handlers) for 0xCC, wo we have
165  * to use ud2 instead. ud2 is an undefined opcode, #x0b0f, or
166  * 0F 0B in low-endian notation, that causes SIGILL to fire. We check
167  * for this instruction in the SIGILL handler and if we see it, we
168  * advance the EIP by two bytes to skip over ud2 instruction and
169  * call sigtrap_handler. */
170 #if defined(LISP_FEATURE_UD2_BREAKPOINTS)
171 #define END()
172 #define TRAP ud2
173 #else
174 #define END() .end
175 #define TRAP int3
176 #endif
177
178         .text
179         .globl  GNAME(all_threads)
180 \f
181 /*
182  * A call to call_into_c preserves esi, edi, and ebp.   
183  * (The C function will preserve ebx, esi, edi, and ebp across its
184  * function call, but we trash ebx ourselves by using it to save the
185  * return Lisp address.)
186  *
187  * Return values are in eax and maybe edx for quads, or st(0) for
188  * floats.
189  *
190  * This should work for Lisp calls C calls Lisp calls C..
191  *
192  * FIXME & OAOOM: This duplicates call-out in src/compiler/x86/c-call.lisp,
193  * so if you tweak this, change that too!
194  */
195 /*
196  * Note on sections specific to LISP_FEATURE_SB_SAFEPOINT:
197  *
198  * The code below is essential to safepoint-based garbage collection,
199  * and several details need to be considered for correct implementation.
200  *
201  * The stack spilling approach:
202  *   On SB-SAFEPOINT platforms, the CALL-OUT vop is defined to spill all
203  *   live Lisp TNs to the stack to provide information for conservative
204  *   GC cooperatively (avoiding the need to retrieve register values
205  *   from POSIX signal contexts or Windows GetThreadContext()).
206  *
207  * Finding the SP at all:
208  *   The main remaining value needed by GC is the stack pointer (SP) at
209  *   the moment of entering the foreign function.  For this purpose, a
210  *   thread-local field for the SP is used.  Two stores to that field
211  *   are done for each C call, one to save the SP before calling out and
212  *   and one to undo that store afterwards.
213  *
214  * Stores as synchronization points:
215  *   These two stores delimit the C call: While the SP is set, our
216  *   thread is known not to run Lisp code: During GC, memory protection
217  *   ensures that no thread proceeds across stores.
218  *
219  * The return PC issue:
220  *   (Note that CALL-OUT has, in principle, two versions: Inline
221  *   assembly in the VOP -or- alternatively the out-of-line version you
222  *   are currently reading.  In reality, safepoint builds currently
223  *   lack the inline code entirely.)
224  *
225  *   Both versions need to take special care with the return PC:
226  *   - In the inline version of the code (if it existed), the two stores
227  *     would be done directly in the CALL-OUT vop.  In that theoretical
228  *     implementation, there is a time interval between return of the
229  *     actual C call and a second SP store during which the return
230  *     address might not be on the stack anymore.
231  *   - In this out-of-line version, the stores are done during
232  *     call_into_c's frame, but an equivalent problem arises: In order
233  *     to present the stack of arguments as our foreign function expects
234  *     them, call_into_c has to pop the Lisp return address into a
235  *     register first; this register has to be preserved by GENCGC
236  *     separately: our return address is not in the stack anymore.
237  *   In both case, stack scanning alone is not sufficient to pin
238  *   the return address, and we communicate it to GC explicitly
239  *   in addition to the SP.
240  *
241  * Note on look-alike accessor macros with vastly different behaviour:
242  *   THREAD_PC_AROUND_FOREIGN_CALL_OFFSET is an "ordinary" field of the
243  *   struct thread, whereas THREAD_SAVED_CSP_OFFSET is a synchronization
244  *   point on a potentially write-protected page.
245 */
246
247         .text
248         .align  align_16byte,0x90
249         .globl GNAME(call_into_c)
250         TYPE(GNAME(call_into_c))
251 GNAME(call_into_c):
252 /* Save the return Lisp address in ebx. */
253         popl    %ebx
254
255 /* Setup the NPX for C */
256         /* The VOP says regarding CLD: "Clear out DF: Darwin, Windows,
257          * and Solaris at least require this, and it should not hurt
258          * others either." call_into_c didn't have it, but better safe than
259          * sorry. */
260         cld
261         fstp    %st(0)
262         fstp    %st(0)
263         fstp    %st(0)
264         fstp    %st(0)
265         fstp    %st(0)
266         fstp    %st(0)
267         fstp    %st(0)
268         fstp    %st(0)
269
270 #ifdef LISP_FEATURE_SB_SAFEPOINT
271         /* enter safe region: store SP and return PC */
272         movl    SBCL_THREAD_BASE_EA,%edi
273         movl    %esp,MAYBE_FS(THREAD_SAVED_CSP_OFFSET(%edi))
274         movl    %ebx,MAYBE_FS(THREAD_PC_AROUND_FOREIGN_CALL_OFFSET(%edi))
275 #endif
276
277         /* foreign call, preserving ESI, EDI, and EBX */
278         call    *%eax             # normal callout using Lisp stack
279         /* return values now in eax/edx OR st(0) */
280
281 #ifdef LISP_FEATURE_SB_SAFEPOINT
282         /* leave region: clear the SP!  (Also unpin the return PC.) */
283         xorl    %ecx,%ecx
284         movl    %ecx,MAYBE_FS(THREAD_SAVED_CSP_OFFSET(%edi))
285         movl    %ecx,MAYBE_FS(THREAD_PC_AROUND_FOREIGN_CALL_OFFSET(%edi))
286 #endif
287
288         movl    %eax,%ecx         # remember integer return value
289
290 /* Check for a return FP value. */
291         fxam
292         fnstsw  %ax
293         andl    $0x4500,%eax
294         cmpl    $0x4100,%eax
295         jne     Lfp_rtn_value
296
297 /* The return value is in eax, or eax,edx? */
298 /* Set up the NPX stack for Lisp. */
299         fldz                    # Ensure no regs are empty.
300         fldz
301         fldz
302         fldz
303         fldz
304         fldz
305         fldz
306         fldz
307
308 /* Restore the return value. */
309         movl    %ecx,%eax       # maybe return value
310
311 /* Return. */
312         jmp     *%ebx
313
314 Lfp_rtn_value:
315 /* The return result is in st(0). */
316 /* Set up the NPX stack for Lisp, placing the result in st(0). */
317         fldz                    # Ensure no regs are empty.
318         fldz
319         fldz
320         fldz
321         fldz
322         fldz
323         fldz
324         fxch    %st(7)          # Move the result back to st(0).
325
326 /* We don't need to restore eax, because the result is in st(0). */
327
328 /* Return. FIXME: It would be nice to restructure this to use RET. */
329         jmp     *%ebx
330
331         SIZE(GNAME(call_into_c))
332
333 \f
334         .text   
335         .globl GNAME(call_into_lisp_first_time)
336         TYPE(GNAME(call_into_lisp_first_time))
337                 
338 /* We don't worry too much about saving registers 
339  * here, because we never expect to return from the initial call to lisp 
340  * anyway */
341         
342         .align  align_16byte,0x90
343 GNAME(call_into_lisp_first_time):
344         pushl   %ebp            # Save old frame pointer.
345         movl    %esp,%ebp       # Establish new frame.
346 #ifndef LISP_FEATURE_WIN32
347         movl    GNAME(all_threads),%eax
348         /* pthread machinery takes care of this for other threads */
349         movl    THREAD_CONTROL_STACK_END_OFFSET(%eax) ,%esp
350 #else
351 /* Win32 -really- doesn't like you switching stacks out from under it. */
352         movl    GNAME(all_threads),%eax
353 #endif
354         jmp     Lstack
355 \f
356         .text   
357         .globl GNAME(call_into_lisp)
358         TYPE(GNAME(call_into_lisp))
359                 
360 /* The C conventions require that ebx, esi, edi, and ebp be preserved
361  * across function calls. */
362         
363         .align  align_16byte,0x90
364 GNAME(call_into_lisp):
365         pushl   %ebp            # Save old frame pointer.
366         movl    %esp,%ebp       # Establish new frame.
367
368 Lstack:
369 /* Save the NPX state */
370         fwait                   # Catch any pending NPX exceptions.
371         subl    $108,%esp       # Make room for the NPX state.
372         fnsave  (%esp)          # save and reset NPX
373
374         movl    (%esp),%eax     # Load NPX control word.
375         andl    $0xfffff2ff,%eax        # Set rounding mode to nearest.
376         orl     $0x00000200,%eax        # Set precision to 64 bits.  (53-bit mantissa)
377         pushl   %eax
378         fldcw   (%esp)          # Recover modes.
379         popl    %eax
380
381         fldz                    # Ensure no FP regs are empty.
382         fldz
383         fldz
384         fldz
385         fldz
386         fldz
387         fldz
388         fldz
389         
390 /* Save C regs: ebx esi edi. */
391         pushl   %ebx
392         pushl   %esi
393         pushl   %edi
394         
395 /* Clear descriptor regs. */
396         xorl    %eax,%eax       # lexenv
397         xorl    %ebx,%ebx       # available
398         xorl    %ecx,%ecx       # arg count
399         xorl    %edx,%edx       # first arg
400         xorl    %edi,%edi       # second arg
401         xorl    %esi,%esi       # third arg
402
403 /* no longer in function call */
404         movl    %esp,%ebx       # remember current stack
405         pushl   %ebx            # Save entry stack on (maybe) new stack.
406
407         /* Establish Lisp args. */
408         movl     8(%ebp),%eax   # lexenv?
409         movl    12(%ebp),%ebx   # address of arg vec
410         movl    16(%ebp),%ecx   # num args
411         shll    $2,%ecx         # Make num args into fixnum.
412         cmpl    $0,%ecx
413         je      Ldone
414         movl    (%ebx),%edx     # arg0
415         cmpl    $4,%ecx
416         je      Ldone
417         movl    4(%ebx),%edi    # arg1
418         cmpl    $8,%ecx
419         je      Ldone
420         movl    8(%ebx),%esi    # arg2
421 Ldone:  
422         /* Registers eax, ecx, edx, edi, and esi are now live. */
423
424 #ifdef LISP_FEATURE_WIN32
425         /* Establish an SEH frame. */
426 #ifdef LISP_FEATURE_SB_THREAD
427         /* FIXME: need to save BSP here. */
428 #error "need to save BSP here, but don't know how yet."
429 #else
430         pushl   BINDING_STACK_POINTER + SYMBOL_VALUE_OFFSET
431 #endif
432         pushl   $GNAME(exception_handler_wrapper)
433         pushl   %fs:0
434         movl    %esp, %fs:0
435 #endif
436
437         /* Alloc new frame. */
438         push    %ebp            # Dummy for return address
439         push    %ebp            # fp in save location S1
440         mov     %esp,%ebp       # The current sp marks start of new frame.
441         sub     $4,%esp         # Ensure 3 slots are allocated, two above.
442
443         call    *CLOSURE_FUN_OFFSET(%eax)
444         
445         /* If the function returned multiple values, it will return to
446            this point.  Lose them */
447         jnc     LsingleValue
448         mov     %ebx, %esp
449 LsingleValue:
450         /* A singled value function returns here */
451
452 #ifdef LISP_FEATURE_WIN32
453         /* Remove our SEH frame. */
454         popl    %fs:0
455         add     $8, %esp
456 #endif
457
458 /* Restore the stack, in case there was a stack change. */
459         popl    %esp            # c-sp
460
461 /* Restore C regs: ebx esi edi. */
462         popl    %edi
463         popl    %esi
464         popl    %ebx
465
466 /* Restore the NPX state. */
467         frstor  (%esp)
468         addl    $108, %esp
469         
470         popl    %ebp            # c-sp
471         movl    %edx,%eax       # c-val
472         ret
473         SIZE(GNAME(call_into_lisp))
474 \f
475 /* support for saving and restoring the NPX state from C */
476         .text
477         .globl  GNAME(fpu_save)
478         TYPE(GNAME(fpu_save))
479         .align  2,0x90
480 GNAME(fpu_save):
481         movl    4(%esp),%eax
482         fnsave  (%eax)          # Save the NPX state. (resets NPX)
483         ret
484         SIZE(GNAME(fpu_save))
485
486         .globl  GNAME(fpu_restore)
487         TYPE(GNAME(fpu_restore))
488         .align  2,0x90
489 GNAME(fpu_restore):
490         movl    4(%esp),%eax
491         frstor  (%eax)          # Restore the NPX state.
492         ret
493         SIZE(GNAME(fpu_restore))
494 \f
495 /*
496  * the undefined-function trampoline
497  */
498         .text
499         .align  align_16byte,0x90
500         .globl GNAME(undefined_tramp)
501         TYPE(GNAME(undefined_tramp))
502         .byte   0, 0, 0, SIMPLE_FUN_HEADER_WIDETAG
503 GNAME(undefined_tramp):
504         pop     4(%ebp)         # Save return PC for backtrace.
505         TRAP
506         .byte   trap_Error
507         .byte   2
508         .byte   UNDEFINED_FUN_ERROR
509         .byte   sc_DescriptorReg # eax in the Descriptor-reg SC
510         ret
511         SIZE(GNAME(undefined_tramp))
512
513 /* KLUDGE: FIND-ESCAPED-FRAME (SYS:SRC;CODE;DEBUG-INT.LISP) needs
514  * to know the name of the function immediately following the
515  * undefined-function trampoline. */
516
517 /*
518  * the closure trampoline
519  */
520         .text
521         .align  align_16byte,0x90
522         .globl GNAME(closure_tramp)
523         TYPE(GNAME(closure_tramp))
524         .byte   0, 0, 0, SIMPLE_FUN_HEADER_WIDETAG
525 GNAME(closure_tramp):
526         movl    FDEFN_FUN_OFFSET(%eax),%eax
527         /* FIXME: The '*' after "jmp" in the next line is from PVE's
528          * patch posted to the CMU CL mailing list Oct 6, 1999. It looks
529          * reasonable, and it certainly seems as though if CMU CL needs it,
530          * SBCL needs it too, but I haven't actually verified that it's
531          * right. It would be good to find a way to force the flow of
532          * control through here to test it. */
533         jmp     *CLOSURE_FUN_OFFSET(%eax)
534         SIZE(GNAME(closure_tramp))
535
536         .text
537         .align  align_16byte,0x90
538         .globl GNAME(funcallable_instance_tramp)
539         TYPE(GNAME(funcallable_instance_tramp))
540 GNAME(funcallable_instance_tramp):
541         movl    FUNCALLABLE_INSTANCE_FUNCTION_OFFSET(%eax),%eax 
542         /* KLUDGE: on this platform, whatever kind of function is in %rax
543          * now, the first word of it contains the address to jump to. */
544         jmp     *CLOSURE_FUN_OFFSET(%eax)
545         SIZE(GNAME(funcallable_instance_tramp))
546         
547 /*
548  * fun-end breakpoint magic
549  */
550
551 /*
552  * For an explanation of the magic involved in function-end
553  * breakpoints, see the implementation in ppc-assem.S.
554  */
555
556         .text
557         .globl  GNAME(fun_end_breakpoint_guts)
558         .align  align_16byte
559 GNAME(fun_end_breakpoint_guts):
560         /* Multiple Value return */
561         jc      multiple_value_return
562         /* Single value return: The eventual return will now use the
563            multiple values return convention but with a return values
564            count of one. */
565         movl    %esp,%ebx       # Setup ebx - the ofp.
566         subl    $4,%esp         # Allocate one stack slot for the return value
567         movl    $4,%ecx         # Setup ecx for one return value.
568         movl    $(NIL),%edi     # default second value
569         movl    $(NIL),%esi     # default third value
570                 
571 multiple_value_return:
572         
573         .globl GNAME(fun_end_breakpoint_trap)
574 GNAME(fun_end_breakpoint_trap):
575         TRAP
576         .byte   trap_FunEndBreakpoint
577         hlt                     # We should never return here.
578
579         .globl GNAME(fun_end_breakpoint_end)
580 GNAME(fun_end_breakpoint_end):
581
582 \f
583         .globl  GNAME(do_pending_interrupt)
584         TYPE(GNAME(do_pending_interrupt))
585         .align  align_16byte,0x90
586 GNAME(do_pending_interrupt):
587         TRAP
588         .byte   trap_PendingInterrupt
589         ret
590         SIZE(GNAME(do_pending_interrupt))
591 \f
592 /* Allocate bytes and return the start of the allocated space
593  * in the specified destination register.
594  *
595  * In the general case the size will be in the destination register.
596  *
597  * All registers must be preserved except the destination.
598  * The C conventions will preserve ebx, esi, edi, and ebp.
599  * So only eax, ecx, and edx need special care here.
600  *
601  * ALLOC factors out the logic of calling alloc(): stack alignment, etc.
602  *
603  * DEFINE_ALLOC_TO_FOO defines an alloction routine.
604  */
605
606 #ifdef LISP_FEATURE_DARWIN
607 #define ALLOC(size)                                             \
608         pushl   %ebp;              /* Save EBP               */ \
609         movl    %esp,%ebp;         /* Save ESP to EBP        */ \
610         pushl   $0;                /* Reserve space for arg  */ \
611         andl    $0xfffffff0,%esp;  /* Align stack to 16bytes */ \
612         movl    size, (%esp);      /* Argument to alloc      */ \
613         call    GNAME(alloc);                                   \
614         movl    %ebp,%esp;         /* Restore ESP from EBP   */ \
615         popl    %ebp;              /* Restore EBP            */
616 #else
617 #define ALLOC(size)                                             \
618         pushl   size;              /* Argument to alloc      */ \
619         call    GNAME(alloc);                                   \
620         addl    $4,%esp;           /* Pop argument           */
621 #endif
622
623 #define DEFINE_ALLOC_TO_EAX(name,size)                          \
624         .globl  GNAME(name);                                    \
625         TYPE(GNAME(name));                                      \
626         .align  align_16byte,0x90;                              \
627 GNAME(name):                                                    \
628         pushl   %ecx;              /* Save ECX and EDX       */ \
629         pushl   %edx;                                           \
630         ALLOC(size)                                             \
631         popl    %edx;              /* Restore ECX and EDX    */ \
632         popl    %ecx;                                           \
633         ret;                                                    \
634         SIZE(GNAME(name))
635
636 #define DEFINE_ALLOC_TO_ECX(name,size)                          \
637         .globl  GNAME(name);                                    \
638         TYPE(GNAME(name));                                      \
639         .align  align_16byte,0x90;                              \
640 GNAME(name):                                                    \
641         pushl   %eax;              /* Save EAX and EDX       */ \
642         pushl   %edx;                                           \
643         ALLOC(size)                                             \
644         movl    %eax,%ecx;         /* Result to destination  */ \
645         popl    %edx;                                           \
646         popl    %eax;                                           \
647         ret;                                                    \
648         SIZE(GNAME(name))
649         
650 #define DEFINE_ALLOC_TO_EDX(name,size)                          \
651         .globl  GNAME(name);                                    \
652         TYPE(GNAME(name));                                      \
653         .align  align_16byte,0x90;                              \
654 GNAME(name):                                                    \
655         pushl   %eax;               /* Save EAX and ECX      */ \
656         pushl   %ecx;                                           \
657         ALLOC(size)                                             \
658         movl    %eax,%edx;          /* Restore EAX and ECX   */ \
659         popl    %ecx;                                           \
660         popl    %eax;                                           \
661         ret;                                                    \
662         SIZE(GNAME(name))
663
664 #define DEFINE_ALLOC_TO_REG(name,reg,size)                      \
665         .globl  GNAME(name);                                    \
666         TYPE(GNAME(name));                                      \
667         .align  align_16byte,0x90;                              \
668 GNAME(name):                                                    \
669         pushl   %eax;              /* Save EAX, ECX, and EDX */ \
670         pushl   %ecx;                                           \
671         pushl   %edx;                                           \
672         ALLOC(size)                                             \
673         movl    %eax,reg;          /* Restore them           */ \
674         popl    %edx;                                           \
675         popl    %ecx;                                           \
676         popl    %eax;                                           \
677         ret;                                                    \
678         SIZE(GNAME(name))
679
680 DEFINE_ALLOC_TO_EAX(alloc_to_eax,%eax)
681 DEFINE_ALLOC_TO_EAX(alloc_8_to_eax,$8)
682 DEFINE_ALLOC_TO_EAX(alloc_16_to_eax,$16)
683
684 DEFINE_ALLOC_TO_ECX(alloc_to_ecx,%ecx)
685 DEFINE_ALLOC_TO_ECX(alloc_8_to_ecx,$8)
686 DEFINE_ALLOC_TO_ECX(alloc_16_to_ecx,$16)
687
688 DEFINE_ALLOC_TO_EDX(alloc_to_edx,%edx)
689 DEFINE_ALLOC_TO_EDX(alloc_8_to_edx,$8)
690 DEFINE_ALLOC_TO_EDX(alloc_16_to_edx,$16)
691
692 DEFINE_ALLOC_TO_REG(alloc_to_ebx,%ebx,%ebx)
693 DEFINE_ALLOC_TO_REG(alloc_8_to_ebx,%ebx,$8)
694 DEFINE_ALLOC_TO_REG(alloc_16_to_ebx,%ebx,$16)
695
696 DEFINE_ALLOC_TO_REG(alloc_to_esi,%esi,%esi)
697 DEFINE_ALLOC_TO_REG(alloc_8_to_esi,%esi,$8)
698 DEFINE_ALLOC_TO_REG(alloc_16_to_esi,%esi,$16)
699
700 DEFINE_ALLOC_TO_REG(alloc_to_edi,%edi,%edi)
701 DEFINE_ALLOC_TO_REG(alloc_8_to_edi,%edi,$8)
702 DEFINE_ALLOC_TO_REG(alloc_16_to_edi,%edi,$16)
703
704 /* Called from lisp when an inline allocation overflows.
705  * Every register except the result needs to be preserved.
706  * We depend on C to preserve ebx, esi, edi, and ebp.
707  * But where necessary must save eax, ecx, edx. */
708
709 #ifdef LISP_FEATURE_SB_THREAD
710 #define START_REGION %fs:THREAD_ALLOC_REGION_OFFSET
711 #else
712 #define START_REGION GNAME(boxed_region)
713 #endif
714
715 #define ALLOC_OVERFLOW(size)                                    \
716         /* Calculate the size for the allocation. */            \
717         subl    START_REGION,size;                              \
718         ALLOC(size)
719
720 /* This routine handles an overflow with eax=crfp+size. So the
721    size=eax-crfp. */
722         .align  align_16byte
723         .globl  GNAME(alloc_overflow_eax)
724         TYPE(GNAME(alloc_overflow_eax))
725 GNAME(alloc_overflow_eax):
726         pushl   %ecx            # Save ecx
727         pushl   %edx            # Save edx
728         ALLOC_OVERFLOW(%eax)
729         popl    %edx    # Restore edx.
730         popl    %ecx    # Restore ecx.
731         ret
732         SIZE(GNAME(alloc_overflow_eax))
733
734         .align  align_16byte
735         .globl  GNAME(alloc_overflow_ecx)
736         TYPE(GNAME(alloc_overflow_ecx))
737 GNAME(alloc_overflow_ecx):
738         pushl   %eax            # Save eax
739         pushl   %edx            # Save edx
740         ALLOC_OVERFLOW(%ecx)
741         movl    %eax,%ecx       # setup the destination.
742         popl    %edx    # Restore edx.
743         popl    %eax    # Restore eax.
744         ret
745         SIZE(GNAME(alloc_overflow_ecx))
746
747         .align  align_16byte
748         .globl  GNAME(alloc_overflow_edx)
749         TYPE(GNAME(alloc_overflow_edx))
750 GNAME(alloc_overflow_edx):
751         pushl   %eax            # Save eax
752         pushl   %ecx            # Save ecx
753         ALLOC_OVERFLOW(%edx)
754         movl    %eax,%edx       # setup the destination.
755         popl    %ecx    # Restore ecx.
756         popl    %eax    # Restore eax.
757         ret
758         SIZE(GNAME(alloc_overflow_edx))
759
760 /* This routine handles an overflow with ebx=crfp+size. So the
761    size=ebx-crfp. */
762         .align  align_16byte
763         .globl  GNAME(alloc_overflow_ebx)
764         TYPE(GNAME(alloc_overflow_ebx))
765 GNAME(alloc_overflow_ebx):
766         pushl   %eax            # Save eax
767         pushl   %ecx            # Save ecx
768         pushl   %edx            # Save edx
769         ALLOC_OVERFLOW(%ebx)
770         movl    %eax,%ebx       # setup the destination.
771         popl    %edx    # Restore edx.
772         popl    %ecx    # Restore ecx.
773         popl    %eax    # Restore eax.
774         ret
775         SIZE(GNAME(alloc_overflow_ebx))
776
777 /* This routine handles an overflow with esi=crfp+size. So the
778    size=esi-crfp. */
779         .align  align_16byte
780         .globl  GNAME(alloc_overflow_esi)
781         TYPE(GNAME(alloc_overflow_esi))
782 GNAME(alloc_overflow_esi):
783         pushl   %eax            # Save eax
784         pushl   %ecx            # Save ecx
785         pushl   %edx            # Save edx
786         ALLOC_OVERFLOW(%esi)
787         movl    %eax,%esi       # setup the destination.
788         popl    %edx    # Restore edx.
789         popl    %ecx    # Restore ecx.
790         popl    %eax    # Restore eax.
791         ret
792         SIZE(GNAME(alloc_overflow_esi))
793
794         .align  align_16byte
795         .globl  GNAME(alloc_overflow_edi)
796         TYPE(GNAME(alloc_overflow_edi))
797 GNAME(alloc_overflow_edi):
798         pushl   %eax            # Save eax
799         pushl   %ecx            # Save ecx
800         pushl   %edx            # Save edx
801         ALLOC_OVERFLOW(%edi)
802         movl    %eax,%edi       # setup the destination.
803         popl    %edx    # Restore edx.
804         popl    %ecx    # Restore ecx.
805         popl    %eax    # Restore eax.
806         ret
807         SIZE(GNAME(alloc_overflow_edi))
808
809
810 #ifdef LISP_FEATURE_WIN32
811         /* The guts of the exception-handling system doesn't use
812          * frame pointers, which manages to throw off backtraces
813          * rather badly.  So here we grab the (known-good) EBP
814          * and EIP from the exception context and use it to fake
815          * up a stack frame which will skip over the system SEH
816          * code. */
817         .align  align_16byte
818         .globl  GNAME(exception_handler_wrapper)
819         TYPE(GNAME(exception_handler_wrapper))
820 GNAME(exception_handler_wrapper):
821         /* Context layout is: */
822         /* 7 dwords before FSA. (0x1c) */
823         /* 8 dwords and 0x50 bytes in the FSA. (0x70/0x8c) */
824         /* 4 dwords segregs. (0x10/0x9c) */
825         /* 6 dwords non-stack GPRs. (0x18/0xb4) */
826         /* EBP (at 0xb4) */
827         /* EIP (at 0xb8) */
828 #define CONTEXT_EBP_OFFSET 0xb4
829 #define CONTEXT_EIP_OFFSET 0xb8
830         /* some other stuff we don't care about. */
831         pushl   %ebp
832         movl    0x10(%esp), %ebp        /* context */
833         pushl   CONTEXT_EIP_OFFSET(%ebp)
834         pushl   CONTEXT_EBP_OFFSET(%ebp)
835         movl    %esp, %ebp
836         pushl   0x1c(%esp)
837         pushl   0x1c(%esp)
838         pushl   0x1c(%esp)
839         pushl   0x1c(%esp)
840         call    GNAME(handle_exception)
841         lea     8(%ebp), %esp
842         popl    %ebp
843         ret
844         SIZE(GNAME(exception_handler_wrapper))
845 #endif
846
847 #ifdef LISP_FEATURE_DARWIN
848         .align align_16byte
849         .globl GNAME(call_into_lisp_tramp)
850         TYPE(GNAME(call_into_lisp_tramp))
851 GNAME(call_into_lisp_tramp):
852         /* 1. build the stack frame from the block that's pointed to by ECX
853            2. free the block
854            3. set ECX to 0
855            4. call the function via call_into_lisp
856         */
857         pushl   0(%ecx)          /* return address */
858
859         pushl   %ebp
860         movl    %esp, %ebp
861
862         pushl   32(%ecx)         /* eflags */
863         pushl   28(%ecx)         /* EAX */
864         pushl   20(%ecx)         /* ECX */
865         pushl   16(%ecx)         /* EDX */
866         pushl   24(%ecx)         /* EBX */
867         pushl   $0                /* popal is going to ignore esp */
868         pushl   %ebp              /* is this right?? */
869         pushl   12(%ecx)         /* ESI */
870         pushl   8(%ecx)          /* EDI */
871         pushl   $0                /* args for call_into_lisp */
872         pushl   $0
873         pushl   4(%ecx)          /* function to call */
874
875         /* free our save block */
876         pushl   %ecx              /* reserve sufficient space on stack for args */
877         pushl   %ecx
878         andl    $0xfffffff0, %esp  /* align stack */
879         movl    $0x40, 4(%esp)
880         movl    %ecx, (%esp)
881         call    GNAME(os_invalidate)
882
883         /* call call_into_lisp */
884         leal    -48(%ebp), %esp
885         call    GNAME(call_into_lisp)
886
887         /* Clean up our mess */
888         leal    -36(%ebp), %esp
889         popal
890         popfl
891         leave
892         ret
893         
894         SIZE(call_into_lisp_tramp)
895 #endif
896         
897         .align  align_16byte,0x90
898         .globl  GNAME(post_signal_tramp)
899         TYPE(GNAME(post_signal_tramp))
900 GNAME(post_signal_tramp):
901         /* this is notionally the second half of a function whose first half
902          * doesn't exist.  This is where call_into_lisp returns when called 
903          * using return_to_lisp_function */
904         addl $12,%esp   /* clear call_into_lisp args from stack */
905         popal           /* restore registers */
906         popfl
907 #ifdef LISP_FEATURE_DARWIN
908         /* skip two padding words */
909         addl $8,%esp
910 #endif
911         leave
912         ret
913         SIZE(GNAME(post_signal_tramp))
914
915
916         /* fast_bzero implementations and code to detect which implementation
917          * to use.
918          */
919 \f
920         .globl GNAME(fast_bzero_pointer)
921         .data
922         .align  align_16byte
923 GNAME(fast_bzero_pointer):
924         /* Variable containing a pointer to the bzero function to use.
925          * Initially points to a basic function.  Change this variable
926          * to fast_bzero_detect if OS supports SSE.  */
927         .long GNAME(fast_bzero_base)
928 \f
929         .globl GNAME(gc_safepoint_page)
930         .data
931         .align  align_page
932 GNAME(gc_safepoint_page):
933         .fill BACKEND_PAGE_BYTES,1,0
934 \f
935         .text
936         .align  align_16byte,0x90
937         .globl GNAME(fast_bzero)
938         TYPE(GNAME(fast_bzero))
939 GNAME(fast_bzero):        
940         /* Indirect function call */
941         jmp *GNAME(fast_bzero_pointer)
942         SIZE(GNAME(fast_bzero))
943         
944 \f      
945         .text
946         .align  align_16byte,0x90
947         .globl GNAME(fast_bzero_detect)
948         TYPE(GNAME(fast_bzero_detect))
949 GNAME(fast_bzero_detect):
950         /* Decide whether to use SSE, MMX or REP version */
951         push %eax /* CPUID uses EAX-EDX */
952         push %ebx
953         push %ecx
954         push %edx
955         mov $1, %eax
956         cpuid
957         test $0x04000000, %edx    /* SSE2 needed for MOVNTDQ */
958         jnz Lsse2
959         /* Originally there was another case here for using the
960          * MOVNTQ instruction for processors that supported MMX but
961          * not SSE2. This turned out to be a loss especially on
962          * Athlons (where this instruction is apparently microcoded
963          * somewhat slowly). So for simplicity revert to REP STOSL
964          * for all non-SSE2 processors.
965          */
966 Lbase:
967         movl $(GNAME(fast_bzero_base)), GNAME(fast_bzero_pointer)
968         jmp Lrestore
969 Lsse2:
970         movl $(GNAME(fast_bzero_sse)), GNAME(fast_bzero_pointer)
971         jmp Lrestore
972         
973 Lrestore:
974         pop %edx
975         pop %ecx
976         pop %ebx
977         pop %eax
978         jmp *GNAME(fast_bzero_pointer)
979         
980         SIZE(GNAME(fast_bzero_detect))
981         
982 \f
983         .text
984         .align  align_16byte,0x90
985         .globl GNAME(fast_bzero_sse)
986         TYPE(GNAME(fast_bzero_sse))
987         
988 GNAME(fast_bzero_sse):
989         /* A fast routine for zero-filling blocks of memory that are
990          * guaranteed to start and end at a 4096-byte aligned address.
991          */        
992         push %esi                 /* Save temporary registers */
993         push %edi
994         mov 16(%esp), %esi        /* Parameter: amount of bytes to fill */
995         mov 12(%esp), %edi        /* Parameter: start address */
996         shr $6, %esi              /* Amount of 64-byte blocks to copy */
997         jz Lend_sse               /* If none, stop */
998         movups %xmm7, -16(%esp)   /* Save XMM register */
999         xorps  %xmm7, %xmm7       /* Zero the XMM register */
1000         jmp Lloop_sse
1001         .align align_16byte
1002 Lloop_sse:
1003
1004         /* Copy the 16 zeroes from xmm7 to memory, 4 times. MOVNTDQ is the
1005          * non-caching double-quadword moving variant, i.e. the memory areas
1006          * we're touching are not fetched into the L1 cache, since we're just
1007          * going to overwrite the memory soon anyway.
1008          */
1009         movntdq %xmm7, 0(%edi)
1010         movntdq %xmm7, 16(%edi)
1011         movntdq %xmm7, 32(%edi)
1012         movntdq %xmm7, 48(%edi)
1013  
1014         add $64, %edi /* Advance pointer */
1015         dec %esi      /* Decrement 64-byte block count */
1016         jnz Lloop_sse
1017         movups -16(%esp), %xmm7 /* Restore the XMM register */
1018         sfence        /* Ensure that weakly ordered writes are flushed. */
1019 Lend_sse:
1020         mov 12(%esp), %esi      /* Parameter: start address */
1021         prefetcht0 0(%esi)      /* Prefetch the start of the block into cache,
1022                                  * since it's likely to be used immediately. */
1023         pop %edi      /* Restore temp registers */
1024         pop %esi
1025         ret
1026         SIZE(GNAME(fast_bzero_sse))
1027                 
1028 \f
1029         .text
1030         .align  align_16byte,0x90
1031         .globl GNAME(fast_bzero_base)
1032         TYPE(GNAME(fast_bzero_base))
1033         
1034 GNAME(fast_bzero_base):
1035         /* A fast routine for zero-filling blocks of memory that are
1036          * guaranteed to start and end at a 4096-byte aligned address.
1037          */        
1038         push %eax                 /* Save temporary registers */
1039         push %ecx
1040         push %edi
1041         mov 20(%esp), %ecx        /* Parameter: amount of bytes to fill */
1042         mov 16(%esp), %edi        /* Parameter: start address */
1043         xor %eax, %eax            /* Zero EAX */
1044         shr $2, %ecx              /* Amount of 4-byte blocks to copy */
1045         jz  Lend_base
1046
1047         rep
1048         stosl                     /* Store EAX to *EDI, ECX times, incrementing
1049                                    * EDI by 4 after each store */
1050         
1051 Lend_base:        
1052         pop %edi                  /* Restore temp registers */
1053         pop %ecx
1054         pop %eax
1055         ret
1056         SIZE(GNAME(fast_bzero_base))
1057
1058 \f
1059 /* When LISP_FEATURE_C_STACK_IS_CONTROL_STACK, we cannot safely scrub
1060  * the control stack from C, largely due to not knowing where the
1061  * active stack frame ends.  On such platforms, we reimplement the
1062  * core scrubbing logic in assembly, in this case here:
1063  */
1064         .text
1065         .align  align_16byte,0x90
1066         .globl GNAME(arch_scrub_control_stack)
1067         TYPE(GNAME(arch_scrub_control_stack))
1068 GNAME(arch_scrub_control_stack):
1069         /* We are passed three parameters:
1070          * A (struct thread *) at [ESP+4],
1071          * the address of the guard page at [ESP+8], and
1072          * the address of the hard guard page at [ESP+12].
1073          * We may trash EAX, ECX, and EDX with impunity.
1074          * [ESP] is our return address, [ESP-4] is the first
1075          * stack slot to scrub. */
1076
1077         /* We start by setting up our scrub pointer in EAX, our
1078          * guard page upper bound in ECX, and our hard guard
1079          * page upper bound in EDX. */
1080         lea     -4(%esp), %eax
1081         mov     GNAME(os_vm_page_size),%edx
1082         mov     %edx, %ecx
1083         add     8(%esp), %ecx
1084         add     12(%esp), %edx
1085
1086         /* We need to do a memory operation relative to the
1087          * thread pointer, so put it in %ecx and our guard
1088          * page upper bound in 4(%esp). */
1089         xchg    4(%esp), %ecx
1090
1091         /* Now we begin our main scrub loop. */
1092 ascs_outer_loop:
1093
1094         /* If we're about to scrub the hard guard page, exit. */
1095         cmp     %edx, %eax
1096         jae     ascs_check_guard_page
1097         cmp     12(%esp), %eax
1098         ja      ascs_finished
1099
1100 ascs_check_guard_page:
1101         /* If we're about to scrub the guard page, and the guard
1102          * page is protected, exit. */
1103         cmp     4(%esp), %eax
1104         jae     ascs_clear_loop
1105         cmp     8(%esp), %eax
1106         jbe     ascs_clear_loop
1107         cmpl    $(NIL), THREAD_CONTROL_STACK_GUARD_PAGE_PROTECTED_OFFSET(%ecx)
1108         jne     ascs_finished
1109
1110         /* Clear memory backwards to the start of the (4KiB) page */
1111 ascs_clear_loop:
1112         movl    $0, (%eax)
1113         test    $0xfff, %eax
1114         lea     -4(%eax), %eax
1115         jnz     ascs_clear_loop
1116
1117         /* If we're about to hit the hard guard page, exit. */
1118         cmp     %edx, %eax
1119         jae     ascs_finished
1120
1121         /* If the next (previous?) 4KiB page contains a non-zero
1122          * word, continue scrubbing. */
1123 ascs_check_loop:
1124         testl   $-1, (%eax)
1125         jnz     ascs_outer_loop
1126         test    $0xfff, %eax
1127         lea     -4(%eax), %eax
1128         jnz     ascs_check_loop
1129
1130 ascs_finished:
1131         ret
1132         SIZE(GNAME(arch_scrub_control_stack))
1133 \f
1134         END()