los_exc.c 38.1 KB
Newer Older
W
wenjun 已提交
1
/*
M
mamingshuai 已提交
2 3
 * Copyright (c) 2013-2019 Huawei Technologies Co., Ltd. All rights reserved.
 * Copyright (c) 2020-2021 Huawei Device Co., Ltd. All rights reserved.
W
wenjun 已提交
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this list of
 *    conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice, this list
 *    of conditions and the following disclaimer in the documentation and/or other materials
 *    provided with the distribution.
 *
 * 3. Neither the name of the copyright holder nor the names of its contributors may be used
 *    to endorse or promote products derived from this software without specific prior written
 *    permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "los_exc.h"
#include "los_memory_pri.h"
#include "los_printf_pri.h"
#include "los_task_pri.h"
#include "los_hw_pri.h"
37
#ifdef LOSCFG_SAVE_EXCINFO
W
wenjun 已提交
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
#include "los_excinfo_pri.h"
#endif
#include "los_sys_stack_pri.h"
#ifdef LOSCFG_COREDUMP
#include "los_coredump.h"
#endif
#ifdef LOSCFG_GDB
#include "gdb_int.h"
#endif
#include "los_mp.h"
#include "los_vm_map.h"
#include "los_vm_dump.h"
#include "los_arch_mmu.h"
#include "los_vm_phys.h"
#include "los_vm_fault.h"
#include "los_vm_common.h"
54
#ifdef LOSCFG_KERNEL_DYNLOAD
55
#include "los_load_elf.h"
56
#endif
W
wenjun 已提交
57 58 59 60 61 62 63
#include "arm.h"
#include "los_bitmap.h"
#include "los_process_pri.h"
#include "los_exc_pri.h"
#ifdef LOSCFG_FS_VFS
#include "console.h"
#endif
Q
qidechun 已提交
64 65 66
#ifdef LOSCFG_BLACKBOX
#include "los_blackbox.h"
#endif
W
wenjun 已提交
67 68 69 70 71 72 73 74 75 76 77 78 79


#define INVALID_CPUID  0xFFFF
#define OS_EXC_VMM_NO_REGION  0x0U
#define OS_EXC_VMM_ALL_REGION 0x1U

STATIC UINTPTR g_minAddr;
STATIC UINTPTR g_maxAddr;
STATIC UINT32 g_currHandleExcCpuID = INVALID_CPUID;
VOID OsExcHook(UINT32 excType, ExcContext *excBufAddr, UINT32 far, UINT32 fsr);
UINT32 g_curNestCount[LOSCFG_KERNEL_CORE_NUM] = { 0 };
BOOL g_excFromUserMode[LOSCFG_KERNEL_CORE_NUM];
STATIC EXC_PROC_FUNC g_excHook = (EXC_PROC_FUNC)OsExcHook;
80
#ifdef LOSCFG_KERNEL_SMP
W
wenjun 已提交
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
STATIC SPIN_LOCK_INIT(g_excSerializerSpin);
STATIC UINT32 g_currHandleExcPID = OS_INVALID_VALUE;
STATIC UINT32 g_nextExcWaitCpu = INVALID_CPUID;
#endif

#define OS_MAX_BACKTRACE    15U
#define DUMPSIZE            128U
#define DUMPREGS            12U
#define INSTR_SET_MASK      0x01000020U
#define THUMB_INSTR_LEN     2U
#define ARM_INSTR_LEN       4U
#define POINTER_SIZE        4U
#define WNR_BIT             11U
#define FSR_FLAG_OFFSET_BIT 10U
#define FSR_BITS_BEGIN_BIT  3U


#define GET_FS(fsr) (((fsr) & 0xFU) | (((fsr) & (1U << 10)) >> 6))
#define GET_WNR(dfsr) ((dfsr) & (1U << 11))

#define IS_VALID_ADDR(ptr) (((ptr) >= g_minAddr) &&       \
                            ((ptr) <= g_maxAddr) && \
                            (IS_ALIGNED((ptr), sizeof(CHAR *))))

STATIC const StackInfo g_excStack[] = {
    { &__svc_stack,   OS_EXC_SVC_STACK_SIZE,   "svc_stack" },
    { &__exc_stack,   OS_EXC_STACK_SIZE,       "exc_stack" }
};

UINT32 OsGetSystemStatus(VOID)
{
    UINT32 flag;
    UINT32 cpuID = g_currHandleExcCpuID;

    if (cpuID == INVALID_CPUID) {
        flag = OS_SYSTEM_NORMAL;
    } else if (cpuID == ArchCurrCpuid()) {
        flag = OS_SYSTEM_EXC_CURR_CPU;
    } else {
        flag = OS_SYSTEM_EXC_OTHER_CPU;
    }

    return flag;
}

STATIC INT32 OsDecodeFS(UINT32 bitsFS)
{
    switch (bitsFS) {
        case 0x05:  /* 0b00101 */
        case 0x07:  /* 0b00111 */
            PrintExcInfo("Translation fault, %s\n", (bitsFS & 0x2) ? "page" : "section");
            break;
        case 0x09:  /* 0b01001 */
        case 0x0b:  /* 0b01011 */
            PrintExcInfo("Domain fault, %s\n", (bitsFS & 0x2) ? "page" : "section");
            break;
        case 0x0d:  /* 0b01101 */
        case 0x0f:  /* 0b01111 */
            PrintExcInfo("Permission fault, %s\n", (bitsFS & 0x2) ? "page" : "section");
            break;
        default:
            PrintExcInfo("Unknown fault! FS:0x%x. "
                         "Check IFSR and DFSR in ARM Architecture Reference Manual.\n",
                         bitsFS);
            break;
    }

    return LOS_OK;
}

STATIC INT32 OsDecodeInstructionFSR(UINT32 regIFSR)
{
    INT32 ret;
    UINT32 bitsFS = GET_FS(regIFSR); /* FS bits[4]+[3:0] */

    ret = OsDecodeFS(bitsFS);
    return ret;
}

STATIC INT32 OsDecodeDataFSR(UINT32 regDFSR)
{
    INT32 ret = 0;
    UINT32 bitWnR = GET_WNR(regDFSR); /* WnR bit[11] */
    UINT32 bitsFS = GET_FS(regDFSR);  /* FS bits[4]+[3:0] */

    if (bitWnR) {
        PrintExcInfo("Abort caused by a write instruction. ");
    } else {
        PrintExcInfo("Abort caused by a read instruction. ");
    }

    if (bitsFS == 0x01) { /* 0b00001 */
        PrintExcInfo("Alignment fault.\n");
        return ret;
    }
    ret = OsDecodeFS(bitsFS);
    return ret;
}

