; Copyright 2016 Castle Technology Ltd
;
; Licensed under the Apache License, Version 2.0 (the "License");
; you may not use this file except in compliance with the License.
; You may obtain a copy of the License at
;
;     http://www.apache.org/licenses/LICENSE-2.0
;
; Unless required by applicable law or agreed to in writing, software
; distributed under the License is distributed on an "AS IS" BASIS,
; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
; See the License for the specific language governing permissions and
; limitations under the License.
;

; DA handler for AMBControl DA nodes

AMBDAHandler ROUT
        CMP     R0, #DAHandler_ResizePMP
        BNE     UnknownHandlerError
        ; In:
        ;  R0 = Reason code
        ;  R1 = change amount (pages)
        ;  R2 = DA number (ignore)
        ;  R12 -> AMBNode
        ; Out:
        ;  All regs preserved
        Entry   "R1,R2,R12"
      [ AMB_Debug
        LDR     R2, [R12, #AMBNode_handle]
        DebugReg R2, "AMBDAHandler "
        DebugReg R1
      ]
        MOV     R2, R12
        LDR     LR, [R2, #AMBNode_DANode+DANode_PMPSize]
        MOV     R12, R1
        ADDS    R1, R1, LR
        ; Unsigned saturate to clamp to zero
        ; This will also force numbers >= 2^31 to 2^32-1, but we don't care
        ; about that because the max appslot size will be much lower than
        ; 2^31 pages.
        MVNMI   R1, R12, ASR #31 ; 0 if shrinking, &FFFFFFFF if growing
        ; Now clamp to max appslot size
        LDR     R12, =ZeroPage
        LDR     R12, [R12, #SoftAplWorkMaxSize]
        SUB     R12, R12, #ApplicationStart
        CMP     R1, R12, LSR #Log2PageSize
        MOVHI   R1, R12, LSR #Log2PageSize
      [ AMB_Debug
        DebugReg R1, "Changing size to "
      ]
        CMP     R1, LR
        LDR     R12, =ZeroPage
        LDR     R12, [R12, #AMBControl_ws]
        ADR     R14, %FT10
        BGT     growpages
        BLT     shrinkpages
10
      [ AMB_Debug
        LDR     R2, [R2, #AMBNode_DANode+DANode_PMPSize]
        DebugReg R2, "<AMBDAHandler new size "
      ]
        EXIT


    END