(* *********************************************************************)
(*                                                                     *)
(*            The CertiKOS Certified Kit Operating System              *)
(*                                                                     *)
(*                   The FLINT Group, Yale University                  *)
(*                                                                     *)
(*  Copyright The FLINT Group, Yale University.  All rights reserved.  *)
(*  This file is distributed under the terms of the Yale University    *)
(*  Non-Commercial License Agreement.                                  *)
(*                                                                     *)
(* *********************************************************************)
(* *********************************************************************)
(*                                                                     *)
(*              Layers of PM: PAbQueue                                 *)
(*                                                                     *)
(*          Provide initialization of thread queue                     *)
(*                                                                     *)
(*          Ronghui Gu <ronghui.gu@yale.edu>                           *)
(*          Yu Guo <yu.guo@yale.edu>                                   *)
(*                                                                     *)
(*          Yale Flint Group                                           *)
(*                                                                     *)
(* *********************************************************************)

(** This file defines the abstract data and the primitives for the PAbQueue layer,
which will introduce abstraction of kernel context*)
Require Import Coqlib.
Require Import Maps.
Require Import ASTExtra.
Require Import Integers.
Require Import Floats.
Require Import Values.
Require Import Memory.
Require Import Events.
Require Import Stacklayout.
Require Import Globalenvs.
Require Import AsmX.
Require Import Smallstep.
Require Import AuxStateDataType.
Require Import Constant.
Require Import GlobIdent.
Require Import FlatMemory.
Require Import CommonTactic.
Require Import AuxLemma.
Require Import RealParams.
Require Import PrimSemantics.
Require Import LAsm.
Require Import LoadStoreSem2.
Require Import XOmega.
Require Import ObservationImpl.

Require Import liblayers.logic.PTreeModules.
Require Import liblayers.logic.LayerLogicImpl.
Require Import liblayers.compat.CompatLayers.
Require Import liblayers.compat.CompatGenSem.

Require Import CalRealPTPool.
Require Import CalRealPT.
Require Import CalRealIDPDE.
Require Import CalRealInitPTE.
Require Import CalRealSMSPool.
Require Import CalRealProcModule.

Require Import INVLemmaContainer.
Require Import INVLemmaMemory.
Require Import INVLemmaThread.

Require Import AbstractDataType.

Require Export ObjCPU.
Require Export ObjFlatMem.
Require Export ObjContainer.
Require Export ObjVMM.
Require Export ObjLMM.
Require Export ObjShareMem.
Require Export ObjThread.