Y
YOUR_NAME 已提交
180
#ifdef LOSCFG_KERNEL_VM
W
wenjun 已提交
181 182
UINT32 OsArmSharedPageFault(UINT32 excType, ExcContext *frame, UINT32 far, UINT32 fsr)
{
183
    BOOL instructionFault = FALSE;
W
wenjun 已提交
184 185 186
    UINT32 pfFlags = 0;
    UINT32 fsrFlag;
    BOOL write = FALSE;
187
    UINT32 ret;
W
wenjun 已提交
188

189
    PRINT_INFO("page fault entry!!!\n");
W
wenjun 已提交
190 191 192
    if (OsGetSystemStatus() == OS_SYSTEM_EXC_CURR_CPU) {
        return LOS_ERRNO_VM_NOT_FOUND;
    }
193 194
#if defined(LOSCFG_KERNEL_SMP) && defined(LOSCFG_DEBUG_VERSION)
    BOOL irqEnable = !(LOS_SpinHeld(&g_taskSpin) && (OsPercpuGet()->taskLockCnt != 0));
195 196 197
    if (irqEnable) {
        ArchIrqEnable();
    } else {
198 199
        PrintExcInfo("[ERR][%s] may be held scheduler lock when entering [%s] on cpu [%u]\n",
                     OsCurrTaskGet()->taskName, __FUNCTION__, ArchCurrCpuid());
200 201 202 203
    }
#else
    ArchIrqEnable();
#endif
W
wenjun 已提交
204
    if (excType == OS_EXCEPT_PREFETCH_ABORT) {
205
        instructionFault = TRUE;
W
wenjun 已提交
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222
    } else {
        write = !!BIT_GET(fsr, WNR_BIT);
    }

    fsrFlag = ((BIT_GET(fsr, FSR_FLAG_OFFSET_BIT) ? 0b10000 : 0) | BITS_GET(fsr, FSR_BITS_BEGIN_BIT, 0));
    switch (fsrFlag) {
        case 0b00101:
        /* translation fault */
        case 0b00111:
        /* translation fault */
        case 0b01101:
        /* permission fault */
        case 0b01111: {
        /* permission fault */
            BOOL user = (frame->regCPSR & CPSR_MODE_MASK) == CPSR_MODE_USR;
            pfFlags |= write ? VM_MAP_PF_FLAG_WRITE : 0;
            pfFlags |= user ? VM_MAP_PF_FLAG_USER : 0;
223
            pfFlags |= instructionFault ? VM_MAP_PF_FLAG_INSTRUCTION : 0;
W
wenjun 已提交
224
            pfFlags |= VM_MAP_PF_FLAG_NOT_PRESENT;
225
            OsSigIntLock();
226
            ret = OsVmPageFaultHandler(far, pfFlags, frame);
227
            OsSigIntUnlock();
228
            break;
W
wenjun 已提交
229 230
        }
        default:
231 232
            ret = LOS_ERRNO_VM_NOT_FOUND;
            break;
W
wenjun 已提交
233
    }
234
#if defined(LOSCFG_KERNEL_SMP) && defined(LOSCFG_DEBUG_VERSION)
235 236 237 238 239 240 241
    if (irqEnable) {
        ArchIrqDisable();
    }
#else
    ArchIrqDisable();
#endif
    return ret;
W
wenjun 已提交
242
}
Y
YOUR_NAME 已提交
243
#endif
W
wenjun 已提交
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275

STATIC VOID OsExcType(UINT32 excType, ExcContext *excBufAddr, UINT32 far, UINT32 fsr)
{
    /* undefinited exception handling or software interrupt */
    if ((excType == OS_EXCEPT_UNDEF_INSTR) || (excType == OS_EXCEPT_SWI)) {
        if ((excBufAddr->regCPSR & INSTR_SET_MASK) == 0) { /* work status: ARM */
            excBufAddr->PC = excBufAddr->PC - ARM_INSTR_LEN;
        } else if ((excBufAddr->regCPSR & INSTR_SET_MASK) == 0x20) { /* work status: Thumb */
            excBufAddr->PC = excBufAddr->PC - THUMB_INSTR_LEN;
        }
    }

    if (excType == OS_EXCEPT_PREFETCH_ABORT) {
        PrintExcInfo("prefetch_abort fault fsr:0x%x, far:0x%0+8x\n", fsr, far);
        (VOID)OsDecodeInstructionFSR(fsr);
    } else if (excType == OS_EXCEPT_DATA_ABORT) {
        PrintExcInfo("data_abort fsr:0x%x, far:0x%0+8x\n", fsr, far);
        (VOID)OsDecodeDataFSR(fsr);
    }
}

STATIC const CHAR *g_excTypeString[] = {
    "reset",
    "undefined instruction",
    "software interrupt",
    "prefetch abort",
    "data abort",
    "fiq",
    "address abort",
    "irq"
};

Y
YOUR_NAME 已提交
276
#ifdef LOSCFG_KERNEL_VM
277 278
STATIC VADDR_T OsGetTextRegionBase(LosVmMapRegion *region, LosProcessCB *runProcess)
{
279 280
    struct Vnode *curVnode = NULL;
    struct Vnode *lastVnode = NULL;
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
    LosVmMapRegion *curRegion = NULL;
    LosVmMapRegion *lastRegion = NULL;

    if ((region == NULL) || (runProcess == NULL)) {
        return 0;
    }

    if (!LOS_IsRegionFileValid(region)) {
        return region->range.base;
    }

    lastRegion = region;
    do {
        curRegion = lastRegion;
        lastRegion = LOS_RegionFind(runProcess->vmSpace, curRegion->range.base - 1);
        if ((lastRegion == NULL) || !LOS_IsRegionFileValid(lastRegion)) {
            goto DONE;
        }
299 300 301
        curVnode = curRegion->unTypeData.rf.vnode;
        lastVnode = lastRegion->unTypeData.rf.vnode;
    } while (curVnode == lastVnode);
302 303

DONE:
304
#ifdef LOSCFG_KERNEL_DYNLOAD
305 306 307
    if (curRegion->range.base == EXEC_MMAP_BASE) {
        return 0;
    }
308
#endif
309 310
    return curRegion->range.base;
}
Y
YOUR_NAME 已提交
311
#endif
312

