process.cc revision 11850:36119fa7874d
1/*
2 * Copyright (c) 2003-2004 The Regents of The University of Michigan
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met: redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer;
9 * redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution;
12 * neither the name of the copyright holders nor the names of its
13 * contributors may be used to endorse or promote products derived from
14 * this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 *
28 * Authors: Gabe Black
29 *          Ali Saidi
30 */
31
32#include "arch/sparc/process.hh"
33
34#include "arch/sparc/asi.hh"
35#include "arch/sparc/handlers.hh"
36#include "arch/sparc/isa_traits.hh"
37#include "arch/sparc/registers.hh"
38#include "arch/sparc/types.hh"
39#include "base/loader/elf_object.hh"
40#include "base/loader/object_file.hh"
41#include "base/misc.hh"
42#include "cpu/thread_context.hh"
43#include "debug/Stack.hh"
44#include "mem/page_table.hh"
45#include "sim/process_impl.hh"
46#include "sim/syscall_return.hh"
47#include "sim/system.hh"
48
49using namespace std;
50using namespace SparcISA;
51
52static const int FirstArgumentReg = 8;
53
54
55SparcLiveProcess::SparcLiveProcess(LiveProcessParams * params,
56        ObjectFile *objFile, Addr _StackBias)
57    : LiveProcess(params, objFile), StackBias(_StackBias)
58{
59
60    // XXX all the below need to be updated for SPARC - Ali
61    brk_point = objFile->dataBase() + objFile->dataSize() + objFile->bssSize();
62    brk_point = roundUp(brk_point, PageBytes);
63
64    // Set pointer for next thread stack.  Reserve 8M for main stack.
65    next_thread_stack_base = stack_base - (8 * 1024 * 1024);
66
67    // Initialize these to 0s
68    fillStart = 0;
69    spillStart = 0;
70}
71
72void
73SparcLiveProcess::handleTrap(int trapNum, ThreadContext *tc)
74{
75    PCState pc = tc->pcState();
76    switch (trapNum) {
77      case 0x01: // Software breakpoint
78        warn("Software breakpoint encountered at pc %#x.\n", pc.pc());
79        break;
80      case 0x02: // Division by zero
81        warn("Software signaled a division by zero at pc %#x.\n", pc.pc());
82        break;
83      case 0x03: // Flush window trap
84        flushWindows(tc);
85        break;
86      case 0x04: // Clean windows
87        warn("Ignoring process request for clean register "
88                "windows at pc %#x.\n", pc.pc());
89        break;
90      case 0x05: // Range check
91        warn("Software signaled a range check at pc %#x.\n", pc.pc());
92        break;
93      case 0x06: // Fix alignment
94        warn("Ignoring process request for os assisted unaligned accesses "
95                "at pc %#x.\n", pc.pc());
96        break;
97      case 0x07: // Integer overflow
98        warn("Software signaled an integer overflow at pc %#x.\n", pc.pc());
99        break;
100      case 0x32: // Get integer condition codes
101        warn("Ignoring process request to get the integer condition codes "
102                "at pc %#x.\n", pc.pc());
103        break;
104      case 0x33: // Set integer condition codes
105        warn("Ignoring process request to set the integer condition codes "
106                "at pc %#x.\n", pc.pc());
107        break;
108      default:
109        panic("Unimplemented trap to operating system: trap number %#x.\n", trapNum);
110    }
111}
112
113void
114SparcLiveProcess::initState()
115{
116    LiveProcess::initState();
117
118    ThreadContext *tc = system->getThreadContext(contextIds[0]);
119    // From the SPARC ABI
120
121    // Setup default FP state
122    tc->setMiscRegNoEffect(MISCREG_FSR, 0);
123
124    tc->setMiscRegNoEffect(MISCREG_TICK, 0);
125
126    /*
127     * Register window management registers
128     */
129
130    // No windows contain info from other programs
131    // tc->setMiscRegNoEffect(MISCREG_OTHERWIN, 0);
132    tc->setIntReg(NumIntArchRegs + 6, 0);
133    // There are no windows to pop
134    // tc->setMiscRegNoEffect(MISCREG_CANRESTORE, 0);
135    tc->setIntReg(NumIntArchRegs + 4, 0);
136    // All windows are available to save into
137    // tc->setMiscRegNoEffect(MISCREG_CANSAVE, NWindows - 2);
138    tc->setIntReg(NumIntArchRegs + 3, NWindows - 2);
139    // All windows are "clean"
140    // tc->setMiscRegNoEffect(MISCREG_CLEANWIN, NWindows);
141    tc->setIntReg(NumIntArchRegs + 5, NWindows);
142    // Start with register window 0
143    tc->setMiscReg(MISCREG_CWP, 0);
144    // Always use spill and fill traps 0
145    // tc->setMiscRegNoEffect(MISCREG_WSTATE, 0);
146    tc->setIntReg(NumIntArchRegs + 7, 0);
147    // Set the trap level to 0
148    tc->setMiscRegNoEffect(MISCREG_TL, 0);
149    // Set the ASI register to something fixed
150    tc->setMiscReg(MISCREG_ASI, ASI_PRIMARY);
151
152    // Set the MMU Primary Context Register to hold the process' pid
153    tc->setMiscReg(MISCREG_MMU_P_CONTEXT, _pid);
154
155    /*
156     * T1 specific registers
157     */
158    // Turn on the icache, dcache, dtb translation, and itb translation.
159    tc->setMiscRegNoEffect(MISCREG_MMU_LSU_CTRL, 15);
160}
161
162void
163Sparc32LiveProcess::initState()
164{
165    SparcLiveProcess::initState();
166
167    ThreadContext *tc = system->getThreadContext(contextIds[0]);
168    // The process runs in user mode with 32 bit addresses
169    PSTATE pstate = 0;
170    pstate.ie = 1;
171    pstate.am = 1;
172    tc->setMiscReg(MISCREG_PSTATE, pstate);
173
174    argsInit(32 / 8, PageBytes);
175}
176
177void
178Sparc64LiveProcess::initState()
179{
180    SparcLiveProcess::initState();
181
182    ThreadContext *tc = system->getThreadContext(contextIds[0]);
183    // The process runs in user mode
184    PSTATE pstate = 0;
185    pstate.ie = 1;
186    tc->setMiscReg(MISCREG_PSTATE, pstate);
187
188    argsInit(sizeof(IntReg), PageBytes);
189}
190
191template<class IntType>
192void
193SparcLiveProcess::argsInit(int pageSize)
194{
195    int intSize = sizeof(IntType);
196
197    typedef AuxVector<IntType> auxv_t;
198
199    std::vector<auxv_t> auxv;
200
201    string filename;
202    if (argv.size() < 1)
203        filename = "";
204    else
205        filename = argv[0];
206
207    // Even for a 32 bit process, the ABI says we still need to
208    // maintain double word alignment of the stack pointer.
209    uint64_t align = 16;
210
211    // Patch the ld_bias for dynamic executables.
212    updateBias();
213
214    // load object file into target memory
215    objFile->loadSections(initVirtMem);
216
217    enum hardwareCaps
218    {
219        M5_HWCAP_SPARC_FLUSH = 1,
220        M5_HWCAP_SPARC_STBAR = 2,
221        M5_HWCAP_SPARC_SWAP = 4,
222        M5_HWCAP_SPARC_MULDIV = 8,
223        M5_HWCAP_SPARC_V9 = 16,
224        // This one should technically only be set
225        // if there is a cheetah or cheetah_plus tlb,
226        // but we'll use it all the time
227        M5_HWCAP_SPARC_ULTRA3 = 32
228    };
229
230    const int64_t hwcap =
231        M5_HWCAP_SPARC_FLUSH |
232        M5_HWCAP_SPARC_STBAR |
233        M5_HWCAP_SPARC_SWAP |
234        M5_HWCAP_SPARC_MULDIV |
235        M5_HWCAP_SPARC_V9 |
236        M5_HWCAP_SPARC_ULTRA3;
237
238    // Setup the auxilliary vectors. These will already have endian conversion.
239    // Auxilliary vectors are loaded only for elf formatted executables.
240    ElfObject * elfObject = dynamic_cast<ElfObject *>(objFile);
241    if (elfObject) {
242        // Bits which describe the system hardware capabilities
243        auxv.push_back(auxv_t(M5_AT_HWCAP, hwcap));
244        // The system page size
245        auxv.push_back(auxv_t(M5_AT_PAGESZ, SparcISA::PageBytes));
246        // Defined to be 100 in the kernel source.
247        // Frequency at which times() increments
248        auxv.push_back(auxv_t(M5_AT_CLKTCK, 100));
249        // For statically linked executables, this is the virtual address of the
250        // program header tables if they appear in the executable image
251        auxv.push_back(auxv_t(M5_AT_PHDR, elfObject->programHeaderTable()));
252        // This is the size of a program header entry from the elf file.
253        auxv.push_back(auxv_t(M5_AT_PHENT, elfObject->programHeaderSize()));
254        // This is the number of program headers from the original elf file.
255        auxv.push_back(auxv_t(M5_AT_PHNUM, elfObject->programHeaderCount()));
256        // This is the base address of the ELF interpreter; it should be
257        // zero for static executables or contain the base address for
258        // dynamic executables.
259        auxv.push_back(auxv_t(M5_AT_BASE, getBias()));
260        // This is hardwired to 0 in the elf loading code in the kernel
261        auxv.push_back(auxv_t(M5_AT_FLAGS, 0));
262        // The entry point to the program
263        auxv.push_back(auxv_t(M5_AT_ENTRY, objFile->entryPoint()));
264        // Different user and group IDs
265        auxv.push_back(auxv_t(M5_AT_UID, uid()));
266        auxv.push_back(auxv_t(M5_AT_EUID, euid()));
267        auxv.push_back(auxv_t(M5_AT_GID, gid()));
268        auxv.push_back(auxv_t(M5_AT_EGID, egid()));
269        // Whether to enable "secure mode" in the executable
270        auxv.push_back(auxv_t(M5_AT_SECURE, 0));
271    }
272
273    // Figure out how big the initial stack needs to be
274
275    // The unaccounted for 8 byte 0 at the top of the stack
276    int sentry_size = 8;
277
278    // This is the name of the file which is present on the initial stack
279    // It's purpose is to let the user space linker examine the original file.
280    int file_name_size = filename.size() + 1;
281
282    int env_data_size = 0;
283    for (int i = 0; i < envp.size(); ++i) {
284        env_data_size += envp[i].size() + 1;
285    }
286    int arg_data_size = 0;
287    for (int i = 0; i < argv.size(); ++i) {
288        arg_data_size += argv[i].size() + 1;
289    }
290
291    // The info_block.
292    int base_info_block_size =
293        sentry_size + file_name_size + env_data_size + arg_data_size;
294
295    int info_block_size = roundUp(base_info_block_size, align);
296
297    int info_block_padding = info_block_size - base_info_block_size;
298
299    // Each auxilliary vector is two words
300    int aux_array_size = intSize * 2 * (auxv.size() + 1);
301
302    int envp_array_size = intSize * (envp.size() + 1);
303    int argv_array_size = intSize * (argv.size() + 1);
304
305    int argc_size = intSize;
306    int window_save_size = intSize * 16;
307
308    // Figure out the size of the contents of the actual initial frame
309    int frame_size =
310        aux_array_size +
311        envp_array_size +
312        argv_array_size +
313        argc_size +
314        window_save_size;
315
316    // There needs to be padding after the auxiliary vector data so that the
317    // very bottom of the stack is aligned properly.
318    int aligned_partial_size = roundUp(frame_size, align);
319    int aux_padding = aligned_partial_size - frame_size;
320
321    int space_needed =
322        info_block_size +
323        aux_padding +
324        frame_size;
325
326    stack_min = stack_base - space_needed;
327    stack_min = roundDown(stack_min, align);
328    stack_size = stack_base - stack_min;
329
330    // Allocate space for the stack
331    allocateMem(roundDown(stack_min, pageSize), roundUp(stack_size, pageSize));
332
333    // map out initial stack contents
334    IntType sentry_base = stack_base - sentry_size;
335    IntType file_name_base = sentry_base - file_name_size;
336    IntType env_data_base = file_name_base - env_data_size;
337    IntType arg_data_base = env_data_base - arg_data_size;
338    IntType auxv_array_base = arg_data_base -
339        info_block_padding - aux_array_size - aux_padding;
340    IntType envp_array_base = auxv_array_base - envp_array_size;
341    IntType argv_array_base = envp_array_base - argv_array_size;
342    IntType argc_base = argv_array_base - argc_size;
343#if TRACING_ON
344    IntType window_save_base = argc_base - window_save_size;
345#endif
346
347    DPRINTF(Stack, "The addresses of items on the initial stack:\n");
348    DPRINTF(Stack, "%#x - sentry NULL\n", sentry_base);
349    DPRINTF(Stack, "filename = %s\n", filename);
350    DPRINTF(Stack, "%#x - file name\n", file_name_base);
351    DPRINTF(Stack, "%#x - env data\n", env_data_base);
352    DPRINTF(Stack, "%#x - arg data\n", arg_data_base);
353    DPRINTF(Stack, "%#x - auxv array\n", auxv_array_base);
354    DPRINTF(Stack, "%#x - envp array\n", envp_array_base);
355    DPRINTF(Stack, "%#x - argv array\n", argv_array_base);
356    DPRINTF(Stack, "%#x - argc \n", argc_base);
357    DPRINTF(Stack, "%#x - window save\n", window_save_base);
358    DPRINTF(Stack, "%#x - stack min\n", stack_min);
359
360    assert(window_save_base == stack_min);
361
362    // write contents to stack
363
364    // figure out argc
365    IntType argc = argv.size();
366    IntType guestArgc = SparcISA::htog(argc);
367
368    // Write out the sentry void *
369    uint64_t sentry_NULL = 0;
370    initVirtMem.writeBlob(sentry_base,
371            (uint8_t*)&sentry_NULL, sentry_size);
372
373    // Write the file name
374    initVirtMem.writeString(file_name_base, filename.c_str());
375
376    // Copy the aux stuff
377    for (int x = 0; x < auxv.size(); x++) {
378        initVirtMem.writeBlob(auxv_array_base + x * 2 * intSize,
379                (uint8_t*)&(auxv[x].a_type), intSize);
380        initVirtMem.writeBlob(auxv_array_base + (x * 2 + 1) * intSize,
381                (uint8_t*)&(auxv[x].a_val), intSize);
382    }
383
384    // Write out the terminating zeroed auxilliary vector
385    const IntType zero = 0;
386    initVirtMem.writeBlob(auxv_array_base + intSize * 2 * auxv.size(),
387            (uint8_t*)&zero, intSize);
388    initVirtMem.writeBlob(auxv_array_base + intSize * (2 * auxv.size() + 1),
389            (uint8_t*)&zero, intSize);
390
391    copyStringArray(envp, envp_array_base, env_data_base, initVirtMem);
392    copyStringArray(argv, argv_array_base, arg_data_base, initVirtMem);
393
394    initVirtMem.writeBlob(argc_base, (uint8_t*)&guestArgc, intSize);
395
396    // Set up space for the trap handlers into the processes address space.
397    // Since the stack grows down and there is reserved address space abov
398    // it, we can put stuff above it and stay out of the way.
399    fillStart = stack_base;
400    spillStart = fillStart + sizeof(MachInst) * numFillInsts;
401
402    ThreadContext *tc = system->getThreadContext(contextIds[0]);
403    // Set up the thread context to start running the process
404    // assert(NumArgumentRegs >= 2);
405    // tc->setIntReg(ArgumentReg[0], argc);
406    // tc->setIntReg(ArgumentReg[1], argv_array_base);
407    tc->setIntReg(StackPointerReg, stack_min - StackBias);
408
409    // %g1 is a pointer to a function that should be run at exit. Since we
410    // don't have anything like that, it should be set to 0.
411    tc->setIntReg(1, 0);
412
413    tc->pcState(getStartPC());
414
415    // Align the "stack_min" to a page boundary.
416    stack_min = roundDown(stack_min, pageSize);
417
418//    num_processes++;
419}
420
421void
422Sparc64LiveProcess::argsInit(int intSize, int pageSize)
423{
424    SparcLiveProcess::argsInit<uint64_t>(pageSize);
425
426    // Stuff the trap handlers into the process address space
427    initVirtMem.writeBlob(fillStart,
428            (uint8_t*)fillHandler64, sizeof(MachInst) * numFillInsts);
429    initVirtMem.writeBlob(spillStart,
430            (uint8_t*)spillHandler64, sizeof(MachInst) *  numSpillInsts);
431}
432
433void
434Sparc32LiveProcess::argsInit(int intSize, int pageSize)
435{
436    SparcLiveProcess::argsInit<uint32_t>(pageSize);
437
438    // Stuff the trap handlers into the process address space
439    initVirtMem.writeBlob(fillStart,
440            (uint8_t*)fillHandler32, sizeof(MachInst) * numFillInsts);
441    initVirtMem.writeBlob(spillStart,
442            (uint8_t*)spillHandler32, sizeof(MachInst) *  numSpillInsts);
443}
444
445void Sparc32LiveProcess::flushWindows(ThreadContext *tc)
446{
447    IntReg Cansave = tc->readIntReg(NumIntArchRegs + 3);
448    IntReg Canrestore = tc->readIntReg(NumIntArchRegs + 4);
449    IntReg Otherwin = tc->readIntReg(NumIntArchRegs + 6);
450    MiscReg CWP = tc->readMiscReg(MISCREG_CWP);
451    MiscReg origCWP = CWP;
452    CWP = (CWP + Cansave + 2) % NWindows;
453    while (NWindows - 2 - Cansave != 0) {
454        if (Otherwin) {
455            panic("Otherwin non-zero.\n");
456        } else {
457            tc->setMiscReg(MISCREG_CWP, CWP);
458            // Do the stores
459            IntReg sp = tc->readIntReg(StackPointerReg);
460            for (int index = 16; index < 32; index++) {
461                uint32_t regVal = tc->readIntReg(index);
462                regVal = htog(regVal);
463                if (!tc->getMemProxy().tryWriteBlob(
464                        sp + (index - 16) * 4, (uint8_t *)&regVal, 4)) {
465                    warn("Failed to save register to the stack when "
466                            "flushing windows.\n");
467                }
468            }
469            Canrestore--;
470            Cansave++;
471            CWP = (CWP + 1) % NWindows;
472        }
473    }
474    tc->setIntReg(NumIntArchRegs + 3, Cansave);
475    tc->setIntReg(NumIntArchRegs + 4, Canrestore);
476    tc->setMiscReg(MISCREG_CWP, origCWP);
477}
478
479void
480Sparc64LiveProcess::flushWindows(ThreadContext *tc)
481{
482    IntReg Cansave = tc->readIntReg(NumIntArchRegs + 3);
483    IntReg Canrestore = tc->readIntReg(NumIntArchRegs + 4);
484    IntReg Otherwin = tc->readIntReg(NumIntArchRegs + 6);
485    MiscReg CWP = tc->readMiscReg(MISCREG_CWP);
486    MiscReg origCWP = CWP;
487    CWP = (CWP + Cansave + 2) % NWindows;
488    while (NWindows - 2 - Cansave != 0) {
489        if (Otherwin) {
490            panic("Otherwin non-zero.\n");
491        } else {
492            tc->setMiscReg(MISCREG_CWP, CWP);
493            // Do the stores
494            IntReg sp = tc->readIntReg(StackPointerReg);
495            for (int index = 16; index < 32; index++) {
496                IntReg regVal = tc->readIntReg(index);
497                regVal = htog(regVal);
498                if (!tc->getMemProxy().tryWriteBlob(
499                        sp + 2047 + (index - 16) * 8, (uint8_t *)&regVal, 8)) {
500                    warn("Failed to save register to the stack when "
501                            "flushing windows.\n");
502                }
503            }
504            Canrestore--;
505            Cansave++;
506            CWP = (CWP + 1) % NWindows;
507        }
508    }
509    tc->setIntReg(NumIntArchRegs + 3, Cansave);
510    tc->setIntReg(NumIntArchRegs + 4, Canrestore);
511    tc->setMiscReg(MISCREG_CWP, origCWP);
512}
513
514IntReg
515Sparc32LiveProcess::getSyscallArg(ThreadContext *tc, int &i)
516{
517    assert(i < 6);
518    return bits(tc->readIntReg(FirstArgumentReg + i++), 31, 0);
519}
520
521void
522Sparc32LiveProcess::setSyscallArg(ThreadContext *tc, int i, IntReg val)
523{
524    assert(i < 6);
525    tc->setIntReg(FirstArgumentReg + i, bits(val, 31, 0));
526}
527
528IntReg
529Sparc64LiveProcess::getSyscallArg(ThreadContext *tc, int &i)
530{
531    assert(i < 6);
532    return tc->readIntReg(FirstArgumentReg + i++);
533}
534
535void
536Sparc64LiveProcess::setSyscallArg(ThreadContext *tc, int i, IntReg val)
537{
538    assert(i < 6);
539    tc->setIntReg(FirstArgumentReg + i, val);
540}
541
542void
543SparcLiveProcess::setSyscallReturn(ThreadContext *tc, SyscallReturn sysret)
544{
545    // check for error condition.  SPARC syscall convention is to
546    // indicate success/failure in reg the carry bit of the ccr
547    // and put the return value itself in the standard return value reg ().
548    PSTATE pstate = tc->readMiscRegNoEffect(MISCREG_PSTATE);
549    if (sysret.successful()) {
550        // no error, clear XCC.C
551        tc->setIntReg(NumIntArchRegs + 2,
552                      tc->readIntReg(NumIntArchRegs + 2) & 0xEE);
553        IntReg val = sysret.returnValue();
554        if (pstate.am)
555            val = bits(val, 31, 0);
556        tc->setIntReg(ReturnValueReg, val);
557    } else {
558        // got an error, set XCC.C
559        tc->setIntReg(NumIntArchRegs + 2,
560                      tc->readIntReg(NumIntArchRegs + 2) | 0x11);
561        IntReg val = sysret.errnoValue();
562        if (pstate.am)
563            val = bits(val, 31, 0);
564        tc->setIntReg(ReturnValueReg, val);
565    }
566}
567