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