W
wenjun 已提交
313 314 315 316 317 318 319 320
STATIC VOID OsExcSysInfo(UINT32 excType, const ExcContext *excBufAddr)
{
    LosTaskCB *runTask = OsCurrTaskGet();
    LosProcessCB *runProcess = OsCurrProcessGet();

    PrintExcInfo("excType: %s\n"
                 "processName       = %s\n"
                 "processID         = %u\n"
Y
YOUR_NAME 已提交
321
#ifdef LOSCFG_KERNEL_VM
W
wenjun 已提交
322
                 "process aspace    = 0x%08x -> 0x%08x\n"
Y
YOUR_NAME 已提交
323
#endif
W
wenjun 已提交
324 325 326 327 328
                 "taskName          = %s\n"
                 "taskID            = %u\n",
                 g_excTypeString[excType],
                 runProcess->processName,
                 runProcess->processID,
Y
YOUR_NAME 已提交
329
#ifdef LOSCFG_KERNEL_VM
W
wenjun 已提交
330 331
                 runProcess->vmSpace->base,
                 runProcess->vmSpace->base + runProcess->vmSpace->size,
Y
YOUR_NAME 已提交
332
#endif
W
wenjun 已提交
333 334 335
                 runTask->taskName,
                 runTask->taskID);

Y
YOUR_NAME 已提交
336
#ifdef LOSCFG_KERNEL_VM
W
wenjun 已提交
337 338 339
    if (OsProcessIsUserMode(runProcess)) {
        PrintExcInfo("task user stack   = 0x%08x -> 0x%08x\n",
                     runTask->userMapBase, runTask->userMapBase + runTask->userMapSize);
Y
YOUR_NAME 已提交
340 341 342
    } else
#endif
    {
W
wenjun 已提交
343 344 345 346 347
        PrintExcInfo("task kernel stack = 0x%08x -> 0x%08x\n",
                     runTask->topOfStack, runTask->topOfStack + runTask->stackSize);
    }

    PrintExcInfo("pc    = 0x%x ", excBufAddr->PC);
Y
YOUR_NAME 已提交
348 349
#ifdef LOSCFG_KERNEL_VM
    LosVmMapRegion *region = NULL;
W
wenjun 已提交
350 351 352 353 354
    if (g_excFromUserMode[ArchCurrCpuid()] == TRUE) {
        if (LOS_IsUserAddress((vaddr_t)excBufAddr->PC)) {
            region = LOS_RegionFind(runProcess->vmSpace, (VADDR_T)excBufAddr->PC);
            if (region != NULL) {
                PrintExcInfo("in %s ---> 0x%x", OsGetRegionNameOrFilePath(region),
355
                             (VADDR_T)excBufAddr->PC - OsGetTextRegionBase(region, runProcess));
W
wenjun 已提交
356 357 358 359 360 361 362
            }
        }

        PrintExcInfo("\nulr   = 0x%x ", excBufAddr->ULR);
        region = LOS_RegionFind(runProcess->vmSpace, (VADDR_T)excBufAddr->ULR);
        if (region != NULL) {
            PrintExcInfo("in %s ---> 0x%x", OsGetRegionNameOrFilePath(region),
363
                         (VADDR_T)excBufAddr->ULR - OsGetTextRegionBase(region, runProcess));
W
wenjun 已提交
364 365
        }
        PrintExcInfo("\nusp   = 0x%x", excBufAddr->USP);
Y
YOUR_NAME 已提交
366 367 368
    } else
#endif
    {
W
wenjun 已提交
369 370 371 372 373 374
        PrintExcInfo("\nklr   = 0x%x\n"
                     "ksp   = 0x%x\n",
                     excBufAddr->LR,
                     excBufAddr->SP);
    }

M
mamingshuai 已提交
375
    PrintExcInfo("\nfp    = 0x%x\n", excBufAddr->R11);
W
wenjun 已提交
376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
}

STATIC VOID OsExcRegsInfo(const ExcContext *excBufAddr)
{
    /*
     * Split register information into two parts:
     * Ensure printing does not rely on memory modules.
     */
    PrintExcInfo("R0    = 0x%x\n"
                 "R1    = 0x%x\n"
                 "R2    = 0x%x\n"
                 "R3    = 0x%x\n"
                 "R4    = 0x%x\n"
                 "R5    = 0x%x\n"
                 "R6    = 0x%x\n",
                 excBufAddr->R0, excBufAddr->R1, excBufAddr->R2, excBufAddr->R3,
                 excBufAddr->R4, excBufAddr->R5, excBufAddr->R6);
    PrintExcInfo("R7    = 0x%x\n"
                 "R8    = 0x%x\n"
                 "R9    = 0x%x\n"
                 "R10   = 0x%x\n"
                 "R11   = 0x%x\n"
                 "R12   = 0x%x\n"
                 "CPSR  = 0x%x\n",
                 excBufAddr->R7, excBufAddr->R8, excBufAddr->R9, excBufAddr->R10,
                 excBufAddr->R11, excBufAddr->R12, excBufAddr->regCPSR);
}

LITE_OS_SEC_TEXT_INIT UINT32 LOS_ExcRegHook(EXC_PROC_FUNC excHook)
{
    UINT32 intSave;

    intSave = LOS_IntLock();
    g_excHook = excHook;
    LOS_IntRestore(intSave);

    return LOS_OK;
}

EXC_PROC_FUNC OsExcRegHookGet(VOID)
{
    return g_excHook;
}

Y
YOUR_NAME 已提交
420
#ifdef LOSCFG_KERNEL_VM
W
wenjun 已提交
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
STATIC VOID OsDumpExcVaddrRegion(LosVmSpace *space, LosVmMapRegion *region)
{
    INT32 i, numPages, pageCount;
    paddr_t addr, oldAddr, startVaddr, startPaddr;
    vaddr_t pageBase;
    BOOL mmuFlag = FALSE;

    numPages = region->range.size >> PAGE_SHIFT;
    mmuFlag = TRUE;
    for (pageCount = 0, startPaddr = 0, startVaddr = 0, i = 0; i < numPages; i++) {
        pageBase = region->range.base + i * PAGE_SIZE;
        addr = 0;
        if (LOS_ArchMmuQuery(&space->archMmu, pageBase, &addr, NULL) != LOS_OK) {
            if (startPaddr == 0) {
                continue;
            }
        } else if (startPaddr == 0) {
            startVaddr = pageBase;
            startPaddr = addr;
            oldAddr = addr;
            pageCount++;
            if (numPages > 1) {
                continue;
            }
        } else if (addr == (oldAddr + PAGE_SIZE)) {
            pageCount++;
            oldAddr = addr;
            if (i < (numPages - 1)) {
                continue;
            }
        }
        if (mmuFlag == TRUE) {
            PrintExcInfo("       uvaddr       kvaddr       mapped size\n");
            mmuFlag = FALSE;
        }
        PrintExcInfo("       0x%08x   0x%08x   0x%08x\n",
M
mamingshuai 已提交
457
                     startVaddr, LOS_PaddrToKVaddr(startPaddr), (UINT32)pageCount << PAGE_SHIFT);
W
wenjun 已提交
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
        pageCount = 0;
        startPaddr = 0;
    }
}

STATIC VOID OsDumpProcessUsedMemRegion(LosProcessCB *runProcess, LosVmSpace *runspace, UINT16 vmmFlags)
{
    LosVmMapRegion *region = NULL;
    LosRbNode *pstRbNodeTemp = NULL;
    LosRbNode *pstRbNodeNext = NULL;
    UINT32 count = 0;

    /* search the region list */
    RB_SCAN_SAFE(&runspace->regionRbTree, pstRbNodeTemp, pstRbNodeNext)
        region = (LosVmMapRegion *)pstRbNodeTemp;
        PrintExcInfo("%3u -> regionBase: 0x%08x regionSize: 0x%08x\n", count, region->range.base, region->range.size);
        if (vmmFlags == OS_EXC_VMM_ALL_REGION) {
            OsDumpExcVaddrRegion(runspace, region);
        }
        count++;
        (VOID)OsRegionOverlapCheckUnlock(runspace, region);
    RB_SCAN_SAFE_END(&space->regionRbTree, pstRbNodeTemp, pstRbNodeNext)
}

STATIC VOID OsDumpProcessUsedMemNode(UINT16 vmmFalgs)
{
    LosProcessCB *runProcess = NULL;
    LosVmSpace *runspace = NULL;

    runProcess = OsCurrProcessGet();
    if (runProcess == NULL) {
        return;
    }

    if (!OsProcessIsUserMode(runProcess)) {
        return;
    }

    PrintExcInfo("\n   ******Current process %u vmm regions: ******\n", runProcess->processID);

    runspace = runProcess->vmSpace;
    if (!runspace) {
        return;
    }

    OsDumpProcessUsedMemRegion(runProcess, runspace, vmmFalgs);
    return;
}
Y
YOUR_NAME 已提交
506
#endif
W
wenjun 已提交
507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528