(** * Abstract Data and Primitives at this layer*)
Section WITHMEM.

  Local Open Scope Z_scope.

  Context `{real_params: RealParams}.

  (** **Definition of the raw data at MPTBit layer*)
  (*Record RData :=
    mkRData {
        HP: flatmem; (**r we model the memory from 1G to 3G as heap*)
        ti: trapinfo; (**r abstract of CR2, stores the address where page fault happens*)
        pe: bool; (**r abstract of CR0, indicates whether the paging is enabled or not*)
        ikern: bool; (**r pure logic flag, shows whether it's in kernel mode or not*)
        ihost: bool; (**r logic flag, shows whether it's in the host mode or not*)
        AT: ATable; (**r allocation table*)
        nps: Z; (**r number of the pages*)

        PT: Z; (**r the current page table index*)
        ptpool: PTPool; (**r page table pool*)
        ipt: bool; (**r pure logic flag, shows whether it's using the kernel's page table*)
        pb : PTBitMap; (**r [page table bit map], indicating which page table has been used*)

        kctxt: KContextPool; (**r kernel context pool*)
        abtcb: AbTCBPool; (**r thread control blocks pool*)
        abq: AbQueuePool (**r thread queue pool*)
      }.*)

  (** **Definition of the invariants at MPTNew layer*)
  (** [0th page map] is reserved for the kernel thread*)
  Record high_level_invariant (abd: RData) :=
    mkInvariant {
        valid_nps: pg abd = true -> kern_low <= nps abd <= maxpage;
        valid_AT_kern: pg abd = true -> LAT_kern (LAT abd) (nps abd);
        valid_AT_usr: pg abd = true -> LAT_usr (LAT abd) (nps abd);
        valid_kern: ipt abd = false -> pg abd = true;
        valid_iptt: ipt abd = true -> ikern abd = true;
        valid_iptf: ikern abd = false -> ipt abd = false;
        valid_ihost: ihost abd = false -> pg abd = true /\ ikern abd = true;
        valid_container: Container_valid (AC abd);
        valid_pperm_ppage: Lconsistent_ppage (LAT abd) (pperm abd) (nps abd);
        init_pperm: pg abd = false -> (pperm abd) = ZMap.init PGUndef;
        valid_PMap: pg abd = true ->
                    (forall i, 0<= i < num_proc ->
                               PMap_valid (ZMap.get i (ptpool abd)));
        (* 0th page map is reserved for the kernel thread*)
        valid_PT_kern: pg abd = true -> ipt abd = true -> (PT abd) = 0;
        valid_PMap_kern: pg abd = true -> PMap_kern (ZMap.get 0 (ptpool abd));
        valid_PT: pg abd = true -> 0<= PT abd < num_proc;
        valid_dirty: dirty_ppage (pperm abd) (HP abd);

        valid_idpde: pg abd = true -> IDPDE_init (idpde abd);
        valid_pperm_pmap: consistent_pmap (ptpool abd) (pperm abd) (LAT abd) (nps abd);
        valid_pmap_domain: consistent_pmap_domain (ptpool abd) (pperm abd) (LAT abd) (nps abd);
        valid_lat_domain: consistent_lat_domain (ptpool abd) (LAT abd) (nps abd);

        valid_root: pg abd = true -> cused (ZMap.get 0 (AC abd)) = true;

        valid_TCB: pg abd = true -> AbTCBCorrect_range (abtcb abd);
        valid_TDQ: pg abd = true -> AbQCorrect_range (abq abd);
        valid_notinQ: pg abd = true -> NotInQ (AC abd) (abtcb abd);
        valid_count: pg abd = true -> QCount (abtcb abd) (abq abd);
        valid_inQ: pg abd = true -> InQ (abtcb abd) (abq abd)

      }.

  (** ** Definition of the abstract state ops *)
  Global Instance pabqueue_data_ops : CompatDataOps RData :=
    {
      empty_data := init_adt;
      high_level_invariant := high_level_invariant;
      low_level_invariant := low_level_invariant;
      kernel_mode adt := ikern adt = true /\ ihost adt = true;
      observe := ObservationImpl.observe
    }.

  (** ** Proofs that the initial abstract_data should satisfy the invariants*)
  Section Property_Abstract_Data.

    Lemma empty_data_high_level_invariant:
      high_level_invariant init_adt.
    Proof.
      constructor; simpl; intros; auto; try inv H.
      - apply empty_container_valid.
      - eapply Lconsistent_ppage_init.
      - eapply dirty_ppage_init.
      - eapply consistent_pmap_init.
      - eapply consistent_pmap_domain_init.
      - eapply consistent_lat_domain_init.
   Qed.

    (** ** Definition of the abstract state *)
    Global Instance pabqueue_data_prf : CompatData RData.
    Proof.
      constructor.
      - apply low_level_invariant_incr.
      - apply empty_data_low_level_invariant.
      - apply empty_data_high_level_invariant.
    Qed.

  End Property_Abstract_Data.

  Context `{Hstencil: Stencil}.
  Context `{Hmem: Mem.MemoryModel}.
  Context `{Hmwd: UseMemWithData mem}.

  (** * Proofs that the primitives satisfies the invariants at this layer *)
  Section INV.

    Section ALLOC.

      Lemma alloc_high_level_inv:
        forall d d' i n,
          alloc_spec i d = Some (d', n) ->
          high_level_invariant d ->
          high_level_invariant d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        inv H0. constructor; simpl; eauto.
        - intros; eapply LAT_kern_norm; eauto. eapply _x.
        - intros; eapply LAT_usr_norm; eauto.
        - eapply alloc_container_valid'; eauto.
        - eapply Lconsistent_ppage_norm_alloc; eauto.
        - intros; congruence.
        - eapply dirty_ppage_gso_alloc; eauto.
        - eapply consistent_pmap_gso_at_false; eauto. apply _x.
        - eapply consistent_pmap_domain_gso_at_false; eauto. apply _x.
        - eapply consistent_lat_domain_gss_nil; eauto.
        - zmap_solve.
        - intros; apply NotInQ_gso_true; auto.
      Qed.

      Lemma alloc_low_level_inv:
        forall d d' i n n',
          alloc_spec i d = Some (d', n) ->
          low_level_invariant n' d ->
          low_level_invariant n' d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        inv H0. constructor; eauto.
      Qed.

      Lemma alloc_kernel_mode:
        forall d d' i n,
          alloc_spec i d = Some (d', n) ->
          kernel_mode d ->
          kernel_mode d'.
      Proof.
        intros. functional inversion H; subst; eauto.
      Qed.

      Global Instance alloc_inv: PreservesInvariants alloc_spec.
      Proof.
        preserves_invariants_simpl'.
        - eapply alloc_low_level_inv; eassumption.
        - eapply alloc_high_level_inv; eassumption.
        - eapply alloc_kernel_mode; eassumption.
      Qed.

    End ALLOC.

    Global Instance pfree_inv: PreservesInvariants pfree_spec.
    Proof.
      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.
      - intros; eapply LAT_kern_norm; eauto.
      - intros; eapply LAT_usr_norm; eauto.
      - eapply Lconsistent_ppage_norm_undef; eauto.
      - eapply dirty_ppage_gso_undef; eauto.
      - eapply consistent_pmap_gso_pperm_alloc; eauto.
      - eapply consistent_pmap_domain_gso_at_0; eauto.
      - eapply consistent_lat_domain_gss_nil; eauto.
    Qed.

    Global Instance trapin_inv: PrimInvariants trapin_spec.
    Proof.
      PrimInvariants_simpl H H0.
    Qed.

    Global Instance trapout_inv: PrimInvariants trapout_spec.
    Proof.
      PrimInvariants_simpl H H0.
    Qed.

    Global Instance hostin_inv: PrimInvariants hostin_spec.
    Proof.
      PrimInvariants_simpl H H0.
    Qed.

    Global Instance hostout_inv: PrimInvariants hostout_spec.
    Proof.
      PrimInvariants_simpl H H0.
    Qed.

    Global Instance ptin_inv: PrimInvariants ptin_spec.
    Proof.
      PrimInvariants_simpl H H0.
    Qed.

    Global Instance ptout_inv: PrimInvariants ptout_spec.
    Proof.
      PrimInvariants_simpl H H0.
    Qed.

    Global Instance fstore_inv: PreservesInvariants fstore_spec.
    Proof.
      split; intros; inv_generic_sem H; inv H0; functional inversion H2.
      - functional inversion H. split; trivial.
      - functional inversion H.
        split; subst; simpl;
        try (eapply dirty_ppage_store_unmaped; try reflexivity; try eassumption); trivial.
      - functional inversion H0.
        split; simpl; try assumption.
    Qed.

    Global Instance setPT_inv: PreservesInvariants setPT_spec.
    Proof.
      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.
    Qed.

    Section PTINSERT.

      Section PTINSERT_PTE.

        Lemma ptInsertPTE_high_level_inv:
          forall d d' n vadr padr p,
            ptInsertPTE0_spec n vadr padr p d = Some d' ->
            high_level_invariant d ->
            high_level_invariant d'.
        Proof.
          intros. functional inversion H; subst; eauto.
          inv H0; constructor_gso_simpl_tac; intros.
          - eapply LAT_kern_norm; eauto.
          - eapply LAT_usr_norm; eauto.
          - eapply Lconsistent_ppage_norm; eassumption.
          - eapply PMap_valid_gso_valid; eauto.
          - functional inversion H2. functional inversion H1.
            eapply PMap_kern_gso; eauto.
          - functional inversion H2. functional inversion H0.
            eapply consistent_pmap_ptp_same; try eassumption.
            eapply consistent_pmap_gso_pperm_alloc'; eassumption.
          - functional inversion H2.
            eapply consistent_pmap_domain_append; eauto.
            destruct (ZMap.get pti pdt); try contradiction;
            red; intros (v0 & p0 & He); contra_inv.
          - eapply consistent_lat_domain_gss_append; eauto.
            subst pti; destruct (ZMap.get (PTX vadr) pdt); try contradiction;
            red; intros (v0 & p0 & He); contra_inv.
        Qed.

        Lemma ptInsertPTE_low_level_inv:
          forall d d' n vadr padr p n',
            ptInsertPTE0_spec n vadr padr p d = Some d' ->
            low_level_invariant n' d ->
            low_level_invariant n' d'.
        Proof.
          intros. functional inversion H; subst; eauto.
          inv H0. constructor; eauto.
        Qed.

        Lemma ptInsertPTE_kernel_mode:
          forall d d' n vadr padr p,
            ptInsertPTE0_spec n vadr padr p d = Some d' ->
            kernel_mode d ->
            kernel_mode d'.
        Proof.
          intros. functional inversion H; subst; eauto.
        Qed.

      End PTINSERT_PTE.

      Section PTALLOCPDE.

        Lemma ptAllocPDE_high_level_inv:
          forall d d' n vadr v,
            ptAllocPDE0_spec n vadr d = Some (d', v) ->
            high_level_invariant d ->
            high_level_invariant d'.
        Proof.
          intros. functional inversion H; subst; eauto.
          inv H0; constructor_gso_simpl_tac; intros.
          - eapply LAT_kern_norm; eauto. eapply _x.
          - eapply LAT_usr_norm; eauto.
          - eapply alloc_container_valid'; eauto.
          - apply Lconsistent_ppage_norm_hide; try assumption.
          - congruence.
          - eapply PMap_valid_gso_pde_unp; eauto.
            eapply real_init_PTE_defined.
          - functional inversion H3.
            eapply PMap_kern_gso; eauto.
          - eapply dirty_ppage_gss; eauto.
          - eapply consistent_pmap_ptp_gss; eauto; apply _x.
          - eapply consistent_pmap_domain_gso_at_false; eauto; try apply _x.
            eapply consistent_pmap_domain_ptp_unp; eauto.
            apply real_init_PTE_unp.
          - apply consistent_lat_domain_gss_nil; eauto.
            apply consistent_lat_domain_gso_p; eauto.
          - zmap_solve.
          - apply NotInQ_gso_true; auto.
        Qed.

        Lemma ptAllocPDE_low_level_inv:
          forall d d' n vadr v n',
            ptAllocPDE0_spec n vadr d = Some (d', v) ->
            low_level_invariant n' d ->
            low_level_invariant n' d'.
        Proof.
          intros. functional inversion H; subst; eauto.
          inv H0. constructor; eauto.
        Qed.

        Lemma ptAllocPDE_kernel_mode:
          forall d d' n vadr v,
            ptAllocPDE0_spec n vadr d = Some (d', v) ->
            kernel_mode d ->
            kernel_mode d'.
        Proof.
          intros. functional inversion H; subst; eauto.
        Qed.

      End PTALLOCPDE.

      Lemma ptInsert_high_level_inv:
        forall d d' n vadr padr p v,
          ptInsert0_spec n vadr padr p d = Some (d', v) ->
          high_level_invariant d ->
          high_level_invariant d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        - eapply ptInsertPTE_high_level_inv; eassumption.
        - eapply ptAllocPDE_high_level_inv; eassumption.
        - eapply ptInsertPTE_high_level_inv; try eassumption.
          eapply ptAllocPDE_high_level_inv; eassumption.
      Qed.

      Lemma ptInsert_low_level_inv:
        forall d d' n vadr padr p n' v,
          ptInsert0_spec n vadr padr p d = Some (d', v) ->
          low_level_invariant n' d ->
          low_level_invariant n' d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        - eapply ptInsertPTE_low_level_inv; eassumption.
        - eapply ptAllocPDE_low_level_inv; eassumption.
        - eapply ptInsertPTE_low_level_inv; try eassumption.
          eapply ptAllocPDE_low_level_inv; eassumption.
      Qed.

      Lemma ptInsert_kernel_mode:
        forall d d' n vadr padr p v,
          ptInsert0_spec n vadr padr p d = Some (d', v) ->
          kernel_mode d ->
          kernel_mode d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        - eapply ptInsertPTE_kernel_mode; eassumption.
        - eapply ptAllocPDE_kernel_mode; eassumption.
        - eapply ptInsertPTE_kernel_mode; try eassumption.
          eapply ptAllocPDE_kernel_mode; eassumption.
      Qed.

    End PTINSERT.

    Section PTRESV.

      Lemma ptResv_high_level_inv:
        forall d d' n vadr p v,
          ptResv_spec n vadr p d = Some (d', v) ->
          high_level_invariant d ->
          high_level_invariant d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        eapply ptInsert_high_level_inv; try eassumption.
        eapply alloc_high_level_inv; eassumption.
      Qed.

      Lemma ptResv_low_level_inv:
        forall d d' n vadr p n' v,
          ptResv_spec n vadr p d = Some (d', v) ->
          low_level_invariant n' d ->
          low_level_invariant n' d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        eapply ptInsert_low_level_inv; try eassumption.
        eapply alloc_low_level_inv; eassumption.
      Qed.

      Lemma ptResv_kernel_mode:
        forall d d' n vadr p v,
          ptResv_spec n vadr p d = Some (d', v) ->
          kernel_mode d ->
          kernel_mode d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        eapply ptInsert_kernel_mode; try eassumption.
        eapply alloc_kernel_mode; eassumption.
      Qed.

      Global Instance ptResv_inv: PreservesInvariants ptResv_spec.
      Proof.
        preserves_invariants_simpl'.
        - eapply ptResv_low_level_inv; eassumption.
        - eapply ptResv_high_level_inv; eassumption.
        - eapply ptResv_kernel_mode; eassumption.
      Qed.

    End PTRESV.

    Section OFFER_SHARE.

      Section PTRESV2.

        Lemma ptResv2_high_level_inv:
          forall d d' n vadr p n' vadr' p' v,
            ptResv2_spec n vadr p n' vadr' p' d = Some (d', v) ->
            high_level_invariant d ->
            high_level_invariant d'.
        Proof.
          intros; functional inversion H; subst; eauto;
          eapply ptInsert_high_level_inv; try eassumption.
          - eapply alloc_high_level_inv; eassumption.
          - eapply ptInsert_high_level_inv; try eassumption.
            eapply alloc_high_level_inv; eassumption.
        Qed.

        Lemma ptResv2_low_level_inv:
          forall d d' n vadr p n' vadr' p' l v,
            ptResv2_spec n vadr p n' vadr' p' d = Some (d', v) ->
            low_level_invariant l d ->
            low_level_invariant l d'.
        Proof.
          intros; functional inversion H; subst; eauto;
          eapply ptInsert_low_level_inv; try eassumption.
          - eapply alloc_low_level_inv; eassumption.
          - eapply ptInsert_low_level_inv; try eassumption.
            eapply alloc_low_level_inv; eassumption.
        Qed.

        Lemma ptResv2_kernel_mode:
          forall d d' n vadr p n' vadr' p' v,
            ptResv2_spec n vadr p n' vadr' p' d = Some (d', v) ->
            kernel_mode d ->
            kernel_mode d'.
        Proof.
          intros; functional inversion H; subst; eauto;
          eapply ptInsert_kernel_mode; try eassumption.
          - eapply alloc_kernel_mode; eassumption.
          - eapply ptInsert_kernel_mode; try eassumption.
            eapply alloc_kernel_mode; eassumption.
        Qed.

      End PTRESV2.

      Global Instance offer_shared_mem_inv:
        PreservesInvariants offer_shared_mem_spec.
      Proof.
        preserves_invariants_simpl';
        functional inversion H2; subst; eauto 2; try (inv H0; constructor; trivial; fail).
        - exploit ptResv2_low_level_inv; eauto.
          intros HP; inv HP. constructor; trivial.
        - exploit ptResv2_low_level_inv; eauto.
          intros HP; inv HP. constructor; trivial.
        - exploit ptResv2_high_level_inv; eauto.
          intros HP; inv HP. constructor; trivial.
        - exploit ptResv2_high_level_inv; eauto.
          intros HP; inv HP. constructor; trivial.
        - exploit ptResv2_kernel_mode; eauto.
        - exploit ptResv2_kernel_mode; eauto.
      Qed.

    End OFFER_SHARE.

    Global Instance shared_mem_status_inv:
      PreservesInvariants shared_mem_status_spec.
    Proof.
      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.
    Qed.

    Global Instance kctxt_switch_inv: KCtxtSwitchInvariants kctxt_switch_spec.
    Proof.
      constructor; intros; functional inversion H.
      - inv H1. constructor; trivial.
        eapply kctxt_inject_neutral_gss_mem; eauto.
      - inv H0. subst. constructor; auto; simpl in *; intros; try congruence.
    Qed.

    Global Instance kctxt_new_inv: DNewInvariants kctxt_new_spec.
    Proof.
      constructor; intros; inv H0;
      unfold ObjThread.kctxt_new_spec in *;
      subdestruct; inv H; simpl; auto.
      - (* low level invariant *)
        constructor; trivial; intros; simpl in *.
        eapply kctxt_inject_neutral_gss_flatinj'; eauto.
        eapply kctxt_inject_neutral_gss_flatinj; eauto.

      - (* high_level_invariant *)
        constructor; simpl; eauto 2; try congruence; intros.
        + exploit split_container_valid; eauto.
          eapply container_split_some; eauto.
          auto.
        + unfold update_cusage, update_cchildren; zmap_solve.
        + unfold update_cusage, update_cchildren; apply NotInQ_gso_true; auto.
          zmap_simpl; repeat apply NotInQ_gso_true; auto.
    Qed.

    Global Instance set_state_inv: PreservesInvariants set_state0_spec.
    Proof.
      preserves_invariants_simpl low_level_invariant high_level_invariant; auto 2.
      - eapply AbTCBCorrect_range_gss; eauto.
        eapply AbTCBCorrect_range_valid_b; eauto.
      - eapply NotInQ_gso_state; eauto.
      - eapply QCount_gso_state; eauto.
      - eapply InQ_gso_state; eauto.
    Qed.

    Global Instance tdqueue_init_inv: PreservesInvariants tdqueue_init0_spec.
    Proof.
      preserves_invariants_simpl low_level_invariant high_level_invariant.
      - apply real_nps_range.
      - apply real_lat_kern_valid.
      - apply real_lat_usr_valid.
      - apply real_container_valid.
      - rewrite init_pperm0; try assumption.
        apply Lreal_pperm_valid.
      - eapply real_pt_PMap_valid; eauto.
      - apply real_pt_PMap_kern.
      - omega.
      - assumption.
      - apply real_idpde_init.
      - apply real_pt_consistent_pmap.
      - apply real_pt_consistent_pmap_domain.
      - apply Lreal_at_consistent_lat_domain.
      - apply real_abtcb_range; auto.
      - apply real_abq_range; auto.
      - eapply real_abtcb_pb_notInQ; eauto.
      - eapply real_abtcb_abq_QCount; eauto.
      - eapply real_abq_tcb_inQ; eauto.
    Qed.

    Global Instance enqueue_inv: PreservesInvariants enqueue0_spec.
    Proof.
      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2;
      functional inversion H5.
      - eapply AbTCBCorrect_range_gss; eauto. omega.
      - eapply AbQCorrect_range_gss_enqueue; eauto.
      - eapply NotInQ_gso_ac; eauto.
      - eapply QCount_gss_enqueue; eauto.
      - eapply InQ_gss_enqueue; eauto.
    Qed.

    Global Instance dequeue_inv: PreservesInvariants dequeue0_spec.
    Proof.
      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.
      - eapply AbTCBCorrect_range_gss; eauto. omega.
      - eapply AbQCorrect_range_gss_remove; eauto.
      - eapply NotInQ_gso_neg; eauto.
      - eapply QCount_gss_remove; eauto.
        eapply last_range_AbQ; eauto.
      - eapply InQ_gss_remove; eauto.
        + eapply last_range_AbQ; eauto.
        + apply last_correct; auto.
    Qed.

    Global Instance queue_rmv_inv: PreservesInvariants queue_rmv0_spec.
    Proof.
      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2;
      functional inversion H5.
      - eapply AbTCBCorrect_range_gss; eauto. omega.
      - eapply AbQCorrect_range_gss_remove; eauto.
      - eapply NotInQ_gso_neg; eauto.
      - eapply QCount_gss_remove; eauto.
      - eapply InQ_gss_remove; eauto.
        eapply QCount_valid; eauto.
    Qed.

    Global Instance clearCR2_inv: PreservesInvariants clearCR2_spec.
    Proof.
      preserves_invariants_simpl low_level_invariant high_level_invariant; auto.
    Qed.

    (*Global Instance thread_free_inv: PreservesInvariants thread_free_spec.
    Proof.
      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.
      - destruct (zeq i0 (Int.unsigned i)); subst.
        + rewrite ZMap.gss. apply PT_init_common_pdt_usr.
          apply real_free_pt_valid; apply valid_PT_common0; auto.
        + rewrite ZMap.gso; auto.
      - destruct (zeq (Int.unsigned i) 0); subst. omega.
        rewrite ZMap.gso; auto.
      - destruct (zeq (Int.unsigned i) 0); subst. omega.
        rewrite ZMap.gso; auto.
      - unfold PTB_defined in *; intros.
        destruct (zeq (Int.unsigned i) i0); subst.
        rewrite ZMap.gss.
        red; intros HF; inv HF.
        rewrite ZMap.gso; auto.
      - destruct (zeq (Int.unsigned i) i0); subst.
        + rewrite ZMap.gss. unfold AbTCBCorrect in *.
          refine_split'; eauto; omega.
        + rewrite ZMap.gso; auto.
      - destruct (zeq (Int.unsigned i) i0); subst.
        + rewrite ZMap.gss in *. inv H12; trivial.
        + rewrite ZMap.gso in *; eauto.
      - destruct (zeq (Int.unsigned i) i0); subst.
        + rewrite ZMap.gss in *. inv H11. eauto.
        + rewrite ZMap.gso in *; eauto.
      - destruct (zeq (Int.unsigned i) i0); subst.
        + rewrite ZMap.gss.
          destruct (valid_inQ0 H4 _ _ _ H10 H11 H12 H13) as [s' HM].
          rewrite H8 in HM. inv HM. omega.
        + rewrite ZMap.gso; eauto.
    Qed.*)

    Global Instance flatmem_copy_inv: PreservesInvariants flatmem_copy_spec.
    Proof.
      preserves_invariants_simpl low_level_invariant high_level_invariant;
      try eapply dirty_ppage_gss_copy; eauto.
    Qed.

    Global Instance device_output_inv: PreservesInvariants device_output_spec.
    Proof.
      preserves_invariants_simpl'' low_level_invariant high_level_invariant; eauto.
    Qed.

  End INV.

  Definition exec_loadex {F V} := exec_loadex2 (F := F) (V := V).

  Definition exec_storeex {F V} :=  exec_storeex2 (flatmem_store:= flatmem_store) (F := F) (V := V).

  Global Instance flatmem_store_inv: FlatmemStoreInvariant (flatmem_store:= flatmem_store).
  Proof.
    split; inversion 1; intros.
    - functional inversion H0. split; trivial.
    - functional inversion H1.
      split; simpl; try (eapply dirty_ppage_store_unmaped'; try reflexivity; try eassumption); trivial.
  Qed.

  Global Instance trapinfo_set_inv: TrapinfoSetInvariant.
  Proof.
    split; inversion 1; intros; constructor; auto.
  Qed.

  (** * Layer Definition *)
  Definition pabqueue : compatlayer (cdata RData) :=
    fload ↦ gensem fload_spec
          ⊕ fstore ↦ gensem fstore_spec
          ⊕ flatmem_copy ↦ gensem flatmem_copy_spec
          ⊕ vmxinfo_get ↦ gensem vmxinfo_get_spec
          ⊕ device_output ↦ gensem device_output_spec
          ⊕ pfree ↦ gensem pfree_spec
          ⊕ set_pt ↦ gensem setPT_spec
          ⊕ pt_read ↦ gensem ptRead_spec
          ⊕ pt_resv ↦ gensem ptResv_spec
          ⊕ kctxt_new ↦ dnew_compatsem ObjThread.kctxt_new_spec
          (*⊕ pt_free ↦ gensem pt_free_spec*)
          ⊕ shared_mem_status ↦ gensem shared_mem_status_spec
          ⊕ offer_shared_mem ↦ gensem offer_shared_mem_spec

          ⊕ get_state ↦ gensem get_state0_spec
          ⊕ set_state ↦ gensem set_state0_spec
          ⊕ tdqueue_init ↦ gensem tdqueue_init0_spec
          ⊕ enqueue ↦ gensem enqueue0_spec
          ⊕ dequeue ↦ gensem dequeue0_spec
          ⊕ queue_rmv ↦ gensem queue_rmv0_spec

          ⊕ pt_in ↦ primcall_general_compatsem' ptin_spec (prim_ident:= pt_in)
          ⊕ pt_out ↦ primcall_general_compatsem' ptout_spec (prim_ident:= pt_out)
          ⊕ clear_cr2 ↦ gensem clearCR2_spec
          ⊕ container_get_nchildren ↦ gensem container_get_nchildren_spec
          ⊕ container_get_quota ↦ gensem container_get_quota_spec
          ⊕ container_get_usage ↦ gensem container_get_usage_spec
          ⊕ container_can_consume ↦ gensem container_can_consume_spec
          ⊕ container_alloc ↦ gensem alloc_spec
          ⊕ trap_in ↦ primcall_general_compatsem trapin_spec
          ⊕ trap_out ↦ primcall_general_compatsem trapout_spec
          ⊕ host_in ↦ primcall_general_compatsem hostin_spec
          ⊕ host_out ↦ primcall_general_compatsem hostout_spec
          ⊕ trap_get ↦ primcall_trap_info_get_compatsem trap_info_get_spec
          ⊕ trap_set ↦ primcall_trap_info_ret_compatsem trap_info_ret_spec
          ⊕ kctxt_switch ↦ primcall_kctxt_switch_compatsem kctxt_switch_spec
          ⊕ accessors ↦ {| exec_load := @exec_loadex; exec_store := @exec_storeex |}.

  (*Definition semantics := LAsm.Lsemantics pabqueue.*)

End WITHMEM.


Require Import RefProofDeps.
Require Import RData.
Require Import EventReplay.
Require Import MoverTypes.
Require Import Constants.
Require Import CommonLib.
Require Import RefTactics.
Require Import AbsAccessor.Spec.
Require Import TableAux2.Spec.
Require Import TableAux.Spec.
Require Import TableAux3.Specs.table_destroy_aux.
Require Import TableAux3.LowSpecs.table_destroy_aux.
Require Import TableAux3.RefProof.RefRel.

Local Open Scope string_scope.
Local Open Scope Z_scope.
Local Opaque Z.add Z.mul Z.div Z.shiftl Z.shiftr Z.land Z.lor.

Section Refine.

  Hint Unfold
       granule_map_spec
       get_g_rtt_refcount_spec
       table_delete_spec
       table_fold_spec
       pgte_write_spec
       invalidate_page_spec
       invalidate_pages_in_block_spec
       invalidate_block_spec
       granule_put_spec
       null_ptr_spec
       set_g_rtt_rd_spec
       granule_memzero_mapped_spec
       granule_memzero_spec
       granule_set_state_spec
       buffer_unmap_spec
    .

  Lemma table_destroy_aux_spec_exists:
    forall habd habd'  labd g_llt g_tbl ll_table level index map_addr res
      (Hspec: table_destroy_aux_spec g_llt g_tbl ll_table level index map_addr habd = Some (habd', res))
      (Hrel: relate_RData habd labd),
    exists labd', table_destroy_aux_spec0 g_llt g_tbl ll_table level index map_addr labd = Some (labd', res) /\ relate_RData habd' labd'.
  Proof.
    Local Opaque ptr_eq peq fill_table. pose proof orb_64_range as orr.
    pose proof IPA_PTE_IPA as ipi. pose proof IPA_PTE_IPA2 as ipi2.
    pose proof pte_4096_range as p4096.
    pose proof pte_2011_4096_range as p2_4096.
    intros. destruct Hrel. inv id_rdata. destruct g_llt, g_tbl, ll_table.
    unfold table_destroy_aux_spec, table_destroy_aux_spec0 in *; repeat autounfold in *.
    hsimpl_hyp Hspec; inv Hspec; extract_prop_dec.
    - simpl in *. grewrite. inv Prop2.
      match goal with
      | |- context [prop_dec (?a = ?a)] => destruct (prop_dec (a = a)); [ simpl | contra ]
      end.
      grewrite. solve_peq. simpl.
      repeat (grewrite; try simpl_htarget; simpl in * ).
      rewrite table_a5_d7. extract_if. bool_rel. grewrite. reflexivity. grewrite.
      extract_if. destruct_if; reflexivity. grewrite.
      rewrite ZMap.gso. repeat (grewrite; try simpl_htarget; simpl in * ).
      solve_bool_range. grewrite.
      destruct_if. destruct_if' Case; inversion Case.
      rewrite ZMap.gso. repeat (grewrite; try simpl_htarget; repeat simpl_field; repeat swap_fields; simpl).
      extract_if. bool_rel; grewrite. omega. grewrite. solve_peq.
      repeat (grewrite; try simpl_htarget; repeat simpl_field; repeat swap_fields; simpl).
      eexists; split. reflexivity. constructor.
      rewrite (zmap_comm _ _ Prop3). bool_rel. grewrite. simpl.
      destruct_if. reflexivity. reflexivity.
      red; intro T; inv T. red; intro T; inv T. destruct_if; reflexivity.
    - simpl in *. grewrite. inv Prop2.
      match goal with
      | |- context [prop_dec (?a = ?a)] => destruct (prop_dec (a = a)); [ simpl | contra ]
      end.
      grewrite. solve_peq. simpl.
      repeat (grewrite; try simpl_htarget; simpl in * ).
      solve_bool_range. grewrite. solve_bool_range. grewrite.
      extract_if. bool_rel; grewrite. omega. grewrite.
      extract_if. destruct_if. apply orb_64_range. autounfold. apply orb_64_range. autounfold.
      rewrite table_a5_d7_m7. reflexivity. apply Prop1. autounfold. apply entry_to_phys_range. apply Prop1. reflexivity.
      apply orb_64_range. autounfold. rewrite table_a5_d7_m7. reflexivity.
      apply Prop1. autounfold. apply entry_to_phys_range. apply Prop1. grewrite.
      repeat (grewrite; try simpl_htarget; repeat simpl_field; repeat swap_fields; simpl).
      rewrite ZMap.gso. repeat (grewrite; try simpl_htarget; repeat simpl_field; repeat swap_fields; simpl).
      solve_bool_range. grewrite. solve_bool_range. grewrite.
      destruct (Z.land (g_data (gnorm (gs (share labd)) @ z0)) @ 0 504403158265495552 / 72057594037927936 =? 2) eqn:ipa.
      + rewrite ipi. grewrite. rewrite ZMap.gso. grewrite.
        simpl_htarget. grewrite. simpl. simpl_htarget.
        extract_if. bool_rel. grewrite. omega. grewrite. simpl.
        repeat simpl_field; repeat swap_fields; simpl_htarget. solve_peq.
        simpl. simpl_htarget. repeat simpl_field; repeat swap_fields; simpl_htarget.
        repeat rewrite (zmap_comm _ _ Prop4).
        simpl. simpl_htarget. repeat simpl_field; repeat swap_fields; simpl_htarget.
        eexists. split. reflexivity. constructor. bool_rel. grewrite. simpl. reflexivity.
        red; intro T; inv T. apply Prop1. apply Prop1. omega.
      + rewrite ipi2. grewrite. rewrite ZMap.gso. grewrite.
        simpl_htarget. grewrite. simpl. simpl_htarget.
        extract_if. bool_rel. grewrite. omega. grewrite. simpl.
        repeat simpl_field; repeat swap_fields; simpl_htarget. solve_peq.
        simpl. simpl_htarget. repeat simpl_field; repeat swap_fields; simpl_htarget.
        repeat rewrite (zmap_comm _ _ Prop4).
        simpl. simpl_htarget. repeat simpl_field; repeat swap_fields; simpl_htarget.
        eexists. split. reflexivity. constructor. bool_rel. grewrite. simpl. reflexivity.
        red; intro T; inv T. apply Prop1. apply Prop1.
      + red; intro T; inv T.
  Qed.

End Refine.


From iris.proofmode Require Import proofmode.
From lrust.typing Require Import typing.
From iris.prelude Require Import options.

Section get_x.
  Context `{!typeGS Σ}.

  Definition get_x : val :=
    fn: ["p"] :=
       let: "p'" := !"p" in
       letalloc: "r" <- "p'" +ₗ #0 in
       delete [ #1; "p"] ;; return: ["r"].

  Lemma get_x_type :
    typed_val get_x (fn(∀ α, ∅; &uniq{α}(Π[int; int])) → &shr{α}int).
  Proof.
    intros E L. iApply type_fn; [solve_typing..|]. iIntros "/= !>". iIntros (α ϝ ret p).
    inv_vec p=>p. simpl_subst.
    iApply type_deref; [solve_typing..|]. iIntros (p'); simpl_subst.
    iApply (type_letalloc_1 (&shr{α}int)); [solve_typing..|]. iIntros (r). simpl_subst.
    iApply type_delete; [solve_typing..|].
    iApply type_jump; solve_typing.
  Qed.
End get_x.


Require Import HoareDef IntroHeader IntroF1 IntroFSep2 SimModSem.
Import Sep.
Require Import Coqlib.
Require Import ImpPrelude.
Require Import Skeleton.
Require Import PCM.
Require Import ModSem Behavior.
Require Import Relation_Definitions.

(*** TODO: export these in Coqlib or Universe ***)
Require Import Relation_Operators.
Require Import RelationPairs.
From ITree Require Import
     Events.MapDefault.
From ExtLib Require Import
     Core.RelDec
     Structures.Maps
     Data.Map.FMapAList.

Require Import HTactics ProofMode.

Set Implicit Arguments.

Local Open Scope nat_scope.

Section SIMMODSEM.

  Context `{Σ: GRA.t}.
  Context `{@GRA.inG IRA.t Σ}.

  Let W: Type := Any.t * Any.t.

  Let wf: _ -> W -> Prop :=
    @mk_wf
      _
      unit
      (fun _ _ _ => ⌜True⌝%I)
  .

  Theorem correct: refines2 [IntroF1.F] [IntroFSep2.F].
  Proof.
    eapply adequacy_local2. econs; ss.
    i. econstructor 1 with (wf:=wf) (le:=top2); et; swap 2 3.
    { ss. }
    { esplits. econs; ss. eapply to_semantic. iIntros "H". iSplits; ss. }

    econs; ss. init. harg. mDesAll.
    des; clarify. unfold fF, ccallU. steps. astart 10. force_r. exists x. steps. force_r; ss. steps.
    unfold Ncall. steps. des_ifs.
    - unfold ccallU. steps. acatch. des. hcall _ _ with "*"; auto.
      { esplits; ss; et. }
      steps. astop. ss. steps. mDesAll; clarify. rewrite Any.upcast_downcast. ss. steps.
      force_r; ss. steps. force_l. esplits. steps. hret _; ss.
      { iModIntro. iFrame. iSplits; ss; et. }
    - steps. astop. steps. force_l. esplits. steps.
      mAssert _ with "A".
      { iApply (OwnM_Upd with "A"). instantiate (1:=IRA.client false). r. clear_until H.
        ur. i. des_ifs.
      }
      hret _; ss.
      { iMod "A1". iModIntro. iFrame. iSplits; ss; et. }
  Unshelve. all: ss. all: try exact 0.
  Qed.

End SIMMODSEM.


Require Import LayerDeps.
Require Import Ident.
Require Import RData.
Require Import EventReplay.
Require Import MoverTypes.
Require Import Constants.
Require Import CommonLib.
Require Import AbsAccessor.Spec.
Require Import BaremoreHandler.Spec.
Require Import TableAux3.Spec.
Require Import RmiSMC.Spec.
Require Import TableAux.Spec.
Require Import RunSMC.Spec.
Require Import TableWalk.Spec.

Local Open Scope Z_scope.

Section Layer.

  Context `{real_params: RealParams}.

  Section InvDef.

    Record high_level_invariant (adt: RData) :=
      mkInvariants { }.

    Global Instance TableWalk_ops : CompatDataOps RData :=
      {
        empty_data := empty_adt;
        high_level_invariant := high_level_invariant;
        low_level_invariant := fun (b: block) (d: RData) => True;
        kernel_mode adt := True
      }.

  End InvDef.

  Section InvInit.

    Global Instance TableWalk_prf : CompatData RData.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

  End InvInit.

  Context `{Hstencil: Stencil}.
  Context `{Hmem: Mem.MemoryModelX}.
  Context `{Hmwd: UseMemWithData mem}.

  Section InvProof.

    Global Instance table_walk_lock_unlock_inv: PreservesInvariants table_walk_lock_unlock_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance set_mapping_inv: PreservesInvariants set_mapping_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance el3_sync_lel_inv: PreservesInvariants el3_sync_lel_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance ns_granule_map_inv: PreservesInvariants ns_granule_map_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance granule_get_inv: PreservesInvariants granule_get_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance buffer_unmap_inv: PreservesInvariants buffer_unmap_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance table_destroy_aux_inv: PreservesInvariants table_destroy_aux_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance granule_unlock_inv: PreservesInvariants granule_unlock_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance enter_rmm_inv: PreservesInvariants enter_rmm_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance smc_granule_delegate_inv: PreservesInvariants smc_granule_delegate_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance granule_put_inv: PreservesInvariants granule_put_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance exit_rmm_inv: PreservesInvariants exit_rmm_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance invalidate_page_inv: PreservesInvariants invalidate_page_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance smc_granule_undelegate_inv: PreservesInvariants smc_granule_undelegate_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance granule_set_state_inv: PreservesInvariants granule_set_state_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance entry_is_table_inv: PreservesInvariants entry_is_table_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance smc_rec_destroy_inv: PreservesInvariants smc_rec_destroy_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance get_wi_g_llt_inv: PreservesInvariants get_wi_g_llt_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance smc_rec_create_inv: PreservesInvariants smc_rec_create_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance granule_map_inv: PreservesInvariants granule_map_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance smc_rec_run_inv: PreservesInvariants smc_rec_run_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance invalidate_block_inv: PreservesInvariants invalidate_block_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance granule_memzero_inv: PreservesInvariants granule_memzero_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance read_reg_inv: PreservesInvariants read_reg_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance find_lock_granule_inv: PreservesInvariants find_lock_granule_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance is_null_inv: PreservesInvariants is_null_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance assert_cond_inv: PreservesInvariants assert_cond_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance ns_buffer_unmap_inv: PreservesInvariants ns_buffer_unmap_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance granule_memzero_mapped_inv: PreservesInvariants granule_memzero_mapped_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance pgte_read_inv: PreservesInvariants pgte_read_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance ns_buffer_read_data_inv: PreservesInvariants ns_buffer_read_data_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance table_create_aux_inv: PreservesInvariants table_create_aux_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance pgte_write_inv: PreservesInvariants pgte_write_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance validate_table_commands_inv: PreservesInvariants validate_table_commands_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance get_rd_state_inv: PreservesInvariants get_rd_state_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance find_granule_inv: PreservesInvariants find_granule_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance smc_realm_create_inv: PreservesInvariants smc_realm_create_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance user_step_inv: PreservesInvariants user_step_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance get_wi_index_inv: PreservesInvariants get_wi_index_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance smc_realm_activate_inv: PreservesInvariants smc_realm_activate_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

    Global Instance smc_realm_destroy_inv: PreservesInvariants smc_realm_destroy_spec.
    Proof.
      constructor; intros; simpl; eauto.
      constructor.
    Qed.

  End InvProof.

  Section LayerDef.

    Definition TableWalk_fresh : compatlayer (cdata RData) :=
      _table_walk_lock_unlock ↦ gensem table_walk_lock_unlock_spec
      .

    Definition TableWalk_passthrough : compatlayer (cdata RData) :=
      _set_mapping ↦ gensem set_mapping_spec
        ⊕ _el3_sync_lel ↦ gensem el3_sync_lel_spec
        ⊕ _ns_granule_map ↦ gensem ns_granule_map_spec
        ⊕ _granule_get ↦ gensem granule_get_spec
        ⊕ _buffer_unmap ↦ gensem buffer_unmap_spec
        ⊕ _table_destroy_aux ↦ gensem table_destroy_aux_spec
        ⊕ _granule_unlock ↦ gensem granule_unlock_spec
        ⊕ _enter_rmm ↦ gensem enter_rmm_spec
        ⊕ _smc_granule_delegate ↦ gensem smc_granule_delegate_spec
        ⊕ _granule_put ↦ gensem granule_put_spec
        ⊕ _exit_rmm ↦ gensem exit_rmm_spec
        ⊕ _invalidate_page ↦ gensem invalidate_page_spec
        ⊕ _smc_granule_undelegate ↦ gensem smc_granule_undelegate_spec
        ⊕ _granule_set_state ↦ gensem granule_set_state_spec
        ⊕ _entry_is_table ↦ gensem entry_is_table_spec
        ⊕ _smc_rec_destroy ↦ gensem smc_rec_destroy_spec
        ⊕ _get_wi_g_llt ↦ gensem get_wi_g_llt_spec
        ⊕ _smc_rec_create ↦ gensem smc_rec_create_spec
        ⊕ _granule_map ↦ gensem granule_map_spec
        ⊕ _smc_rec_run ↦ gensem smc_rec_run_spec
        ⊕ _invalidate_block ↦ gensem invalidate_block_spec
        ⊕ _granule_memzero ↦ gensem granule_memzero_spec
        ⊕ _read_reg ↦ gensem read_reg_spec
        ⊕ _find_lock_granule ↦ gensem find_lock_granule_spec
        ⊕ _is_null ↦ gensem is_null_spec
        ⊕ _assert_cond ↦ gensem assert_cond_spec
        ⊕ _ns_buffer_unmap ↦ gensem ns_buffer_unmap_spec
        ⊕ _granule_memzero_mapped ↦ gensem granule_memzero_mapped_spec
        ⊕ _pgte_read ↦ gensem pgte_read_spec
        ⊕ _ns_buffer_read_data ↦ gensem ns_buffer_read_data_spec
        ⊕ _table_create_aux ↦ gensem table_create_aux_spec
        ⊕ _pgte_write ↦ gensem pgte_write_spec
        ⊕ _validate_table_commands ↦ gensem validate_table_commands_spec
        ⊕ _get_rd_state ↦ gensem get_rd_state_spec
        ⊕ _find_granule ↦ gensem find_granule_spec
        ⊕ _smc_realm_create ↦ gensem smc_realm_create_spec
        ⊕ _user_step ↦ gensem user_step_spec
        ⊕ _get_wi_index ↦ gensem get_wi_index_spec
        ⊕ _smc_realm_activate ↦ gensem smc_realm_activate_spec
        ⊕ _smc_realm_destroy ↦ gensem smc_realm_destroy_spec
      .

    Definition TableWalk := TableWalk_fresh ⊕ TableWalk_passthrough.

  End LayerDef.

End Layer.


(*
 * Copyright (c) 2020-2023 BedRock Systems, Inc.
 * This software is distributed under the terms of the BedRock Open-Source License.
 * See the LICENSE-BedRock file in the repository root for details.
 *)
Require Import iris.proofmode.proofmode.

From bedrock.lang.cpp Require Import ast semantics.
From bedrock.lang.cpp.logic Require Import
     pred path_pred heap_pred destroy
     wp initializers.
Require Import bedrock.lang.bi.errors.

Module Type Stmt.
  #[local] Arguments wp_test [_ _ _] _ _ _.

  (** weakest pre-condition for statements
   *)
  Section with_resolver.
    Context `{Σ : cpp_logic thread_info} {σ : genv}.
    Variable (tu : translation_unit).

    #[local] Notation wp := (wp tu).
    #[local] Notation interp := (interp tu).
    #[local] Notation wp_initialize := (wp_initialize tu).
    #[local] Notation default_initialize := (default_initialize tu).

    Implicit Types Q : Kpred.

    Definition Kseq (Q : Kpred -> mpred) (k : Kpred) : Kpred :=
      KP (funI rt =>
          match rt with
          | Normal => Q k
          | rt => k rt
          end).
    #[global] Instance Kseq_mono : Proper (((⊢) ==> (⊢)) ==> (⊢) ==> (⊢)) Kseq.
    Proof.
      constructor => rt; rewrite /Kseq/KP/=.
      destruct rt; try apply H; apply H0.
    Qed.

    Definition Kfree (free : FreeTemp) : Kpred -> Kpred :=
      Kat_exit (interp free).

    Lemma Kfree_frame free Q Q' rt :
      Q rt -* Q' rt |-- Kfree free Q rt -* Kfree free Q' rt.
    Proof.
      iIntros "X". iApply Kat_exit_frame => //.
      iIntros (??) "H"; by iApply interp_frame.
    Qed.

    (** * Expression Evaluation *)

    Axiom wp_expr : forall ρ e Q,
        |> wp_discard tu ρ e (fun free => interp free (Q Normal))
        |-- wp ρ (Sexpr e) Q.

    (** * Declarations *)

    (* This definition performs allocation of local variables.
     *
     * note that references do not allocate anything in the semantics, they are
     * just aliases.
     *
     * TODO there is a lot of overlap between this and [wp_initialize] (which does initialization
     * of aggregate fields).
     *)
    Definition wp_decl_var (ρ ρ_init : region) (x : ident) (ty : type) (init : option Expr)
               (k : region -> FreeTemp -> epred)
      : mpred :=
      Forall (addr : ptr),
        let destroy frees :=
            interp frees (k (Rbind x addr ρ) (FreeTemps.delete ty addr))
        in
        match init with
        | Some init => wp_initialize ρ_init ty addr init $ fun frees => destroy frees
        | None => default_initialize ty addr (fun frees => destroy frees)
        end.

    Lemma wp_decl_var_frame : forall x ρ ρ_init init ty (k k' : region -> FreeTemps -> epred),
        Forall a (b : _), k a b -* k' a b
        |-- wp_decl_var ρ ρ_init x ty init k -* wp_decl_var ρ ρ_init x ty init k'.
    Proof.
      rewrite /wp_decl_var; intros.
      iIntros "X Y" (addr); iSpecialize ("Y" $! addr); iRevert "Y".
      case_match;
        [ iApply wp_initialize_frame | iApply default_initialize_frame ];
        iIntros (?); iApply interp_frame; iApply "X".
    Qed.

    (* An error used to say that thread safe initializers are not supported *)
    Record thread_safe_initializer (d : VarDecl) : Prop := {}.

    Fixpoint wp_decl (ρ ρ_init : region) (d : VarDecl) (k : region -> FreeTemps -> epred) {struct d} : mpred :=
      match d with
      | Dvar x ty init => wp_decl_var ρ ρ_init x ty init k
      | Ddecompose init x ds =>
        wp_decl_var ρ_init ρ_init x (type_of init) (Some init) (fun ρ_init' free =>
          (fix continue ds ρ k free :=
             match ds with
             | nil => k ρ free
             | d :: ds => wp_decl ρ ρ_init' d (fun ρ free' => continue ds ρ k (FreeTemps.seq free' free))
             end) ds ρ k free)
      | Dinit ts nm ty init =>
        let do_init :=
            match init with
            | None => default_initialize ty (_global nm) (k ρ)
            | Some init => wp_initialize ρ_init ty (_global nm) init (k ρ)
            end
        in
        if ts then
          UNSUPPORTED (thread_safe_initializer d)
        else
          _global nm |-> tblockR ty (cQp.mut 1) ** do_init
      end.

    Lemma wp_decl_frame : forall ds ρ ρ_init m m',
        Forall a b, m a b -* m' a b
        |-- wp_decl ρ ρ_init ds m -* wp_decl ρ ρ_init ds m'.
    Proof.
      refine (fix IH ds := _); destruct ds; simpl; intros.
      { iIntros "X"; by iApply wp_decl_var_frame. }
      { iIntros "A". iApply wp_decl_var_frame.
        iStopProof.
        generalize dependent ρ; generalize dependent m. induction l; intros.
        { iIntros "X" (??) "Y". iApply "X". eauto. }
        { iIntros "x" (??). iApply IH.
          iIntros (??) "Z". iRevert "Z". iApply (IHl with "x"); eauto. } }
      { case_match; eauto.
        case_match.
        { iIntros "? [$ X]"; iRevert "X"; iApply wp_initialize_frame => //; iIntros (?); done. }
        { iIntros "? [$ X]"; iRevert "X"; iApply default_initialize_frame => //. } }
    Qed.

    Fixpoint wp_decls (ρ ρ_init : region) (ds : list VarDecl)
             (k : region -> FreeTemps -> epred) : mpred :=
      match ds with
      | nil => k ρ FreeTemps.id
      | d :: ds => |> wp_decl ρ ρ_init d (fun ρ free => wp_decls ρ ρ_init ds (fun ρ' free' => k ρ' (FreeTemps.seq free' free)))
      end.

    Lemma wp_decls_frame : forall ds ρ ρ_init (Q Q' : region -> FreeTemps -> epred),
        Forall a (b : _), Q a b -* Q' a b
        |-- wp_decls ρ ρ_init ds Q -* wp_decls ρ ρ_init ds Q'.
    Proof.
      induction ds; simpl; intros.
      - iIntros "a"; iApply "a".
      - iIntros "a b"; iNext; iRevert "b".
        iApply wp_decl_frame.
        iIntros (??). iApply IHds. iIntros (??) "X". by iApply "a".
    Qed.

    (** * Blocks *)

    Fixpoint wp_block (ρ : region) (ss : list Stmt) (Q : Kpred) : mpred :=
      match ss with
      | nil => |> Q Normal
      | Sdecl ds :: ss =>
        wp_decls ρ ρ ds (fun ρ free => |> wp_block ρ ss (Kfree free Q))
      | s :: ss =>
        |> wp ρ s (Kseq (wp_block ρ ss) Q)
      end.

    Lemma wp_block_frame : forall body ρ (Q Q' : Kpred),
        (Forall rt, Q rt -* Q' rt) |-- wp_block ρ body Q -* wp_block ρ body Q'.
    Proof.
      clear.
      induction body; simpl; intros.
      - iIntros "a b"; iNext; iApply "a"; eauto.
      - assert
          (Forall rt, Q rt -* Q' rt |--
                        (Forall ds, wp_decls ρ ρ ds (fun ρ' free => |> wp_block ρ' body (Kfree free Q)) -*
                                    wp_decls ρ ρ ds (fun ρ' free => |> wp_block ρ' body (Kfree free Q'))) //\\
                        (|> wp ρ a (Kseq (wp_block ρ body) Q) -*
                            |> wp ρ a (Kseq (wp_block ρ body) Q'))).
        { iIntros "X"; iSplit.
          - iIntros (ds).
            iApply wp_decls_frame. iIntros (??) "x"; iNext.
            iRevert "x"; iApply IHbody.
            iIntros (?); iApply Kfree_frame; iApply "X".
          - iIntros "x"; iNext; iRevert "x"; iApply wp_frame; first by reflexivity.
            iIntros (rt); destruct rt =>/=; eauto.
            by iApply IHbody. }
        iIntros "X".
        iDestruct (H with "X") as "X".
        destruct a; try solve [ iDestruct "X" as "[_ $]" ].
        iDestruct "X" as "[X _]". iApply "X".
    Qed.

    Axiom wp_seq : forall ρ Q ss,
        wp_block ρ ss Q |-- wp ρ (Sseq ss) Q.

    (** [if] *)

    Axiom wp_if : forall ρ e thn els Q,
        |> Unfold WPE.wp_test (wp_test tu ρ e (fun c free =>
               interp free $
               if c
               then wp ρ thn Q
               else wp ρ els Q))
      |-- wp ρ (Sif None e thn els) Q.

    Axiom wp_if_decl : forall ρ d e thn els Q,
        wp ρ (Sseq (Sdecl (d :: nil) :: Sif None e thn els :: nil)) Q
        |-- wp ρ (Sif (Some d) e thn els) Q.

    (** * Loops *)
    (* The loop rules are phrased using loop invariants. An alternative
     * is to use their 1-step unfoldings and a greatest-fixpoint.
     *
     * Inconsistency: Certain infinite loops can be optimized away
     * in C/C++. E.g. [while (1);] can be optimized to [;]. The loop
     * rules do not support these.
     *)

    (* loop with invariant `I` *)
    Definition Kloop (I : mpred) (Q : Kpred) : Kpred :=
      KP (funI rt =>
          match rt with
          | Break => Q Normal
          | Normal | Continue => I
          | rt => Q rt
          end).

    Axiom wp_while : forall ρ test body Q I,
        I |-- wp ρ (Sif None test body Sbreak) (Kloop I Q) ->
        I |-- wp ρ (Swhile None test body) Q.

    (**
       `while (T x = e) body` desugars to `{ T x = e; while (x) body }`
     *)
    Axiom wp_while_decl : forall ρ d test body Q,
            wp ρ (Sseq (Sdecl (d :: nil) :: Swhile None test body :: nil)) Q
        |-- wp ρ (Swhile (Some d) test body) Q.

    Axiom wp_for : forall ρ test incr body Q I,
        let incr_I :=
          match incr with
          | None => I
          | Some incr => wp_discard tu ρ incr (fun free => interp free I)
          end
        in
        match test with
        | None =>
          I |-- wp ρ body (Kloop incr_I Q)
        | Some test =>
          I |-- wp ρ (Sif None test body Sbreak) (Kloop incr_I Q)
        end ->
        I |-- wp ρ (Sfor None test incr body) Q.

    (**
       `for (init; test; incr) body` desugars to `{ init; for (; test; incr) body }`
     *)
    Axiom wp_for_init : forall ρ init test incr b Q,
            wp ρ (Sseq (init :: Sfor None test incr b :: nil)) Q
        |-- wp ρ (Sfor (Some init) test incr b) Q.

    (** ** `do` loops *)

    Definition Kdo (ρ : region) (e : Expr) (I : mpred) (Q : Kpred) : Kpred :=
      KP (funI rt =>
          match rt with
          | Break => Q Normal
          | Continue | Normal =>
            Unfold WPE.wp_test (wp_test tu ρ e (fun c free => interp free $ if c then I else Q Normal))
          | rt => Q rt
          end).

    Axiom wp_do : forall ρ test body Q I,
        I |-- wp ρ body (Kdo ρ test I Q) ->
        I |-- wp ρ (Sdo body test) Q.

    (** * Return *)

    (* the semantics of return is like an initialization
     * expression.
     *)
    Axiom wp_return_void : forall ρ Q,
        get_return_type ρ = Tvoid ->
        Q ReturnVoid |-- wp ρ (Sreturn None) Q.

    Axiom wp_return : forall ρ e (Q : Kpred),
          (let rty := erase_qualifiers (get_return_type ρ) in
           Forall p, wp_initialize ρ rty p e (fun frees =>
                                         interp frees (Q (ReturnVal p))))
           (* ^ NOTE discard [free] because we are extruding the scope of the value *)
       |-- wp ρ (Sreturn (Some e)) Q.

    Axiom wp_return_frame : forall ρ rv (Q Q' : Kpred),
        match rv with
        | None => Q ReturnVoid -* Q' ReturnVoid
        | Some _ =>
          (* NOTE unsound in the presence of exceptions *)
          Forall v, Q (ReturnVal v) -* Q' (ReturnVal v)
        end |-- wp ρ (Sreturn rv) Q -* wp ρ (Sreturn rv) Q'.

    (** * Control flow: `break`, `continue` *)

    Axiom wp_break : forall ρ Q,
        |> Q Break |-- wp ρ Sbreak Q.
    Axiom wp_break_frame : forall ρ (Q Q' : Kpred),
        Q Break -* Q' Break |-- wp ρ Sbreak Q -* wp ρ Sbreak Q'.

    Axiom wp_continue : forall ρ Q,
        |> Q Continue |-- wp ρ Scontinue Q.
    Axiom wp_continue_frame : forall ρ (Q Q' : Kpred),
        Q Continue -* Q' Continue |-- wp ρ Scontinue Q -* wp ρ Scontinue Q'.

    (** `switch` *)

    (* compute the [Prop] that is known if this switch branch is taken *)
    Definition wp_switch_branch (s : SwitchBranch) (v : Z) : Prop :=
      match s with
      | Exact i => v = i
      | Range low high => low <= v <= high
      end%Z.

    (* This performs a syntactic check on [s] to ensure that there are no [case] or [default]
       statements. This is used to avoid missing one of these statements which would compromise
       the soundness of [wp_switch_block]
     *)
    Fixpoint no_case (s : Stmt) : bool :=
      match s with
      | Sseq ls => forallb no_case ls
      | Sdecl _ => true
      | Sif _ _ a b => no_case a && no_case b
      | Swhile _ _ s => no_case s
      | Sfor _ _ _ s => no_case s
      | Sdo s _ => no_case s
      | Sattr _ s => no_case s
      | Sswitch _ _ _ => true
      | Scase _
      | Sdefault => false
      | Sbreak
      | Scontinue
      | Sreturn _
      | Sexpr _
      | Sasm _ _ _ _ _ => true
      | Slabeled _ s => no_case s
      | Sgoto _ => true
      | Sunsupported _ => false
      end.

    Fixpoint get_cases (ls : list Stmt) : list SwitchBranch :=
      match ls with
      | Scase sb :: ls =>
        sb :: get_cases ls
      | _ :: ls => get_cases ls
      | nil => nil
      end.

    Definition default_from_cases (ls : list SwitchBranch) (v : Z) : Prop :=
      (fold_right (fun sb P => ~wp_switch_branch sb v /\ P) True ls).

    (** apply the [wp] calculation to the body of a switch

        NOTE that the semantics of [switch] statements is *very* conservative in the
        current setup. In particular.

          1. We do not support using a [case] to jump over a variable declaration
          2. We do not support [case] statements that jump into the bodies of loops,
             i.e. Duft's device.

        Supporting 1 should not be difficult in principle.
        Full support for 2 seems to require a more sophisticated setup for [wp].
        In other work, this sort of thing is handled as essentially unstructured
        programs.

        We interpret the semantics of [wp_switch_block] by el
     *)
    Fixpoint wp_switch_block (Ldef : option (Z -> Prop)) (ls : list Stmt)
      : option (list ((Z -> Prop) * list Stmt)) :=
      match ls with
      | Scase sb :: ls =>
        (fun x => (wp_switch_branch sb, ls) :: x) <$> wp_switch_block Ldef ls
      | Sdefault :: ls =>
        match Ldef with
        | None =>
          (* NOTE in this case there were multiple [default] statements which is
             not legal *)
          None
        | Some def =>
          (fun x => (def, ls) :: x) <$> wp_switch_block None ls
        end
      | Sdecl _ :: ls' =>
        (* NOTE this check ensures that we never case past a declaration which
           could be problematic from a soundness point of view.
         *)
        if no_case (Sseq ls') then
          wp_switch_block Ldef ls'
        else
          None
      | s :: ls' =>
        if no_case s then
          wp_switch_block Ldef ls'
        else
          None
      | nil =>
        match Ldef with
        | None => Some nil
        | Some def => Some ((def, nil) :: nil)
        end
      end.

    Definition Kswitch (k : Kpred) : Kpred :=
      KP (fun rt =>
            match rt with
            | Break => k Normal
            | rt => k rt
            end).

    Axiom wp_switch_decl : forall ρ d e ls Q,
        wp ρ (Sseq (Sdecl (d :: nil) :: Sswitch None e ls :: nil)) Q
        |-- wp ρ (Sswitch (Some d) e ls) Q.

    (* An error to say that a `switch` block with [body] is not supported *)
    Record switch_block (body : list Stmt) : Prop := {}.

    Axiom wp_switch : forall ρ e b Q,
        match wp_switch_block (Some $ default_from_cases (get_cases b)) b with
        | None => UNSUPPORTED (switch_block b)
        | Some cases =>
          wp_operand tu ρ e (fun v free => interp free $
                    Exists vv : Z, [| v = Vint vv |] **
                    [∧list] x ∈ cases, [| x.1 vv |] -* wp_block ρ x.2 (Kswitch Q))
        end
        |-- wp ρ (Sswitch None e (Sseq b)) Q.

    (* note: case and default statements are only meaningful inside of [switch].
     * this is handled by [wp_switch_block].
     *)
    Axiom wp_case : forall ρ sb Q, Q Normal |-- wp ρ (Scase sb) Q.
    Axiom wp_default : forall ρ Q, Q Normal |-- wp ρ Sdefault Q.

  End with_resolver.

  (* ideally, we would like to use the following line, but [cbn] does not seem to
       like the !.
      Arguments wp_decl_var _ _ _ _ !_ _ /. *)
  #[global] Arguments wp_decl_var _ _ _ _ _ _ _ _ _ /.
  #[global] Arguments wp_decl _ _ _ _ _ _ _ /. (* ! should occur on [d] *)

End Stmt.

Declare Module S : Stmt.

Export S.


From sflib Require Import sflib.
From Paco Require Import paco.

From PromisingLib Require Import Axioms.
From PromisingLib Require Import Basic.
From PromisingLib Require Import Loc.
From PromisingLib Require Import DataStructure.
From PromisingLib Require Import DenseOrder.
From PromisingLib Require Import Language.
From PromisingLib Require Import Event.

Require Import Time.
Require Import View.
Require Import BoolMap.
Require Import Promises.
Require Import Cell.
Require Import Memory.
Require Import Global.
Require Import TView.
Require Import Local.
Require Import Thread.
Require Import Configuration.

Require Import SimLocal.
Require Import SimMemory.
Require Import SimGlobal.
Require Import SimThread.
Require Import Compatibility.

Require Import ITreeLang.
Require Import ITreeLib.

Set Implicit Arguments.

Lemma intro_choose_sim_itree (v: Const.t):
  sim_itree eq
            (Ret tt)
            (ITree.trigger MemE.choose;; Ret tt).
Proof.
  unfold trigger. rewrite bind_vis.
  pcofix CIH. ii. pfold. ii. splits; i.
  { inv TERMINAL_TGT. ss. }
  { right. esplits; eauto.
    rewrite sim_local_promises_bot; eauto.
  }
  ii. right.
  inv STEP_TGT; ss.
  - (* internal *)
    exploit sim_local_internal; eauto. i. des.
    esplits; try apply GL2; eauto. inv LOCAL0; ss.
  - (* choose *)
    inv LOCAL0; dependent destruction STATE.
    esplits; [|refl|econs 1|..]; ss.
    left. rewrite bind_ret_l. eapply paco9_mon; [apply sim_itree_ret|]; ss.
Qed.


From cap_machine Require Export logrel.
From iris.proofmode Require Import proofmode.
From iris.program_logic Require Import weakestpre adequacy lifting.
From stdpp Require Import base.
From cap_machine.ftlr Require Import ftlr_base.
From cap_machine.rules Require Import rules_base rules_Mov.

Section fundamental.
  Context {Σ:gFunctors} {memg:memG Σ} {regg:regG Σ} {sealsg: sealStoreG Σ}
          {nainv: logrel_na_invs Σ}
          `{MachineParameters}.

  Notation D := ((leibnizO Word) -n> iPropO Σ).
  Notation R := ((leibnizO Reg) -n> iPropO Σ).
  Implicit Types w : (leibnizO Word).
  Implicit Types interp : (D).

  Lemma mov_case (r : leibnizO Reg) (p : Perm)
        (b e a : Addr) (w : Word) (dst : RegName) (src : Z + RegName) (P : D):
    ftlr_instr r p b e a w (Mov dst src) P.
  Proof.
    intros Hp Hsome i Hbae Hi.
    iIntros "#IH #Hinv #Hinva #Hreg #Hread Hown Ha HP Hcls HPC Hmap".
    rewrite delete_insert_delete.
    iDestruct ((big_sepM_delete _ _ PC) with "[HPC Hmap]") as "Hmap /=";
      [apply lookup_insert|rewrite delete_insert_delete;iFrame|]. simpl.
    iApply (wp_Mov with "[$Ha $Hmap]"); eauto.
    { simplify_map_eq; auto. }
    { rewrite /subseteq /map_subseteq /set_subseteq_instance. intros rr _.
      apply elem_of_dom. apply lookup_insert_is_Some'; eauto. }

    iIntros "!>" (regs' retv). iDestruct 1 as (HSpec) "[Ha Hmap]".
    destruct HSpec; cycle 1.
    { iApply wp_pure_step_later; auto.
      iMod ("Hcls" with "[Ha HP]"); [iExists w; iFrame|iModIntro]. iNext.
      iIntros "_".
      iApply wp_value; auto. iIntros; discriminate. }
    { (* TODO: it might be possible to refactor the proof below by using more simplify_map_eq *)
      (* TODO: use incrementPC_inv *)
      match goal with
      | H: incrementPC _ = Some _ |- _ => apply incrementPC_Some_inv in H as (p''&b''&e''&a''& ? & HPC & Z & Hregs')
      end. simplify_map_eq.
      iApply wp_pure_step_later; auto.
      iMod ("Hcls" with "[Ha HP]"); [iExists w; iFrame|iModIntro].
      iNext.
      destruct (reg_eq_dec dst PC).
      { subst dst. rewrite lookup_insert in HPC. inv HPC.
        repeat rewrite insert_insert.
        destruct src; simpl in *; try discriminate.
        destruct (reg_eq_dec PC r0).
        { subst r0. simplify_map_eq.
          iIntros "_".
          iApply ("IH" $! r with "[%] [] [Hmap] [$Hown]"); try iClear "IH"; eauto.
          iModIntro. rewrite !fixpoint_interp1_eq /=. destruct Hp as [-> | ->]; iFrame "Hinv". }
        { simplify_map_eq.
          iDestruct ("Hreg" $! r0 _ _ H0) as "Hr0".
          destruct (PermFlowsTo RX p'') eqn:Hpft; iIntros "_".
          - iApply ("IH" $! r with "[%] [] [Hmap] [$Hown]"); try iClear "IH"; eauto.
            + iModIntro.
              destruct p''; simpl in Hpft; try discriminate; repeat (rewrite fixpoint_interp1_eq); simpl; auto.
          - iApply (wp_bind (fill [SeqCtx])).
            iDestruct ((big_sepM_delete _ _ PC) with "Hmap") as "[HPC Hmap]"; [apply lookup_insert|].
            iApply (wp_notCorrectPC with "HPC"); [eapply not_isCorrectPC_perm; destruct p''; simpl in Hpft; try discriminate; eauto|].
            iNext. iIntros "HPC /=".
            iApply wp_pure_step_later; auto.
            iNext; iIntros "_".
            iApply wp_value.
            iIntros. discriminate. } }
      { rewrite lookup_insert_ne in HPC; auto.
        rewrite lookup_insert in HPC. inv HPC.
        iIntros "_".
        iApply ("IH" $! (<[dst:=w0]> _) with "[%] [] [Hmap] [$Hown]"); eauto.
        - intros; simpl.
          rewrite lookup_insert_is_Some.
          destruct (reg_eq_dec dst x0); auto; right; split; auto.
          rewrite lookup_insert_is_Some.
          destruct (reg_eq_dec PC x0); auto; right; split; auto.
       - iIntros (ri v Hri Hvs).
          destruct (reg_eq_dec ri dst).
          + subst ri. rewrite lookup_insert in Hvs.
            destruct src; simplify_map_eq.
            * repeat rewrite fixpoint_interp1_eq; auto.
            * destruct (reg_eq_dec PC r0).
              { subst r0.
                - simplify_map_eq.
                  rewrite !fixpoint_interp1_eq /=.
                destruct Hp as [Hp | Hp]; subst p''; try subst g'';
                  (iFrame "Hinv Hexec"). }
              simplify_map_eq.
              iDestruct ("Hreg" $! r0 _ _ H0) as "Hr0". auto.
          + repeat rewrite lookup_insert_ne in Hvs; auto.
            iApply "Hreg"; auto.
        - iModIntro. rewrite !fixpoint_interp1_eq /=. destruct Hp as [-> | ->]; iFrame "Hinv".
      }
    }
    Unshelve. all: auto.
  Qed.

End fundamental.


Require Import List Ascii.
Require Import Ynot.
Require Import IO Net.

(* todo what does Warning: Trying to mask the absolute name "IO" mean *)

Open Local Scope hprop_scope.
Open Local Scope stsepi_scope.

Set Implicit Arguments.

Ltac rwpack X H := idtac;
  match X with
    | [_]%inhabited => idtac
    | _ =>
      match goal with
        | [ H' : X = [_]%inhabited |- _ ] => rewrite -> H' in H
        | [ H' : [_]%inhabited = X |- _ ] => rewrite -> H' in H
      end
  end.

Ltac rcombine := idtac;
  match goal with
    | [ H : (inhabit_unpack ?X _) = [_]%inhabited |- _ ] =>
      rwpack X H; simpl in H; rewrite <- (pack_injective H)
    | [ H : (inhabit_unpack2 ?X ?Y _) = [_]%inhabited |- _ ] =>
      rwpack X H; rwpack Y H; simpl in H; rewrite <- (pack_injective H)
  end.

Module Type EXECPARAMS.

  Parameter ccorrect : forall (req : list ascii), Trace -> Prop.
  Parameter reply : list ascii -> list ascii -> Prop.

  Parameter io : forall (req : list ascii) (tr : [Trace]),
    STsep (tr ~~ traced tr)
          (fun r:(list ascii * [Trace])=> tr ~~ tr' :~~ (snd r) in traced (tr' ++ tr) * [reply req (fst r)] * [ccorrect req tr']).

End EXECPARAMS.

Module ExecModel(A : EXECPARAMS).
  Export A.

  (* This correctness criteria says that we respond
     to correct requests *)
  Inductive correct (local: Net.SockAddr) : IO.Trace -> Prop :=
  | NilCorrect   : correct local nil
  | ConsCorrect  : forall remote past interim req resp, reply req resp -> correct local past ->
    ccorrect req interim -> correct local (UDP.Sent local remote resp :: interim ++ UDP.Recd local remote req :: past).

  (* A type for an exec server loop. *)
  Definition exec_server_t local := IO.server_t (correct local) (NilCorrect local).

End ExecModel.

Lemma nil_cons_app : forall (A : Type) (l2 : list A) (a : A) (l1 : list A),
  (l1 ++ a :: nil) ++ l2 = l1 ++ a :: l2.
  induction l1; auto. simpl. rewrite IHl1. auto.
Qed.

Module ExecImpl(A : EXECPARAMS).
  Module A := A.
  Module AL := ExecModel(A).
  Import AL.
  Import A.

  Definition iter : forall (local: Net.SockAddr) (tr: [IO.Trace]),
    STsep (tr ~~ IO.traced tr * [correct local tr])
          (fun r:[IO.Trace] => tr ~~ r ~~ [correct local (r ++ tr)] * [r <> nil] * IO.traced (r ++ tr)).
(**
            Exists remote :@ Net.SockAddr, Exists s :@ list ascii, Exists rp :@ list ascii, Exists it :@ Trace, [reply s rp] *
            [r = Net.UDP.Sent local remote rp :: it ++ Net.UDP.Recd local remote s :: nil] * IO.traced (r ++ tr)).
**)
  refine (fun local tr =>
    x <- Net.UDP.recv local tr <@> _;
    rtr <- io (snd x) (tr ~~~ UDP.Recd local (fst x) (snd x) :: tr) <@> _;
    UDP.send local (fst x) (fst rtr)
        (inhabit_unpack2 tr (snd rtr) (fun tr it => it ++ UDP.Recd local (fst x) (snd x) :: tr)) <@> _;;
    {{Return (inhabit_unpack (snd rtr) (fun it => UDP.Sent local (fst x) (fst rtr) :: it ++ UDP.Recd local (fst x) (snd x) :: nil))}}).
  solve [ inhabiter; unpack_conc; canceler; sep fail auto ].
  solve [ sep fail auto ].
  solve [ inhabiter; unpack_conc; repeat rcombine; canceler; sep fail auto ].
  solve [ sep fail auto ].
  inhabiter; unpack_conc; destruct (pack_type_inv (snd rtr)); repeat rcombine. simpl. rewrite H2. inhabiter. rewrite <- (pack_injective H3). canceler. sep fail auto.
  solve [ sep fail auto ].
  solve [ sep fail auto ].
  intros; inhabiter; unpack_conc. destruct (pack_type_inv (snd rtr)). rewrite H3. simpl. intro_pure. rewrite H4 in H. repeat rcombine. rewrite <- (pack_injective H).
    simpl. rewrite nil_cons_app. canceler.
    sep fail ltac:(auto; try constructor; auto; try discriminate).
Qed.

Definition main : forall (local: Net.SockAddr),
  STsep (traced nil)
        (fun _:unit => Exists t :@ Trace, traced t).
  refine (fun local =>
    xxx <- IO.forever
             (fun t => [correct local t])
             (fun t => {{ iter local t }})
             [nil];
   {{Return tt}});
  sep fail ltac:(auto; try constructor).
Qed.

End ExecImpl.