VOID OsDumpContextMem(const ExcContext *excBufAddr)
{
    UINT32 count = 0;
    const UINT32 *excReg = NULL;
    if (g_excFromUserMode[ArchCurrCpuid()] == TRUE) {
        return;
    }

    for (excReg = &(excBufAddr->R0); count <= DUMPREGS; excReg++, count++) {
        if (IS_VALID_ADDR(*excReg)) {
            PrintExcInfo("\ndump mem around R%u:%p", count, (*excReg));
            OsDumpMemByte(DUMPSIZE, ((*excReg) - (DUMPSIZE >> 1)));
        }
    }

    if (IS_VALID_ADDR(excBufAddr->SP)) {
        PrintExcInfo("\ndump mem around SP:%p", excBufAddr->SP);
        OsDumpMemByte(DUMPSIZE, (excBufAddr->SP - (DUMPSIZE >> 1)));
    }
}

529
STATIC VOID OsExcRestore(VOID)
W
wenjun 已提交
530 531 532 533 534 535
{
    UINT32 currCpuID = ArchCurrCpuid();

    g_excFromUserMode[currCpuID] = FALSE;
    g_intCount[currCpuID] = 0;
    g_curNestCount[currCpuID] = 0;
536
#ifdef LOSCFG_KERNEL_SMP
W
wenjun 已提交
537 538 539 540 541 542 543
    OsPercpuGet()->excFlag = CPU_RUNNING;
#endif
    OsPercpuGet()->taskLockCnt = 0;
}

STATIC VOID OsUserExcHandle(ExcContext *excBufAddr)
{
544
    UINT32 intSave;
W
wenjun 已提交
545
    UINT32 currCpu = ArchCurrCpuid();
546
    LosTaskCB *runTask = OsCurrTaskGet();
W
wenjun 已提交
547 548 549 550 551 552
    LosProcessCB *runProcess = OsCurrProcessGet();

    if (g_excFromUserMode[ArchCurrCpuid()] == FALSE) {
        return;
    }

553
#ifdef LOSCFG_KERNEL_SMP
W
wenjun 已提交
554 555 556 557 558 559 560 561 562 563 564 565 566 567
    LOS_SpinLock(&g_excSerializerSpin);
    if (g_nextExcWaitCpu != INVALID_CPUID) {
        g_currHandleExcCpuID = g_nextExcWaitCpu;
        g_nextExcWaitCpu = INVALID_CPUID;
    } else {
        g_currHandleExcCpuID = INVALID_CPUID;
    }
    g_currHandleExcPID = OS_INVALID_VALUE;
    LOS_SpinUnlock(&g_excSerializerSpin);
#else
    g_currHandleExcCpuID = INVALID_CPUID;
#endif
    runProcess->processStatus &= ~OS_PROCESS_FLAG_EXIT;

568
#ifdef LOSCFG_KERNEL_SMP
W
wenjun 已提交
569 570 571 572 573
#ifdef LOSCFG_FS_VFS
    OsWakeConsoleSendTask();
#endif
#endif

Q
qidechun 已提交
574 575 576
#ifdef LOSCFG_BLACKBOX
    BBoxNotifyError("USER_CRASH", MODULE_SYSTEM, "Crash in user", 0);
#endif
577
    SCHEDULER_LOCK(intSave);
578
#ifdef LOSCFG_SAVE_EXCINFO
W
wenjun 已提交
579 580 581
    OsProcessExitCodeCoreDumpSet(runProcess);
#endif
    OsProcessExitCodeSignalSet(runProcess, SIGUSR2);
M
mamingshuai 已提交
582

583 584 585 586 587 588 589 590 591 592
    /* An exception was raised by a task that is not the current main thread during the exit process of
     * the current process.
     */
    if ((runProcess->processStatus & OS_PROCESS_FLAG_EXIT) && (runProcess->threadGroupID != runTask->taskID)) {
        SCHEDULER_UNLOCK(intSave);
        /* Exception handling All operations should be kept prior to that operation */
        OsExcRestore();
        OsTaskToExit(runTask, OS_PRO_EXIT_OK);
    } else {
        SCHEDULER_UNLOCK(intSave);
593

594 595 596 597 598
        /* Exception handling All operations should be kept prior to that operation */
        OsExcRestore();
        /* kill user exc process */
        LOS_Exit(OS_PRO_EXIT_OK);
    }
W
wenjun 已提交
599 600 601 602 603 604 605

    /* User mode exception handling failed , which normally does not exist */
    g_curNestCount[currCpu]++;
    g_intCount[currCpu]++;
    PrintExcInfo("User mode exception ends unscheduled!\n");
}

Z
zhangfanfan2 已提交
606 607
/* this function is used to validate fp or validate the checking range start and end. */
STATIC INLINE BOOL IsValidFP(UINTPTR regFP, UINTPTR start, UINTPTR end, vaddr_t *vaddr)
W
wenjun 已提交
608 609 610 611 612 613 614
{
    VADDR_T kvaddr = regFP;

    if (!((regFP > start) && (regFP < end) && IS_ALIGNED(regFP, sizeof(CHAR *)))) {
        return FALSE;
    }

Y
YOUR_NAME 已提交
615 616
#ifdef LOSCFG_KERNEL_VM
    PADDR_T paddr;
W
wenjun 已提交
617
    if (g_excFromUserMode[ArchCurrCpuid()] == TRUE) {
Y
YOUR_NAME 已提交
618 619
        LosProcessCB *runProcess = OsCurrProcessGet();
        LosVmSpace *runspace = runProcess->vmSpace;
W
wenjun 已提交
620 621 622 623 624 625 626 627 628 629
        if (runspace == NULL) {
            return FALSE;
        }

        if (LOS_ArchMmuQuery(&runspace->archMmu, regFP, &paddr, NULL) != LOS_OK) {
            return FALSE;
        }

        kvaddr = (PADDR_T)(UINTPTR)LOS_PaddrToKVaddr(paddr);
    }
Y
YOUR_NAME 已提交
630
#endif
W
wenjun 已提交
631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
    if (vaddr != NULL) {
        *vaddr = kvaddr;
    }

    return TRUE;
}

STATIC INLINE BOOL FindSuitableStack(UINTPTR regFP, UINTPTR *start, UINTPTR *end, vaddr_t *vaddr)
{
    UINT32 index, stackStart, stackEnd;
    BOOL found = FALSE;
    LosTaskCB *taskCB = NULL;
    const StackInfo *stack = NULL;
    vaddr_t kvaddr;

    if (g_excFromUserMode[ArchCurrCpuid()] == TRUE) {
        taskCB = OsCurrTaskGet();
        stackStart = taskCB->userMapBase;
        stackEnd = taskCB->userMapBase + taskCB->userMapSize;
Z
zhangfanfan2 已提交
650
        if (IsValidFP(regFP, stackStart, stackEnd, &kvaddr) == TRUE) {
W
wenjun 已提交
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
            found = TRUE;
            goto FOUND;
        }
        return found;
    }

    /* Search in the task stacks */
    for (index = 0; index < g_taskMaxNum; index++) {
        taskCB = &g_taskCBArray[index];
        if (OsTaskIsUnused(taskCB)) {
            continue;
        }

        stackStart = taskCB->topOfStack;
        stackEnd = taskCB->topOfStack + taskCB->stackSize;
Z
zhangfanfan2 已提交
666
        if (IsValidFP(regFP, stackStart, stackEnd, &kvaddr) == TRUE) {
W
wenjun 已提交
667 668 669 670 671 672 673 674 675 676
            found = TRUE;
            goto FOUND;
        }
    }

    /* Search in the exc stacks */
    for (index = 0; index < sizeof(g_excStack) / sizeof(StackInfo); index++) {
        stack = &g_excStack[index];
        stackStart = (UINTPTR)stack->stackTop;
        stackEnd = stackStart + LOSCFG_KERNEL_CORE_NUM * stack->stackSize;
Z
zhangfanfan2 已提交
677
        if (IsValidFP(regFP, stackStart, stackEnd, &kvaddr) == TRUE) {
W
wenjun 已提交
678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
            found = TRUE;
            goto FOUND;
        }
    }

FOUND:
    if (found == TRUE) {
        *start = stackStart;
        *end = stackEnd;
        *vaddr = kvaddr;
    }

    return found;
}

L
LiteOS2021 已提交
693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
BOOL OsGetUsrIpInfo(UINTPTR ip, IpInfo *info)
{
    if (info == NULL) {
        return FALSE;
    }
#ifdef LOSCFG_KERNEL_VM
    BOOL ret = FALSE;
    const CHAR *name = NULL;
    LosVmMapRegion *region = NULL;
    LosProcessCB *runProcess = OsCurrProcessGet();

    if (LOS_IsUserAddress((VADDR_T)ip) == FALSE) {
        info->ip = ip;
        name = "kernel";
        ret = FALSE;
        goto END;
    }

    region = LOS_RegionFind(runProcess->vmSpace, (VADDR_T)ip);
    if (region == NULL) {
        info->ip = ip;
        name = "invalid";
        ret = FALSE;
        goto END;
    }

    info->ip = ip - OsGetTextRegionBase(region, runProcess);
    name = OsGetRegionNameOrFilePath(region);
    ret = TRUE;
    if (strcmp(name, "/lib/libc.so") != 0) {
        PRINT_ERR("ip = 0x%x, %s\n", info->ip, name);
    }
END:
    info->len = strlen(name);
    if (strncpy_s(info->f_path, REGION_PATH_MAX, name, REGION_PATH_MAX - 1) != EOK) {
        info->f_path[0] = '\0';
        info->len = 0;
        PRINT_ERR("copy f_path failed, %s\n", name);
    }
    return ret;
#else
    info->ip = ip;
    return FALSE;
#endif
}

UINT32 BackTraceGet(UINTPTR regFP, IpInfo *callChain, UINT32 maxDepth)
W
wenjun 已提交
740 741 742 743 744
{
    UINTPTR tmpFP, backLR;
    UINTPTR stackStart, stackEnd;
    UINTPTR backFP = regFP;
    UINT32 count = 0;
L
LiteOS2021 已提交
745
    BOOL ret;
W
wenjun 已提交
746 747 748
    VADDR_T kvaddr;

    if (FindSuitableStack(regFP, &stackStart, &stackEnd, &kvaddr) == FALSE) {
L
LiteOS2021 已提交
749 750 751 752
        if (callChain == NULL) {
            PrintExcInfo("traceback error fp = 0x%x\n", regFP);
        }
        return 0;
W
wenjun 已提交
753 754 755 756 757 758 759 760 761
    }

    /*
     * Check whether it is the leaf function.
     * Generally, the frame pointer points to the address of link register, while in the leaf function,
     * there's no function call, and compiler will not store the link register, but the frame pointer
     * will still be stored and updated. In that case we needs to find the right position of frame pointer.
     */
    tmpFP = *(UINTPTR *)(UINTPTR)kvaddr;
Z
zhangfanfan2 已提交
762
    if (IsValidFP(tmpFP, stackStart, stackEnd, NULL) == TRUE) {
W
wenjun 已提交
763
        backFP = tmpFP;
L
LiteOS2021 已提交
764 765 766
        if (callChain == NULL) {
            PrintExcInfo("traceback fp fixed, trace using   fp = 0x%x\n", backFP);
        }
W
wenjun 已提交
767 768
    }

Z
zhangfanfan2 已提交
769
    while (IsValidFP(backFP, stackStart, stackEnd, &kvaddr) == TRUE) {
W
wenjun 已提交
770
        tmpFP = backFP;
771
#ifdef LOSCFG_COMPILER_CLANG_LLVM
772
        backFP = *(UINTPTR *)(UINTPTR)kvaddr;
Z
zhangfanfan2 已提交
773
        if (IsValidFP(tmpFP + POINTER_SIZE, stackStart, stackEnd, &kvaddr) == FALSE) {
L
LiteOS2021 已提交
774 775 776 777
            if (callChain == NULL) {
                PrintExcInfo("traceback backLR check failed, backLP: 0x%x\n", tmpFP + POINTER_SIZE);
            }
            return 0;
778
        }
W
wenjun 已提交
779
        backLR = *(UINTPTR *)(UINTPTR)kvaddr;
780
#else
X
x_xiny 已提交
781
        backLR = *(UINTPTR *)(UINTPTR)kvaddr;
Z
zhangfanfan2 已提交
782
        if (IsValidFP(tmpFP - POINTER_SIZE, stackStart, stackEnd, &kvaddr) == FALSE) {
L
LiteOS2021 已提交
783 784 785 786
            if (callChain == NULL) {
                PrintExcInfo("traceback backFP check failed, backFP: 0x%x\n", tmpFP - POINTER_SIZE);
            }
            return 0;
W
wenjun 已提交
787 788
        }
        backFP = *(UINTPTR *)(UINTPTR)kvaddr;
789
#endif
L
LiteOS2021 已提交
790 791 792 793 794
        IpInfo info = {0};
        ret = OsGetUsrIpInfo((VADDR_T)backLR, &info);
        if (callChain == NULL) {
            PrintExcInfo("traceback %u -- lr = 0x%x    fp = 0x%x ", count, backLR, backFP);
            if (ret) {
Y
YOUR_NAME 已提交
795
#ifdef LOSCFG_KERNEL_VM
L
LiteOS2021 已提交
796 797 798
                PrintExcInfo("lr in %s --> 0x%x\n", info.f_path, info.ip);
#else
                PrintExcInfo("\n");
Y
YOUR_NAME 已提交
799
#endif
L
LiteOS2021 已提交
800 801 802 803 804
            } else {
                PrintExcInfo("\n");
            }
        } else {
            (VOID)memcpy_s(&callChain[count], sizeof(IpInfo), &info, sizeof(IpInfo));
W
wenjun 已提交
805 806
        }
        count++;
L
LiteOS2021 已提交
807
        if ((count == maxDepth) || (backFP == tmpFP)) {
W
wenjun 已提交
808 809 810
            break;
        }
    }
L
LiteOS2021 已提交
811 812 813 814 815 816
    return count;
}

VOID BackTraceSub(UINTPTR regFP)
{
    (VOID)BackTraceGet(regFP, NULL, OS_MAX_BACKTRACE);
W
wenjun 已提交
817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
}

VOID BackTrace(UINT32 regFP)
{
    PrintExcInfo("*******backtrace begin*******\n");

    BackTraceSub(regFP);
}

VOID OsExcInit(VOID)
{
    OsExcStackInfoReg(g_excStack, sizeof(g_excStack) / sizeof(g_excStack[0]));
}

VOID OsExcHook(UINT32 excType, ExcContext *excBufAddr, UINT32 far, UINT32 fsr)
{
    OsExcType(excType, excBufAddr, far, fsr);
    OsExcSysInfo(excType, excBufAddr);
    OsExcRegsInfo(excBufAddr);

    BackTrace(excBufAddr->R11);

    (VOID)OsShellCmdTskInfoGet(OS_ALL_TASK_MASK, NULL, OS_PROCESS_INFO_ALL);

#ifndef LOSCFG_DEBUG_VERSION
    if (g_excFromUserMode[ArchCurrCpuid()] != TRUE) {
#endif
Y
YOUR_NAME 已提交
844
#ifdef LOSCFG_KERNEL_VM
W
wenjun 已提交
845
        OsDumpProcessUsedMemNode(OS_EXC_VMM_NO_REGION);
Y
YOUR_NAME 已提交
846
#endif
W
wenjun 已提交
847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905
        OsExcStackInfo();
#ifndef LOSCFG_DEBUG_VERSION
    }
#endif

    OsDumpContextMem(excBufAddr);

    (VOID)OsShellCmdMemCheck(0, NULL);

#ifdef LOSCFG_COREDUMP
    LOS_CoreDumpV2(excType, excBufAddr);
#endif

    OsUserExcHandle(excBufAddr);
}

VOID OsCallStackInfo(VOID)
{
    UINT32 count = 0;
    LosTaskCB *runTask = OsCurrTaskGet();
    UINTPTR stackBottom = runTask->topOfStack + runTask->stackSize;
    UINT32 *stackPointer = (UINT32 *)stackBottom;

    PrintExcInfo("runTask->stackPointer = 0x%x\n"
                 "runTask->topOfStack = 0x%x\n"
                 "text_start:0x%x,text_end:0x%x\n",
                 stackPointer, runTask->topOfStack, &__text_start, &__text_end);

    while ((stackPointer > (UINT32 *)runTask->topOfStack) && (count < OS_MAX_BACKTRACE)) {
        if ((*stackPointer > (UINTPTR)(&__text_start)) &&
            (*stackPointer < (UINTPTR)(&__text_end)) &&
            IS_ALIGNED((*stackPointer), POINTER_SIZE)) {
            if ((*(stackPointer - 1) > (UINT32)runTask->topOfStack) &&
                (*(stackPointer - 1) < stackBottom) &&
                IS_ALIGNED((*(stackPointer - 1)), POINTER_SIZE)) {
                count++;
                PrintExcInfo("traceback %u -- lr = 0x%x\n", count, *stackPointer);
            }
        }
        stackPointer--;
    }
    PRINTK("\n");
}

VOID OsTaskBackTrace(UINT32 taskID)
{
    LosTaskCB *taskCB = NULL;

    if (OS_TID_CHECK_INVALID(taskID)) {
        PRINT_ERR("\r\nTask ID is invalid!\n");
        return;
    }
    taskCB = OS_TCB_FROM_TID(taskID);
    if (OsTaskIsUnused(taskCB) || (taskCB->taskEntry == NULL)) {
        PRINT_ERR("\r\nThe task is not created!\n");
        return;
    }
    PRINTK("TaskName = %s\n", taskCB->taskName);
    PRINTK("TaskID = 0x%x\n", taskCB->taskID);
906
    BackTrace(((TaskContext *)(taskCB->stackPointer))->R11); /* R11 : FP */
W
wenjun 已提交
907 908 909 910 911 912
}

VOID OsBackTrace(VOID)
{
    UINT32 regFP = Get_Fp();
    LosTaskCB *runTask = OsCurrTaskGet();
M
mamingshuai 已提交
913 914 915
    PrintExcInfo("OsBackTrace fp = 0x%x\n", regFP);
    PrintExcInfo("runTask->taskName = %s\n", runTask->taskName);
    PrintExcInfo("runTask->taskID = %u\n", runTask->taskID);
W
wenjun 已提交
916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975
    BackTrace(regFP);
}

#ifdef LOSCFG_GDB
VOID OsUndefIncExcHandleEntry(ExcContext *excBufAddr)
{
    excBufAddr->PC -= 4;  /* lr in undef is pc + 4 */

    if (gdb_undef_hook(excBufAddr, OS_EXCEPT_UNDEF_INSTR)) {
        return;
    }

    if (g_excHook != NULL) {
        /* far, fsr are unused in exc type of OS_EXCEPT_UNDEF_INSTR */
        g_excHook(OS_EXCEPT_UNDEF_INSTR, excBufAddr, 0, 0);
    }
    while (1) {}
}

#if __LINUX_ARM_ARCH__ >= 7
VOID OsPrefetchAbortExcHandleEntry(ExcContext *excBufAddr)
{
    UINT32 far;
    UINT32 fsr;

    excBufAddr->PC -= 4;  /* lr in prefetch abort is pc + 4 */

    if (gdbhw_hook(excBufAddr, OS_EXCEPT_PREFETCH_ABORT)) {
        return;
    }

    if (g_excHook != NULL) {
        far = OsArmReadIfar();
        fsr = OsArmReadIfsr();
        g_excHook(OS_EXCEPT_PREFETCH_ABORT, excBufAddr, far, fsr);
    }
    while (1) {}
}

VOID OsDataAbortExcHandleEntry(ExcContext *excBufAddr)
{
    UINT32 far;
    UINT32 fsr;

    excBufAddr->PC -= 8;  /* lr in data abort is pc + 8 */

    if (gdbhw_hook(excBufAddr, OS_EXCEPT_DATA_ABORT)) {
        return;
    }

    if (g_excHook != NULL) {
        far = OsArmReadDfar();
        fsr = OsArmReadDfsr();
        g_excHook(OS_EXCEPT_DATA_ABORT, excBufAddr, far, fsr);
    }
    while (1) {}
}
#endif /* __LINUX_ARM_ARCH__ */
#endif /* LOSCFG_GDB */

976
#ifdef LOSCFG_KERNEL_SMP
W
wenjun 已提交
977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
#define EXC_WAIT_INTER 50U
#define EXC_WAIT_TIME  2000U

STATIC VOID OsAllCpuStatusOutput(VOID)
{
    UINT32 i;

    for (i = 0; i < LOSCFG_KERNEL_CORE_NUM; i++) {
        switch (g_percpu[i].excFlag) {
            case CPU_RUNNING:
                PrintExcInfo("cpu%u is running.\n", i);
                break;
            case CPU_HALT:
                PrintExcInfo("cpu%u is halted.\n", i);
                break;
            case CPU_EXC:
                PrintExcInfo("cpu%u is in exc.\n", i);
                break;
            default:
                break;
        }
    }
    PrintExcInfo("The current handling the exception is cpu%u !\n", ArchCurrCpuid());
}

STATIC VOID WaitAllCpuStop(UINT32 cpuID)
{
    UINT32 i;
    UINT32 time = 0;

    while (time < EXC_WAIT_TIME) {
        for (i = 0; i < LOSCFG_KERNEL_CORE_NUM; i++) {
            if ((i != cpuID) && (g_percpu[i].excFlag != CPU_HALT)) {
                LOS_Mdelay(EXC_WAIT_INTER);
                time += EXC_WAIT_INTER;
                break;
            }
        }
        /* Other CPUs are all haletd or in the exc. */
        if (i == LOSCFG_KERNEL_CORE_NUM) {
            break;
        }
    }
    return;
}

STATIC VOID OsWaitOtherCoresHandleExcEnd(UINT32 currCpuID)
{
    while (1) {
        LOS_SpinLock(&g_excSerializerSpin);
        if ((g_currHandleExcCpuID == INVALID_CPUID) || (g_currHandleExcCpuID == currCpuID)) {
            g_currHandleExcCpuID = currCpuID;
            g_currHandleExcPID = OsCurrProcessGet()->processID;
            LOS_SpinUnlock(&g_excSerializerSpin);
            break;
        }

        if (g_nextExcWaitCpu == INVALID_CPUID) {
            g_nextExcWaitCpu = currCpuID;
        }
        LOS_SpinUnlock(&g_excSerializerSpin);
        LOS_Mdelay(EXC_WAIT_INTER);
    }
}

1042
STATIC VOID OsCheckAllCpuStatus(VOID)
W
wenjun 已提交
1043 1044 1045 1046 1047 1048 1049 1050
{
    UINT32 currCpuID = ArchCurrCpuid();
    UINT32 ret, target;

    OsPercpuGet()->excFlag = CPU_EXC;
    LOCKDEP_CLEAR_LOCKS();

    LOS_SpinLock(&g_excSerializerSpin);
1051
    /* Only the current nuclear anomaly */
W
wenjun 已提交
1052 1053 1054 1055
    if (g_currHandleExcCpuID == INVALID_CPUID) {
        g_currHandleExcCpuID = currCpuID;
        g_currHandleExcPID = OsCurrProcessGet()->processID;
        LOS_SpinUnlock(&g_excSerializerSpin);
1056
#ifndef LOSCFG_SAVE_EXCINFO
W
wenjun 已提交
1057 1058 1059 1060
        if (g_excFromUserMode[currCpuID] == FALSE) {
            target = (UINT32)(OS_MP_CPU_ALL & ~CPUID_TO_AFFI_MASK(currCpuID));
            HalIrqSendIpi(target, LOS_MP_IPI_HALT);
        }
1061
#endif
W
wenjun 已提交
1062
    } else if (g_excFromUserMode[currCpuID] == TRUE) {
1063 1064 1065
        /* Both cores raise exceptions, and the current core is a user-mode exception.
         * Both cores are abnormal and come from the same process
         */
W
wenjun 已提交
1066 1067
        if (OsCurrProcessGet()->processID == g_currHandleExcPID) {
            LOS_SpinUnlock(&g_excSerializerSpin);
1068
            OsExcRestore();
1069 1070
            ret = LOS_TaskDelete(OsCurrTaskGet()->taskID);
            LOS_Panic("%s supend task :%u failed: 0x%x\n", __FUNCTION__, OsCurrTaskGet()->taskID, ret);
W
wenjun 已提交
1071 1072 1073 1074 1075
        }
        LOS_SpinUnlock(&g_excSerializerSpin);

        OsWaitOtherCoresHandleExcEnd(currCpuID);
    } else {
X
x_xiny 已提交
1076
        if ((g_currHandleExcCpuID < LOSCFG_KERNEL_CORE_NUM) && (g_excFromUserMode[g_currHandleExcCpuID] == TRUE)) {
W
wenjun 已提交
1077 1078 1079 1080 1081 1082 1083 1084 1085
            g_currHandleExcCpuID = currCpuID;
            LOS_SpinUnlock(&g_excSerializerSpin);
            target = (UINT32)(OS_MP_CPU_ALL & ~CPUID_TO_AFFI_MASK(currCpuID));
            HalIrqSendIpi(target, LOS_MP_IPI_HALT);
        } else {
            LOS_SpinUnlock(&g_excSerializerSpin);
            while (1) {}
        }
    }
1086
#ifndef LOSCFG_SAVE_EXCINFO
W
wenjun 已提交
1087 1088 1089 1090
    /* use halt ipi to stop other active cores */
    if (g_excFromUserMode[ArchCurrCpuid()] == FALSE) {
        WaitAllCpuStop(currCpuID);
    }
1091
#endif
W
wenjun 已提交
1092 1093 1094
}
#endif

1095
STATIC VOID OsCheckCpuStatus(VOID)
W
wenjun 已提交
1096
{
1097
#ifdef LOSCFG_KERNEL_SMP
1098
    OsCheckAllCpuStatus();
W
wenjun 已提交
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115
#else
    g_currHandleExcCpuID = ArchCurrCpuid();
#endif
}

LITE_OS_SEC_TEXT VOID STATIC OsExcPriorDisposal(ExcContext *excBufAddr)
{
    if ((excBufAddr->regCPSR & CPSR_MASK_MODE) == CPSR_USER_MODE) {
        g_minAddr = USER_ASPACE_BASE;
        g_maxAddr = USER_ASPACE_BASE + USER_ASPACE_SIZE;
        g_excFromUserMode[ArchCurrCpuid()] = TRUE;
    } else {
        g_minAddr = KERNEL_ASPACE_BASE;
        g_maxAddr = KERNEL_ASPACE_BASE + KERNEL_ASPACE_SIZE;
        g_excFromUserMode[ArchCurrCpuid()] = FALSE;
    }

1116
    OsCheckCpuStatus();
W
wenjun 已提交
1117

1118
#ifdef LOSCFG_KERNEL_SMP
M
mamingshuai 已提交
1119 1120 1121 1122 1123 1124 1125 1126 1127
#ifdef LOSCFG_FS_VFS
    /* Wait for the end of the Console task to avoid multicore printing code */
    OsWaitConsoleSendTaskPend(OsCurrTaskGet()->taskID);
#endif
#endif
}

LITE_OS_SEC_TEXT_INIT STATIC VOID OsPrintExcHead(UINT32 far)
{
Q
qidechun 已提交
1128 1129 1130 1131 1132
#ifdef LOSCFG_BLACKBOX
#ifdef LOSCFG_SAVE_EXCINFO
    SetExcInfoIndex(0);
#endif
#endif
Y
YOUR_NAME 已提交
1133
#ifdef LOSCFG_KERNEL_VM
M
mamingshuai 已提交
1134 1135 1136
    /* You are not allowed to add any other print information before this exception information */
    if (g_excFromUserMode[ArchCurrCpuid()] == TRUE) {
#ifdef LOSCFG_DEBUG_VERSION
Y
YOUR_NAME 已提交
1137 1138
        VADDR_T vaddr = ROUNDDOWN(far, PAGE_SIZE);
        LosVmSpace *space = LOS_SpaceGet(vaddr);
M
mamingshuai 已提交
1139 1140 1141 1142 1143
        if (space != NULL) {
            LOS_DumpMemRegion(vaddr);
        }
#endif
        PrintExcInfo("##################excFrom: User!####################\n");
Y
YOUR_NAME 已提交
1144 1145 1146
    } else
#endif
    {
M
mamingshuai 已提交
1147 1148
        PrintExcInfo("##################excFrom: kernel!###################\n");
    }
W
wenjun 已提交
1149 1150
}

1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
#ifdef LOSCFG_SAVE_EXCINFO
STATIC VOID OsSysStateSave(UINT32 *intCount, UINT32 *lockCount)
{
    *intCount = g_intCount[ArchCurrCpuid()];
    *lockCount = OsPercpuGet()->taskLockCnt;
    g_intCount[ArchCurrCpuid()] = 0;
    OsPercpuGet()->taskLockCnt = 0;
}

STATIC VOID OsSysStateRestore(UINT32 intCount, UINT32 lockCount)
{
    g_intCount[ArchCurrCpuid()] = intCount;
    OsPercpuGet()->taskLockCnt = lockCount;
}
#endif

W
wenjun 已提交
1167 1168 1169 1170 1171 1172 1173
/*
 * Description : EXC handler entry
 * Input       : excType    --- exc type
 *               excBufAddr --- address of EXC buf
 */
LITE_OS_SEC_TEXT_INIT VOID OsExcHandleEntry(UINT32 excType, ExcContext *excBufAddr, UINT32 far, UINT32 fsr)
{
1174 1175 1176 1177 1178
#ifdef LOSCFG_SAVE_EXCINFO
    UINT32 intCount;
    UINT32 lockCount;
#endif

W
wenjun 已提交
1179 1180 1181 1182 1183 1184 1185
    /* Task scheduling is not allowed during exception handling */
    OsPercpuGet()->taskLockCnt++;

    g_curNestCount[ArchCurrCpuid()]++;

    OsExcPriorDisposal(excBufAddr);

M
mamingshuai 已提交
1186
    OsPrintExcHead(far);
W
wenjun 已提交
1187

1188
#ifdef LOSCFG_KERNEL_SMP
W
wenjun 已提交
1189 1190 1191
    OsAllCpuStatusOutput();
#endif

1192
#ifdef LOSCFG_SAVE_EXCINFO
W
wenjun 已提交
1193 1194 1195 1196 1197
    log_read_write_fn func = GetExcInfoRW();
#endif

    if (g_excHook != NULL) {
        if (g_curNestCount[ArchCurrCpuid()] == 1) {
1198
#ifdef LOSCFG_SAVE_EXCINFO
W
wenjun 已提交
1199
            if (func != NULL) {
Q
qidechun 已提交
1200
#ifndef LOSCFG_BLACKBOX
W
wenjun 已提交
1201
                SetExcInfoIndex(0);
Q
qidechun 已提交
1202
#endif
1203
                OsSysStateSave(&intCount, &lockCount);
W
wenjun 已提交
1204
                OsRecordExcInfoTime();
1205
                OsSysStateRestore(intCount, lockCount);
W
wenjun 已提交
1206 1207 1208 1209 1210 1211 1212
            }
#endif
            g_excHook(excType, excBufAddr, far, fsr);
        } else {
            OsCallStackInfo();
        }

1213
#ifdef LOSCFG_SAVE_EXCINFO
W
wenjun 已提交
1214 1215
        if (func != NULL) {
            PrintExcInfo("Be sure flash space bigger than GetExcInfoIndex():0x%x\n", GetExcInfoIndex());
1216
            OsSysStateSave(&intCount, &lockCount);
W
wenjun 已提交
1217
            func(GetRecordAddr(), GetRecordSpace(), 0, GetExcInfoBuf());
1218
            OsSysStateRestore(intCount, lockCount);
W
wenjun 已提交
1219 1220 1221
        }
#endif
    }
M
mamingshuai 已提交
1222 1223 1224 1225 1226 1227 1228 1229 1230

#ifdef LOSCFG_SHELL_CMD_DEBUG
    SystemRebootFunc rebootHook = OsGetRebootHook();
    if ((OsSystemExcIsReset() == TRUE) && (rebootHook != NULL)) {
        LOS_Mdelay(3000); /* 3000: System dead, delay 3 seconds after system restart */
        rebootHook();
    }
#endif

Q
qidechun 已提交
1231 1232 1233
#ifdef LOSCFG_BLACKBOX
    BBoxNotifyError(EVENT_PANIC, MODULE_SYSTEM, "Crash in kernel", 1);
#endif
W
wenjun 已提交
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
    while (1) {}
}

__attribute__((noinline)) VOID LOS_Panic(const CHAR *fmt, ...)
{
    va_list ap;
    va_start(ap, fmt);
    UartVprintf(fmt, ap);
    va_end(ap);
    __asm__ __volatile__("swi 0");
1244
    while (1);
W
wenjun 已提交
1245 1246 1247
}

/* stack protector */
C
Caoruihong 已提交
1248
USED UINT32 __stack_chk_guard = 0xd00a0dff;
W
wenjun 已提交
1249 1250 1251 1252 1253 1254 1255 1256

VOID __stack_chk_fail(VOID)
{
    /* __builtin_return_address is a builtin function, building in gcc */
    LOS_Panic("stack-protector: Kernel stack is corrupted in: %p\n",
              __builtin_return_address(0));
}

M
mamingshuai 已提交
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
VOID LOS_RecordLR(UINTPTR *LR, UINT32 LRSize, UINT32 recordCount, UINT32 jumpCount)
{
    UINT32 count = 0;
    UINT32 index = 0;
    UINT32 stackStart, stackEnd;
    LosTaskCB *taskCB = NULL;
    UINTPTR framePtr, tmpFramePtr, linkReg;

    if (LR == NULL) {
        return;
    }
    /* if LR array is not enough,just record LRSize. */
    if (LRSize < recordCount) {
        recordCount = LRSize;
    }

    taskCB = OsCurrTaskGet();
    stackStart = taskCB->topOfStack;
    stackEnd = stackStart + taskCB->stackSize;

    framePtr = Get_Fp();
    while ((framePtr > stackStart) && (framePtr < stackEnd) && IS_ALIGNED(framePtr, sizeof(CHAR *))) {
        tmpFramePtr = framePtr;
1280 1281 1282
#ifdef LOSCFG_COMPILER_CLANG_LLVM
        linkReg = *(UINTPTR *)(tmpFramePtr + sizeof(UINTPTR));
#else
M
mamingshuai 已提交
1283
        linkReg = *(UINTPTR *)framePtr;
1284
#endif
M
mamingshuai 已提交
1285 1286 1287 1288 1289 1290 1291
        if (index >= jumpCount) {
            LR[count++] = linkReg;
            if (count == recordCount) {
                break;
            }
        }
        index++;
1292 1293 1294
#ifdef LOSCFG_COMPILER_CLANG_LLVM
        framePtr = *(UINTPTR *)framePtr;
#else
M
mamingshuai 已提交
1295
        framePtr = *(UINTPTR *)(tmpFramePtr - sizeof(UINTPTR));
1296
#endif
M
mamingshuai 已提交
1297 1298 1299 1300 1301 1302 1303 1304
    }

    /* if linkReg is not enough,clean up the last of the effective LR as the end. */
    if (count < recordCount) {
        LR[count] = 0;
    }
}