(* *********************************************************************)
(*                                                                     *)
(*            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 VMM                                          *)
(*                                                                     *)
(*          Refinement proof for PTIntro layer                         *)
(*                                                                     *)
(*          Ronghui Gu <ronghui.gu@yale.edu>                           *)
(*                                                                     *)
(*          Yale Flint Group                                           *)
(*                                                                     *)
(* *********************************************************************)

(** This file provide the contextual refinement proof between MAL layer and MPTIntro layer*)
Require Import PTIntroGenDef.
Require Import PTIntroGenSpec.

(** * Definition of the refinement relation*)
Section Refinement.

  Context `{real_params: RealParams}.

  Section WITHMEM.

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

    (** ** The low level specifications exist*)
    Section Exists.

      Lemma setCR3_exist:
        forall habd habd' labd m n s f,
          setPT'_spec n habd = Some habd'
          -> high_level_invariant habd
          -> relate_RData f habd labd
          -> match_RData s habd m f
          -> exists labd', setCR30_spec labd (GLOBP PTPool_LOC (Int.repr (n * PgSize)))
                           = Some labd' /\ relate_RData f habd' labd'
                           /\ PT habd' = n
                           /\ ptpool habd' = ptpool habd
                           /\ pperm habd' = pperm habd
                           /\ idpde habd' = idpde habd
                           /\ CR3 labd' = (GLOBP PTPool_LOC (Int.repr (n * PgSize)))
                           /\ 0 <= n < num_proc.
      Proof.
        unfold setPT'_spec, setCR30_spec; intros until f.
        intros HP HINV HR HM; pose proof HR as HR'; inv HR; revert HP;
        subrewrite'; intros HQ; inv HINV; subdestruct;
        destruct (CR3_valid_dec
                    (GLOBP PTPool_LOC (Int.repr (n * 4096)))).
        - (* ipt = true /\ valid CR3*)
          inv HQ; refine_split'; eauto.
          inv HR'. econstructor; eauto; simpl.
          econstructor; eauto.
          rewrite Int.unsigned_repr. omega.
          rewrite int_max. omega.
        - elim n0; unfold CR3_valid; eauto.
        - (* ipt = false /\ valid CR3 *)
          inv HQ; refine_split'; eauto.
          inv HR'. econstructor; eauto; simpl.
          econstructor; eauto.
          rewrite Int.unsigned_repr. omega.
          rewrite int_max. omega.
        - elim n0; unfold CR3_valid; eauto.
      Qed.

    End Exists.

    Ltac pattern2_refinement_simpl:=
      pattern2_refinement_simpl' (@relate_AbData).

    Section FRESH_PRIM.

      Lemma setPT_spec_ref:
        compatsim (crel HDATA LDATA) (gensem setPT'_spec) setPT_spec_low.
      Proof.
        compatsim_simpl (@match_AbData).
        assert(HOS: kernel_mode d2).
        {
          simpl; inv match_related.
          functional inversion H1; subst;
          refine_split'; trivial; congruence.
        }
        exploit setCR3_exist; eauto; intros (labd' & HP & HM & HN1 & HN2 & HN3 & Hide & HCR3 & Hrange).
        refine_split; eauto.
        econstructor; eauto.
        pose proof match_related as match_relate'.
        inv match_related.
        split; eauto; pattern2_refinement_simpl.
        econstructor; eauto; subrewrite'.
      Qed.

      Lemma getPDE_spec_ref:
        compatsim (crel HDATA LDATA) (gensem getPDE_spec) getPDE_spec_low.
      Proof.
        compatsim_simpl (@match_AbData).
        assert(HOS: kernel_mode d2
                    /\ 0 <= Int.unsigned i < num_proc
                    /\ 0 <= Int.unsigned i0 <= PDX Int.max_unsigned).
        {
          simpl; inv match_related.
          unfold getPDE_spec in *.
          unfold PDE_Arg in *.
          subdestruct; refine_split'; trivial; congruence.
        }
        destruct HOS as [Hkern [Hrange Hrange']].
        generalize H; intros HMAT. inv H. specialize (H1 _ Hrange).
        inv H1. specialize (H _ Hrange').
        destruct H as (v & HLD & _ & HM).
        assert (HVint: exists v', Vint v' = v /\ Int.unsigned z = Int.unsigned v' / PgSize).
        {
          functional inversion H2.
          - subst pt. rewrite H8 in HM. inv HM.
            refine_split'; trivial. subrewrite'.
            rewrite Zplus_comm.
            rewrite Z_div_plus. reflexivity.
            omega.
          - subst pt. rewrite H8 in HM. inv HM.
            refine_split'; trivial.
        }
        destruct HVint as (v' & Heq & Heq'); subst.
        refine_split; eauto.
        econstructor; eauto.
      Qed.

      Lemma getPTE_spec_ref:
        compatsim (crel HDATA LDATA) (gensem getPTE_spec) getPTE_spec_low.
      Proof.
        compatsim_simpl (@match_AbData).
        assert(HOS: kernel_mode d2
                    /\ 0 <= Int.unsigned i < num_proc
                    /\ 0 <= Int.unsigned i0 <= PDX Int.max_unsigned
                    /\ 0 <= Int.unsigned i1 <= PTX Int.max_unsigned).
        {
          simpl; inv match_related.
          unfold getPTE_spec in *.
          unfold PTE_Arg in *. unfold PDE_Arg in *.
          subdestruct; refine_split'; trivial; congruence.
        }
        destruct HOS as (Hkern & Hrange & Hrange' & Hrange'').
        generalize H; intros HMAT. inv H. specialize (H1 _ Hrange).
        inv H1. specialize (H _ Hrange').
        destruct H as (v & HLD & _ & HM).
        assert (HVint: exists v1 v2, Vint v1 = v /\ Int.unsigned v1 = v2 * PgSize + PT_PERM_PTU /\
                                     fload'_spec (v2 * one_k + Int.unsigned i1) d2 = Some (Int.unsigned z)).
        {
          unfold getPTE_spec in *.
          destruct (ikern d1') eqn: Hik; contra_inv.
          destruct (ihost d1') eqn: Hih; contra_inv.
          destruct (init d1') eqn: Hii; contra_inv.
          destruct (ipt d1') eqn: Hit; contra_inv.
          destruct (PTE_Arg (Int.unsigned i) (Int.unsigned i0) (Int.unsigned i1)); contra_inv.
          destruct (ZMap.get (Int.unsigned i0) (ZMap.get (Int.unsigned i) (ptpool d1'))) eqn: HT; contra_inv.
          inv HM. exploit relate_PMap_re; eauto 1. intros HPMap.
          inv HPMap. specialize (H _ Hrange _ Hrange' _ _ HT _ Hrange'').
          destruct H as (v' & HLD' & HM).
          assert (HLD'': fload'_spec (pi * one_k + Int.unsigned i1) d2 = Some (Int.unsigned z)).
          {
            unfold fload'_spec. inv match_related. rewrite <- ikern_re, <- ihost_re.
            rewrite Hik, Hih.
            assert (HOS: 0 <= pi * 4096 + 7 <= Int.max_unsigned).
            {
              specialize (Int.unsigned_range_2 v0). subrewrite'.
            }
            rewrite zle_lt_true.
            - replace ((pi * 1024 + Int.unsigned i1) * 4) with (pi * 4096 + Int.unsigned i1 * 4) by omega.
              destruct (ZMap.get (Int.unsigned i1) pte); contra_inv; inv HM; inv H2.
              + refine_split'; trivial.
                rewrite H7. apply PermZ_eq in H6. rewrite H6. trivial.
              + refine_split'; trivial.
            - revert HOS Hrange''. clear.
              intros. rewrite_omega.
          }
          refine_split'; eauto 1.
        }
        destruct HVint as (v1 & v2 & Heq1 & Heq2 & Heq4).
        refine_split; eauto 1.
        econstructor; eauto.
      Qed.

      Lemma setPTE_spec_ref:
        compatsim (crel HDATA LDATA) (gensem setPTE_spec) setPTE_spec_low.
      Proof.
        compatsim_simpl (@match_AbData).
        assert (Hkern: exists p0,
                         kernel_mode d2
                         /\ 0 <= Int.unsigned i < num_proc
                         /\ 0 <= Int.unsigned i0 <= PDX Int.max_unsigned
                         /\ 0 <= Int.unsigned i1 <= PTX Int.max_unsigned
                         /\ 0 < Int.unsigned i2 < nps d2
                         /\ ZtoPerm (Int.unsigned i3) = Some p0
                         /\ PT d1' = PT d1).
        {
          inv match_related. functional inversion H1; subst.
          unfold PTE_Arg, PDE_Arg in *. subdestruct.
          refine_split'; try congruence; eauto.
        }
        destruct Hkern as (perm & Hkern & Hrange & Hrange' & Hrange'' & Hrange''' & HPerm & HPT).
        inv H. generalize H2; intros HMAT; specialize (H2 _ Hrange); inv H2.
        specialize (H _ Hrange'); destruct H as [v[HLD [HV HM]]].
        assert (HVint: exists v1 v2, Vint v1 = v /\ Int.unsigned v1 = v2 * PgSize + PT_PERM_PTU
                                     /\ match_RData s d1' m2 ι
                                     /\ init d2 = true
                                     /\ exists d2', fstore0_spec  (v2 * one_k + Int.unsigned i1)
                                                                  (Int.unsigned i2 * PgSize + Int.unsigned i3) d2
                                                    = Some d2'
                                                    /\ relate_RData ι d1' d2').
        {
          unfold setPTE_spec in *. subdestruct.
          inv HM. esplit; esplit. split; [reflexivity|]. split; [eassumption|]. split; [|split].
          - (* match_RData *)
            constructor; inv H1; simpl; trivial.
            econstructor; eauto 1; intros.
            destruct (zeq n0 (Int.unsigned i)); subst.
            + (* n = Int.unsigned i *)
              rewrite ZMap.gss. constructor; intros.
              destruct (zeq i4 (Int.unsigned i0)); subst.
              * (* i4 = Int.unsigned i0 *)
                rewrite ZMap.gss. refine_split'; eauto 1.
                constructor; eauto; intros.
              * (* i4 <> Int.unsigned i0 *)
                rewrite ZMap.gso; eauto 2.
                specialize (HMAT _ Hrange). inv HMAT.
                eapply H2; eauto 2.
            + (* n <> int.unsigned i*)
              rewrite ZMap.gso; eauto 2.
          - inv match_related. congruence.
          - (* fstore /\ relate RData *)
            unfold fstore0_spec. inv match_related.
            rewrite <- ikern_re, <- ihost_re. rewrite Hdestruct, Hdestruct0.
            assert (HOS: 0<= pi * 4096 + 7 <= Int.max_unsigned).
            {
              specialize (Int.unsigned_range_2 v0). subrewrite'.
            }
            rewrite zle_lt_true.
            + replace ((pi * 1024 + Int.unsigned i1) * 4) with (pi * 4096 + Int.unsigned i1 * 4) by omega.
              unfold flatmem_store. unfold PageI.
              replace ((pi * 4096 + Int.unsigned i1 * 4) / 4096) with pi.
              * pose proof (pperm_re pi) as HPP.
                rewrite H10 in HPP. inv HPP. trivial.
                refine_split'; eauto 1.
                inv H1. constructor; trivial; simpl; try congruence.
                { (* FlatMem *)
                  unfold FlatMem.flatmem_inj in *.
                  intros; rewrite valid_dirty; [| assumption| eassumption].
                  eapply FlatMem.store_unmapped_inj; eauto 1.
                  simpl. rewrite_omega.
                }
                { (* PMap *)
                  constructor; intros. inv relate_PMap_re.
                  destruct (zeq n0 (Int.unsigned i)); subst.
                  - (* n = Int.unsigned i *)
                    rewrite ZMap.gss in H4.
                    destruct (zeq i4 (Int.unsigned i0)); subst.
                    + (* i4 = Int.unsigned i0 *)
                      rewrite ZMap.gss in H4. inv H4.
                      destruct (zeq vadr (Int.unsigned i1)); subst.
                      * (* vadr = Int.unsigned i1 *)
                        rewrite ZMap.gss. rewrite FlatMem.load_store_same.
                        refine_split'; trivial.
                        econstructor; eauto. apply Int.unsigned_repr.
                        apply ZtoPerm_range in Hdestruct6.
                        exploit valid_nps; eauto. rewrite nps_re.
                        rewrite_omega.
                      * (* vadr <> Int.unsigned i1 *)
                        rewrite ZMap.gso; auto. erewrite FlatMem.load_store_other; eauto 2.
                        simpl. destruct (zle (vadr + 1) (Int.unsigned i1)).
                        left; omega. right; omega.
                    + (* i4 <> Int.unsigned i0 *)
                      rewrite ZMap.gso in H4; auto.
                      assert (Hneq: pi <> pi0).
                      {
                        red; intros; subst.
                        specialize (HMAT _ Hrange). inv HMAT.
                        specialize (H8 _ H2). destruct H8 as (v & _ & _ & HMAT).
                        rewrite H4 in HMAT. inv HMAT. congruence.
                      }
                      erewrite FlatMem.load_store_other; eauto 2. simpl.
                      destruct (zle (pi0 + 1) pi); rewrite_omega.
                  - (* n <> int.unsigned i*)
                    rewrite ZMap.gso in H4; auto.
                    assert (Hneq: pi <> pi0).
                    {
                      red; intros; subst.
                      specialize (HMAT _ H1). inv HMAT.
                      specialize (H8 _ H2). destruct H8 as (v & _ & _ & HMAT).
                      unfold PMap, ZMap.t, PMap.t in HMAT.
                      rewrite H4 in HMAT. inv HMAT. congruence.
                    }
                    erewrite FlatMem.load_store_other; eauto 2. simpl.
                    destruct (zle (pi0 + 1) pi); rewrite_omega.
                }

              * rewrite Zplus_comm.
                rewrite Z_div_plus. rewrite Zdiv_small. reflexivity.
                revert Hrange''. clear; intros. rewrite_omega. omega.
            + rewrite_omega.
        }
        destruct HVint as (v1 & v2 & Heq1 & Heq2 & Hma & Hinit &  d2' & HST & Hre); subst.
        exists ι, Vundef, (fst (m2, d2)), d2'.
        refine_split; eauto 1.
        - econstructor; eauto 1.
        - split; eauto; pattern2_refinement_simpl.
      Qed.

      Lemma rmvPTE_spec_ref:
        compatsim (crel HDATA LDATA) (gensem rmvPTE_spec) rmvPTE_spec_low.
      Proof.
        compatsim_simpl (@match_AbData).
        assert (Hkern: kernel_mode d2
                       /\ 0 <= Int.unsigned i < num_proc
                       /\ 0 <= Int.unsigned i0 <= PDX Int.max_unsigned
                       /\ 0 <= Int.unsigned i1 <= PTX Int.max_unsigned
                       /\ PT d1' = PT d1).
        {
          inv match_related. functional inversion H1; subst.
          unfold PTE_Arg, PDE_Arg in *. subdestruct.
          refine_split'; try congruence; eauto.
        }
        destruct Hkern as [Hkern [Hrange [Hrange' [Hrange'' HPT]]]].
        inv H. generalize H2; intros HMAT; specialize (H2 _ Hrange); inv H2.
        specialize (H _ Hrange'); destruct H as [v[HLD [HV HM]]].
        assert (HVint: exists v1 v2, Vint v1 = v /\ Int.unsigned v1 = v2 * PgSize + PT_PERM_PTU
                                     /\ match_RData s d1' m2 ι
                                     /\ exists d2', fstore0_spec (v2 * one_k + Int.unsigned i1) 0 d2 = Some d2'
                                                    /\ relate_RData ι d1' d2').
        {
          unfold rmvPTE_spec in *. subdestruct.
          inv HM. esplit; esplit. split; [reflexivity|]. split; [eassumption|]. split.
          - (* match_RData *)
            constructor; inv H1; simpl; trivial. econstructor; eauto 1; intros.
            destruct (zeq n0 (Int.unsigned i)); subst.
            + (* n = Int.unsigned i *)
              rewrite ZMap.gss. constructor; intros.
              destruct (zeq i2 (Int.unsigned i0)); subst.
              * (* i2 = Int.unsigned i0 *)
                rewrite ZMap.gss. refine_split'; eauto 1.
                constructor; eauto; intros.
              * (* i2 <> Int.unsigned i0 *)
                rewrite ZMap.gso; eauto 2.
                specialize (HMAT _ Hrange). inv HMAT.
                eauto 2.
            + (* n <> int.unsigned i*)
              rewrite ZMap.gso; eauto 2.

          - (* fstore /\ relate RData *)
            unfold fstore0_spec. inv match_related.
            rewrite <- ikern_re, <- ihost_re. rewrite Hdestruct, Hdestruct0.
            assert (HOS: 0<= pi * 4096 + 7 <= Int.max_unsigned).
            {
              specialize (Int.unsigned_range_2 v0). subrewrite'.
            }
            rewrite zle_lt_true.
            + replace ((pi * 1024 + Int.unsigned i1) * 4) with (pi * 4096 + Int.unsigned i1 * 4) by omega.
              unfold flatmem_store. unfold PageI.
              replace ((pi * 4096 + Int.unsigned i1 * 4) / 4096) with pi.
              * pose proof (pperm_re pi) as HPP.
                rewrite H10 in HPP. inv HPP.
                refine_split'; eauto 1.
                inv H1. constructor; trivial; simpl; try congruence.
                { (* FlatMem *)
                  unfold FlatMem.flatmem_inj in *.
                  intros; rewrite valid_dirty; [| assumption| eassumption].
                  eapply FlatMem.store_unmapped_inj; eauto 1.
                  simpl. rewrite_omega.
                }
                { (* PMap *)
                  constructor; intros. inv relate_PMap_re.
                  destruct (zeq n0 (Int.unsigned i)); subst.
                  - (* n = Int.unsigned i *)
                    rewrite ZMap.gss in H4.
                    destruct (zeq i2 (Int.unsigned i0)); subst.
                    + (* i2 = Int.unsigned i0 *)
                      rewrite ZMap.gss in H4. inv H4.
                      destruct (zeq vadr (Int.unsigned i1)); subst.
                      * (* vadr = Int.unsigned i1 *)
                        rewrite ZMap.gss. rewrite FlatMem.load_store_same.
                        refine_split'; trivial.
                        econstructor; eauto.
                      * (* vadr <> Int.unsigned i1 *)
                        rewrite ZMap.gso; auto. erewrite FlatMem.load_store_other; eauto 2.
                        simpl. destruct (zle (vadr + 1) (Int.unsigned i1)).
                        left; omega. right; omega.
                    + (* i2 <> Int.unsigned i0 *)
                      rewrite ZMap.gso in H4; auto.
                      assert (Hneq: pi <> pi0).
                      {
                        red; intros; subst.
                        specialize (HMAT _ Hrange). inv HMAT.
                        specialize (H8 _ H2). destruct H8 as (v & _ & _ & HMAT).
                        rewrite H4 in HMAT. inv HMAT. congruence.
                      }
                      erewrite FlatMem.load_store_other; eauto 2.
                      simpl. destruct (zle (pi0 + 1) pi); rewrite_omega.
                  - (* n <> int.unsigned i*)
                    rewrite ZMap.gso in H4; auto.
                    assert (Hneq: pi <> pi0).
                    {
                      red; intros; subst.
                      specialize (HMAT _ H1). inv HMAT.
                      specialize (H8 _ H2). destruct H8 as (v & _ & _ & HMAT).
                      unfold PMap, ZMap.t, PMap.t in HMAT.
                      rewrite H4 in HMAT. inv HMAT. congruence.
                    }
                    erewrite FlatMem.load_store_other; eauto 2.
                    simpl. destruct (zle (pi0 + 1) pi); rewrite_omega.
                }

              * rewrite Zplus_comm.
                rewrite Z_div_plus. rewrite Zdiv_small. reflexivity.
                revert Hrange''. clear; intros. rewrite_omega. omega.
            + rewrite_omega.
        }
        destruct HVint as (v1 & v2 & Heq1 & Heq2 & Hma & d2' & HST & Hre); subst.
        exists ι, Vundef, (fst (m2, d2)), d2'.
        refine_split; eauto 1.
        - econstructor; eauto 1.
        - split; eauto; pattern2_refinement_simpl.
      Qed.

      Lemma setPDEU_spec_ref:
        compatsim (crel HDATA LDATA) (gensem setPDEU_spec) setPDEU_spec_low.
      Proof.
        compatsim_simpl (@match_AbData).
        assert (Hkern: kernel_mode d2
                       /\ 0 <= Int.unsigned i < num_proc
                       /\ 0 <= Int.unsigned i0 <= PDX Int.max_unsigned
                       /\ 0 < Int.unsigned i1 < nps d2
                       /\ PT d1' = PT d1
                       /\ init d2 = true).
        {
          inv match_related.
          unfold setPDEU_spec in *.
          unfold PDE_Arg in *.
          subdestruct; refine_split'; trivial; try congruence.
          inv H1. reflexivity.
        }
        destruct Hkern as (Hkern & Hrange & Hrange' & Hrange'' & HPT & Hinit).
        inv H. generalize H2; intros HMAT; specialize (H2 _ Hrange); inv H2.
        specialize (H _ Hrange'); destruct H as [_[_ [HV _]]].
        specialize (Mem.valid_access_store _ _ _ _
                                           (Vint (Int.repr (Int.unsigned i1 * PgSize + PT_PERM_PTU)))
                                           HV); intros [m0 HST].
        refine_split; eauto.
        - econstructor; eauto.
          simpl; lift_trivial. rewrite HST. reflexivity.
        - pose proof H1 as Hspec.
          functional inversion Hspec; subst; simpl in *.
          split; eauto 1; pattern2_refinement_simpl.
          + inv match_related; simpl in *; split; simpl; try eassumption.
            { (* Flatmem *)
              apply FlatMem.free_page_inj. assumption.
            }
            { (* PPermT_les *)
              intros j. specialize (pperm_re j).
              destruct (zeq j (Int.unsigned i1)); subst.
              - rewrite ZMap.gss. rewrite H10 in pperm_re.
                inv pperm_re. constructor.
              - rewrite ZMap.gso; eauto 2.
            }
            { (* PMapPool *)
              subst pt'. constructor; intros.
              destruct (zeq n (Int.unsigned i)); subst.
              { (* n = int.unsigned i*)
                rewrite ZMap.gss in H12.
                destruct (zeq i2 (Int.unsigned i0)); subst.
                { (* i2 = Int.unsigned i0 *)
                  rewrite ZMap.gss in H12.
                  inv H12. rewrite ZMap.gi.
                  refine_split'; eauto 2. constructor.
                }
                { (* i2 <> Int.unsigned i0 *)
                  rewrite ZMap.gso in H12; eauto 1.
                  inv relate_PMap_re. eauto.
                }
              }
              { (* n <> int.unsigned i*)
                rewrite ZMap.gso in H12; eauto 1.
                inv relate_PMap_re. eauto.
              }
            }

          + econstructor; eauto 1; simpl in *.
            {
              econstructor; eauto 1; intros.
              * destruct (zeq n (Int.unsigned i)); subst.
                { (* n = int.unsigned i*)
                  rewrite ZMap.gss.
                  specialize (HMAT _ H). inv HMAT.
                  constructor; intros.
                  specialize (H11 _ H12).
                  destruct (zeq i2 (Int.unsigned i0)); subst.
                  { (* i2 = Int.unsigned i0 *)
                    refine_split'.
                    - eapply Mem.load_store_same; eauto.
                    - eapply Mem.store_valid_access_1; eauto.
                    - subst pt'; repeat rewrite ZMap.gss.
                      constructor; intros.
                      + rewrite Int.unsigned_repr. reflexivity.
                        exploit valid_nps; eauto 1.
                        intros. rewrite_omega.
                      + rewrite ZMap.gss. reflexivity.
                  }
                  { (* i1 <> Int.unsigned i0 *)
                    destruct H11 as [v1[HL1[HV1 HM1]]].
                    refine_split'.
                    - erewrite Mem.load_store_other; eauto.
                      right; simpl.
                      destruct (zle (i2 + 1) (Int.unsigned i0)).
                      + left. revert n l. clear. intros. omega.
                      + right. revert n g. clear. intros. omega.
                    - eapply Mem.store_valid_access_1; eauto.
                    - subst pt'. rewrite ZMap.gso; auto.
                      inv HM1; constructor; intros; eauto 1.
                      + destruct (zeq pi (Int.unsigned i1)); subst.
                        * congruence.
                        * rewrite ZMap.gso; eauto 1.
                  }
                }
                { (* n <> int.unsigned i*)
                  constructor; intros. rewrite ZMap.gso; auto.
                  specialize (HMAT _ H). inv HMAT.
                  specialize (H12 _ H11); destruct H12 as [v1[HL1[HV1 HM1]]].
                  refine_split'.
                  - erewrite Mem.load_store_other; eauto.
                    right; simpl.
                    destruct (zle (n + 1) (Int.unsigned i)).
                    + left. rewrite_omega.
                    + right. rewrite_omega.
                  - eapply Mem.store_valid_access_1; eauto.
                  - unfold PMap, ZMap.t, PMap.t in HM1.
                    inv HM1; econstructor; intros; eauto 1.
                    + destruct (zeq pi (Int.unsigned i1)); subst.
                      * congruence.
                      * rewrite ZMap.gso; eauto 1.
                }
            }
            {
              inv H0. esplit; eauto. intros.
              specialize (H _ H0 _ H12).
              destruct H as (v & HLD & HV' & HM).
              erewrite Mem.load_store_other; eauto.
              - refine_split'; eauto.
                eapply Mem.store_valid_access_1; eauto.
              - left. red; intros; subst.
                specialize (genv_vars_inj _ _ _ _ H3 H11).
                intros. inv H.
            }
      Qed.

      Lemma rmvPDE_spec_ref:
        compatsim (crel HDATA LDATA) (gensem rmvPDE_spec) rmvPDE_spec_low.
      Proof.
        compatsim_simpl (@match_AbData).
        assert (Hkern: kernel_mode d2
                       /\ 0 <= Int.unsigned i < num_proc
                       /\ 0 <= Int.unsigned i0 <= PDX Int.max_unsigned
                       /\ PT d1' = PT d1
                       /\ idpde d1' = idpde d1).
        {
          inv match_related.
          unfold rmvPDE_spec in *.
          unfold PDE_Arg in *.
          subdestruct; refine_split'; trivial; try congruence;
          inv H1; reflexivity.
        }
        destruct Hkern as (Hkern & Hrange & Hrange' & HPT & Hipde).
        inv H. generalize H2; intros HMAT; specialize (H2 _ Hrange); inv H2.
        specialize (H _ Hrange'); destruct H as [_[_ [HV _]]].
        specialize (Mem.valid_access_store _ _ _ _
                                           (Vint (Int.repr PT_PERM_UP))
                                           HV); intros [m0 HST].
        refine_split; eauto.
        - econstructor; eauto.
          simpl; lift_trivial. rewrite HST. reflexivity.
        - pose proof H1 as Hspec.
          assert (Hre_ab: relate_AbData s ι d1' d2).
          {
            inv match_related.
            assert (HP: relate_PMapPool
                          (ZMap.set (Int.unsigned i)
                                    (ZMap.set (Int.unsigned i0) PDEUnPresent
                                              (ZMap.get (Int.unsigned i) (ptpool d1)))
                                    (ptpool d1)) (HP d2)).
            {
              constructor; intros.
              destruct (zeq n (Int.unsigned i)); subst.
              { (* n = int.unsigned i*)
                rewrite ZMap.gss in H4.
                destruct (zeq i1 (Int.unsigned i0)); subst.
                { (* i1 = Int.unsigned i0 *)
                  rewrite ZMap.gss in H4. inv H4.
                }
                { (* i2 <> Int.unsigned i0 *)
                  rewrite ZMap.gso in H4; eauto 1.
                  inv relate_PMap_re. eauto.
                }
              }
              { (* n <> int.unsigned i*)
                rewrite ZMap.gso in H4; eauto 1.
                inv relate_PMap_re. eauto.
              }
            }
            functional inversion Hspec; subst;
            split; trivial; simpl in *; contra_inv.
            { (* PPermT_les *)
              intros j. specialize (pperm_re j).
              destruct (zeq j pi); subst.
              - rewrite ZMap.gss. rewrite H12 in pperm_re.
                inv pperm_re. constructor.
              - rewrite ZMap.gso; eauto 2.
            }
            { (* PPermT_les *)
              intros j. specialize (pperm_re j).
              destruct (zeq j pi); subst.
              - rewrite ZMap.gss. rewrite H11 in pperm_re.
                inv pperm_re. constructor.
              - rewrite ZMap.gso; eauto 2.
            }
          }
          assert (Hma_ab:  match_AbData s d1' m0 ι).
          {
            econstructor; eauto 1; simpl in *.
            {
              econstructor; eauto 1; intros. pose proof HMAT as HMAT'.
              specialize (HMAT _ H).
              assert(HP: forall pp,
                           (forall pi0 a1 a2, ZMap.get pi0 (pperm d1) = PGHide (PGPMap a1 a2) ->
                                              (a1 <> Int.unsigned i \/ a2 <> Int.unsigned i0) ->
                                              ZMap.get pi0 pp = PGHide (PGPMap a1 a2)) ->
                           match_PMap s (ZMap.get n (ZMap.set (Int.unsigned i)
                                                              (ZMap.set (Int.unsigned i0) PDEUnPresent
                                                                        (ZMap.get (Int.unsigned i) (ptpool d1)))
                                                              (ptpool d1))) pp m0 b n).
              {
                intros.
                * destruct (zeq n (Int.unsigned i)); subst.
                  { (* n = int.unsigned i*)
                    rewrite ZMap.gss. inv HMAT.
                    constructor; intros.
                    specialize (H4 _ H5).
                    destruct (zeq i1 (Int.unsigned i0)); subst.
                    { (* i1 = Int.unsigned i0 *)
                      refine_split'.
                      - eapply Mem.load_store_same; eauto.
                      - eapply Mem.store_valid_access_1; eauto.
                      - repeat rewrite ZMap.gss.
                        constructor.
                    }
                    { (* i1 <> Int.unsigned i0 *)
                      destruct H4 as [v1[HL1[HV1 HM1]]].
                      refine_split'.
                      - erewrite Mem.load_store_other; eauto.
                        right; simpl.
                        destruct (zle (i1 + 1) (Int.unsigned i0)).
                        + left. omega.
                        + right. omega.
                      - eapply Mem.store_valid_access_1; eauto.
                      - rewrite ZMap.gso; auto.
                        inv HM1; constructor; intros; eauto.
                    }
                  }
                  { (* n <> int.unsigned i*)
                    constructor; intros. rewrite ZMap.gso; auto.
                    inv HMAT. specialize (H5 _ H4); destruct H5 as [v1[HL1[HV1 HM1]]].
                    refine_split'.
                    - erewrite Mem.load_store_other; eauto.
                      right; simpl.
                      destruct (zle (n + 1) (Int.unsigned i)).
                      + left. rewrite_omega.
                      + right. rewrite_omega.
                    - eapply Mem.store_valid_access_1; eauto.
                    - unfold PMap, ZMap.t, PMap.t in HM1.
                      inv HM1; econstructor; intros; eauto.
                  }
              }
              functional inversion Hspec; subst; simpl in *;
              subst pt'; eapply HP; eauto 1; contra_inv.
              {
                intros. destruct (zeq pi0 pi); subst.
                - specialize (HMAT' _ Hrange). inv HMAT'.
                  specialize (H15 _ Hrange').
                  destruct H15 as (? & _ & _ & HM).
                  rewrite H12 in HM. inv HM.
                  destruct H14; congruence.
                - rewrite ZMap.gso; eauto 1.
              }
              {
                intros. destruct (zeq pi0 pi); subst.
                - specialize (HMAT' _ Hrange). inv HMAT'.
                  specialize (H14 _ Hrange').
                  destruct H14 as (? & _ & _ & HM).
                  rewrite H11 in HM. inv HM.
                  destruct H13; congruence.
                - rewrite ZMap.gso; eauto 1.
              }
            }
            {
              inv H0. rewrite Hipde. esplit; eauto. intros.
              specialize (H _ H0 _ H4).
              destruct H as (v & HLD & HV' & HM).
              erewrite Mem.load_store_other; eauto.
              - refine_split'; eauto.
                eapply Mem.store_valid_access_1; eauto.
              - left. red; intros; subst.
                specialize (genv_vars_inj _ _ _ _ H3 H2).
                intros. inv H.
            }
          }
          split; eauto 1; pattern2_refinement_simpl.
      Qed.

      Lemma setPDE_spec_ref:
        compatsim (crel HDATA LDATA) (gensem setPDE_spec) setPDE_spec_low.
      Proof.
        compatsim_simpl (@match_AbData).
        assert (Hkern: kernel_mode d2
                       /\ 0 <= Int.unsigned i < num_proc
                       /\ 0 <= Int.unsigned i0 <= PDX Int.max_unsigned
                       /\ PT d1' = PT d1).
        {
          inv match_related.
          unfold setPDE_spec in *.
          unfold PDE_Arg in *.
          subdestruct; refine_split'; trivial; try congruence.
          inv H1. reflexivity.
        }
        destruct Hkern as (Hkern & Hrange & Hrange' & HPT).
        inv H. generalize H2; intros HMAT; specialize (H2 _ Hrange); inv H2.
        specialize (H _ Hrange'); destruct H as [_[_ [HV _]]]. inv H0.
        specialize (Mem.valid_access_store _ _ _ _
                                           (Vptr b0 (Int.repr (Int.unsigned i0 * PgSize + PT_PERM_PTU)))
                                           HV); intros [m0 HST].
        refine_split; eauto.
        - econstructor; eauto.
          simpl; lift_trivial. rewrite HST. reflexivity.
        - pose proof H1 as Hspec.
          functional inversion Hspec; subst; simpl in *.
          split; eauto 1; pattern2_refinement_simpl.
          + inv match_related; simpl in *; split; simpl; try eassumption.
            { (* PMapPool *)
              subst pt'. constructor; intros.
              destruct (zeq n (Int.unsigned i)); subst.
              { (* n = int.unsigned i*)
                rewrite ZMap.gss in H11.
                destruct (zeq i1 (Int.unsigned i0)); subst.
                { (* i1 = Int.unsigned i0 *)
                  rewrite ZMap.gss in H11.
                  inv H11.
                }
                { (* i1 <> Int.unsigned i0 *)
                  rewrite ZMap.gso in H11; eauto 1.
                  inv relate_PMap_re. eauto.
                }
              }
              { (* n <> int.unsigned i*)
                rewrite ZMap.gso in H11; eauto 1.
                inv relate_PMap_re. eauto.
              }
            }

          + econstructor; eauto 1; simpl in *.
            {
              econstructor; eauto 1; intros.
              * destruct (zeq n (Int.unsigned i)); subst.
                { (* n = int.unsigned i*)
                  rewrite ZMap.gss.
                  specialize (HMAT _ H0). inv HMAT.
                  constructor; intros.
                  specialize (H10 _ H11).
                  destruct (zeq i1 (Int.unsigned i0)); subst.
                  { (* i1 = Int.unsigned i0 *)
                    refine_split'.
                    - eapply Mem.load_store_same; eauto.
                    - eapply Mem.store_valid_access_1; eauto.
                    - subst pt'; repeat rewrite ZMap.gss.
                      constructor; intros; eauto.
                      rewrite Int.unsigned_repr. reflexivity.
                      rewrite_omega.
                  }
                  { (* i1 <> Int.unsigned i0 *)
                    destruct H10 as [v1[HL1[HV1 HM1]]].
                    refine_split'.
                    - erewrite Mem.load_store_other; eauto.
                      right; simpl.
                      destruct (zle (i1 + 1) (Int.unsigned i0)).
                      + left. omega.
                      + right. omega.
                    - eapply Mem.store_valid_access_1; eauto.
                    - subst pt'. rewrite ZMap.gso; auto.
                  }
                }
                { (* n <> int.unsigned i*)
                  constructor; intros. rewrite ZMap.gso; auto.
                  specialize (HMAT _ H0). inv HMAT.
                  specialize (H11 _ H10); destruct H11 as [v1[HL1[HV1 HM1]]].
                  refine_split'.
                  - erewrite Mem.load_store_other; eauto.
                    right; simpl.
                    destruct (zle (n + 1) (Int.unsigned i)).
                    + left. rewrite_omega.
                    + right. rewrite_omega.
                  - eapply Mem.store_valid_access_1; eauto.
                  - unfold PMap, ZMap.t, PMap.t in HM1.
                    inv HM1; econstructor; intros; eauto 1.
                }
            }
            {
              esplit; eauto. intros.
              specialize (H _ H0 _ H10).
              destruct H as (v & HLD & HV' & HM).
              erewrite Mem.load_store_other; eauto.
              - refine_split'; eauto.
                eapply Mem.store_valid_access_1; eauto.
              - left. red; intros; subst.
                specialize (genv_vars_inj _ _ _ _ H3 H2).
                intros. inv H.
            }
      Qed.

      Lemma pt_in_spec_ref:
        compatsim (crel HDATA LDATA) (primcall_general_compatsem'
                                        ptin'_spec (prim_ident:= pt_in)) pt_in_spec_low.
      Proof.
        compatsim_simpl (@match_AbData); intros.
        inv match_extcall_states.
        assert(HOS: kernel_mode d2).
        {
          simpl; inv match_related.
          functional inversion H8; subst;
          refine_split'; trivial; try congruence.
        }
        refine_split'; eauto.
        econstructor; eauto.
        - specialize (match_reg PC). unfold Pregmap.get in *.
          rewrite H7 in match_reg.
          inv match_reg.
          exploit inject_forward_equal'; eauto.
          intros HW; inv HW.
          rewrite Int.add_zero. reflexivity.
        - functional inversion H8; subst.
          pose proof match_related as match_relate'.
          inv match_related.
          split; eauto; pattern2_refinement_simpl.
          + econstructor; eauto.
            econstructor; eauto.
            inv match_match.
            econstructor; eauto.
          + val_inject_simpl.
      Qed.

      Lemma pt_out_spec_ref:
        compatsim (crel HDATA LDATA) (primcall_general_compatsem'
                                        ptout_spec (prim_ident:= pt_out)) pt_out_spec_low.
      Proof.
        compatsim_simpl (@match_AbData); intros.
        inv match_extcall_states.
        assert(HOS: kernel_mode d2).
        {
          simpl; inv match_related.
          functional inversion H8; subst;
          refine_split'; trivial; try congruence.
        }
        refine_split'; eauto.
        econstructor; eauto.
        - eapply reg_symbol_inject; eassumption.
        - functional inversion H8; subst.
          pose proof match_related as match_relate'.
          inv match_related.
          split; eauto; pattern2_refinement_simpl.
          + econstructor; eauto.
            econstructor; eauto.
            inv match_match.
            econstructor; eauto.
          + val_inject_simpl.
      Qed.

      Lemma setIDPTE_spec_ref:
        compatsim (crel HDATA LDATA) (gensem setIDPTE_spec) setIDPTE_spec_low.
      Proof.
        compatsim_simpl (@match_AbData).
        assert (Hkern: kernel_mode d2
                       /\ 0 <= Int.unsigned i <= PDX Int.max_unsigned
                       /\ 0 <= Int.unsigned i0 <= PTX Int.max_unsigned
                       /\ PT d1' = PT d1
                       /\ exists p0, ZtoPerm (Int.unsigned i1) = Some p0).
        {
          inv match_related.
          unfold setIDPTE_spec in *.
          unfold IDPTE_Arg in *.
          subdestruct; refine_split'; trivial; try congruence.
          inv H1. reflexivity.
        }
        destruct Hkern as (Hkern & Hrange & Hrange' & HPT & p0 & Hipde).
        inv H0. generalize H2; intros HMAT. specialize (H2 _ Hrange _ Hrange').
        destruct H2 as [_[_ [HV _]]].
        specialize (Mem.valid_access_store _ _ _ _
                                           (Vint (Int.repr ((Int.unsigned i * 1024 + Int.unsigned i0) * 4096 +
                                                            Int.unsigned i1)))
                                           HV); intros [m0 HST].
        refine_split; eauto.
        - econstructor; eauto.
          simpl; lift_trivial. rewrite HST. reflexivity.
        - pose proof H1 as Hspec.
          functional inversion Hspec; subst; simpl in *.
          split; eauto 1; pattern2_refinement_simpl.
          + inv match_related; simpl in *; split; simpl; try eassumption.
          + econstructor; eauto 1; simpl in *.
            {
              inv H. esplit; eauto. intros.
              specialize (H0 _ H). inv H0.
              split; intros. specialize (H11 _ H0).
              destruct H11 as (v & HLD & HV' & HM).
              erewrite Mem.load_store_other; eauto.
              - refine_split'; eauto.
                eapply Mem.store_valid_access_1; eauto.
              - left. red; intros; subst.
                specialize (genv_vars_inj _ _ _ _ H3 H10).
                intros. contra_inv.
            }
            {
              econstructor; eauto 1; intros. subst pde'.
              * destruct (zeq i2 (Int.unsigned i)); subst.
                { (* i2 = int.unsigned i*)
                  rewrite ZMap.gss.
                  specialize (HMAT _ H0).
                  destruct (zeq j (Int.unsigned i0)); subst.
                  { (* j = Int.unsigned i0 *)
                    rewrite ZMap.gss. refine_split'.
                    - eapply Mem.load_store_same; eauto.
                    - eapply Mem.store_valid_access_1; eauto.
                    - simpl. econstructor; eauto.
                      rewrite Int.unsigned_repr. reflexivity.
                      exploit ZtoPerm_range; eauto. intros.
                      rewrite_omega.
                  }
                  { (* j <> Int.unsigned i0 *)
                    specialize (HMAT _ H10).
                    destruct HMAT as [v1[HL1[HV1 HM1]]].
                    refine_split'.
                    - erewrite Mem.load_store_other; eauto.
                      right; simpl.
                      destruct (zle (j + 1) (Int.unsigned i0)).
                      + left. omega.
                      + right. omega.
                    - eapply Mem.store_valid_access_1; eauto.
                    - rewrite ZMap.gso; auto.
                  }
                }
                { (* i2 <> int.unsigned i*)
                  rewrite ZMap.gso; auto.
                  specialize (HMAT _ H0 _ H10).
                  destruct HMAT as [v1[HL1[HV1 HM1]]].
                  refine_split'; eauto.
                  - erewrite Mem.load_store_other; eauto.
                    right; simpl.
                    destruct (zle (i2 + 1) (Int.unsigned i)).
                    + left. rewrite_omega.
                    + right. rewrite_omega.
                  - eapply Mem.store_valid_access_1; eauto.
                }
            }
      Qed.

    End FRESH_PRIM.

  End WITHMEM.

End Refinement.


(* *********************************************************************)
(*                                                                     *)
(*            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 VM: PIPC                                     *)
(*                                                                     *)
(*          Provide the abstraction of ipc channel                     *)
(*                                                                     *)
(*          Haozhong Zhang <haozhong.zhang@yale.edu>                   *)
(*          Ronghui Gu <ronghui.gu@yale.edu>                           *)
(*                                                                     *)
(*          Yale Flint Group                                           *)
(*                                                                     *)
(* *********************************************************************)

(** This file defines the abstract data and the primitives for the PIPC layer,
which will introduce the primtives of thread*)
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 INVLemmaProc.

Require Import AbstractDataType.

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

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

  Local Open Scope Z_scope.

  Context `{real_params: RealParams}.

  (** **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 -> AbTCBStrong_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);
        valid_curid: 0 <= cid abd < num_proc;
        correct_curid: pg abd = true -> CurIDValid (cid abd) (AC abd) (abtcb abd);
        single_curid: pg abd = true -> SingleRun (cid abd) (abtcb abd);
        (*valid_chan: pg abd = true -> ChanPool_Valid (chpool abd)*)
        valid_chan: pg abd = true -> SyncChanPool_Valid (syncchpool abd)
      }.

  (** ** Definition of the abstract state ops *)
  Global Instance pipc_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.
      - repeat rewrite ZMap.gi; intuition.
    Qed.

    (** ** Definition of the abstract state *)
    Global Instance pipc_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.
        - intros; apply CurIDValid_gss_ac; 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.
          - apply CurIDValid_gss_ac; 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 thread_spawn_inv: DNewInvariants thread_spawn_spec.
    Proof.
      constructor; intros; inv H0;
      unfold thread_spawn_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.
        + eapply AbTCBStrong_range_gss_READY; eauto.
        + eapply AbQCorrect_range_gss_enqueue; eauto.
        + unfold update_cusage, update_cchildren; apply NotInQ_gso_ac_true; auto.
          zmap_simpl; repeat apply NotInQ_gso_true; auto.
        + eapply QCount_gss_spawn; eauto.
          eapply AbTCBStrong_range_impl; eauto.
          split; [|split; [|eauto]].
          assert (Hpos:= cvalid_child_id_pos _ valid_container0 _ Hdestruct3 0); omega.
          apply cvalid_unused_next_child; auto.
        + eapply InQ_gss_spawn; eauto.
          eapply AbTCBStrong_range_impl; eauto.
          split; [|split; [|eauto]].
          assert (Hpos:= cvalid_child_id_pos _ valid_container0 _ Hdestruct3 0); omega.
          apply cvalid_unused_next_child; auto.
        + unfold update_cusage, update_cchildren; apply CurIDValid_gso_neq_true; auto.
          zmap_simpl; repeat apply CurIDValid_gss_ac; auto.
          assert (Hneq:= cvalid_child_id_neq _ valid_container0 _ Hdestruct3); zmap_simpl.
          apply cvalid_unused_next_child; auto.
        + eapply SingleRun_gso_state_READY; eauto.
    Qed.

    Local Opaque remove.

    Global Instance thread_yield_inv: ThreadScheduleInvariants thread_yield_spec.
    Proof.
      constructor; intros; functional inversion H.
      - inv H1. constructor; trivial.
        eapply kctxt_inject_neutral_gss_mem; eauto.
      - inv H0. subst.
        assert (HOS: 0<= num_chan <= num_chan) by omega.
        exploit last_range_AbQ; eauto. intros Hrange.
        constructor; auto; simpl in *; intros; try congruence.
        + eapply AbTCBStrong_range_gss_RUN; eauto.
          eapply AbTCBStrong_range_gss_READY; eauto.
        + eapply AbQCorrect_range_gss_remove'; eauto.
          eapply list_range_enqueue; eauto.
          eapply AbQCorrect_range_impl; eauto.
        + eapply NotInQ_gso_neg; eauto.
          eapply NotInQ_gso_ac; eauto.
          eapply correct_curid0; eauto.
        + eapply QCount_gss_yield; eauto.
        + eapply InQ_gss_yield; eauto.
        + eapply CurIDValid_gss_last; eauto.
        + eapply SingleRun_gss_gso_cid; eauto. congruence.
    Qed.

    Global Instance thread_sleep_inv: ThreadTransferInvariants thread_sleep_spec.
    Proof.
      constructor; intros; functional inversion H.
      - inv H1. constructor; trivial.
        eapply kctxt_inject_neutral_gss_mem; eauto.
      - inv H0. subst.
        assert (HOS: 0<= num_chan <= num_chan) by omega.
        assert (HNeq: 64 <> n') by omega.
        exploit last_range_AbQ; eauto. intros Hrange.
        assert (HOS': 0 <= n' <= num_proc) by omega.
        assert (Hcid: ZMap.get (cid d) (abtcb d) = AbTCBValid RUN (-1))
          by (eapply correct_curid0; eauto).
        constructor; auto; simpl in *; intros; try congruence.
        + eapply AbTCBStrong_range_gss_RUN; eauto.
          eapply AbTCBStrong_range_gss_SLEEP; eauto.
        + eapply AbQCorrect_range_gss_remove; eauto.
          * eapply AbQCorrect_range_gss_enqueue; eauto.
          * rewrite ZMap.gso; eauto.
        + eapply NotInQ_gso_neg; eauto.
          eapply NotInQ_gso_ac; eauto.
          eapply correct_curid0; eauto.
        + eapply QCount_gss_remove; eauto.
          * eapply QCount_gss_enqueue; eauto.
          * rewrite ZMap.gso; eauto.
        + eapply InQ_gss_remove; eauto.
          * eapply InQ_gss_enqueue; eauto.
          * eapply QCount_gss_enqueue; eauto.
          * rewrite ZMap.gso; eauto.
          * apply last_correct; eauto.
        + eapply CurIDValid_gss_last; eauto.
        + eapply SingleRun_gss_gso_cid; eauto. congruence.
    Qed.

    (*Global Instance sendto_chan_inv: PreservesInvariants sendto_chan_spec.
    Proof.
      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.
      eapply ChanPool_Valid_gss; eauto.
    Qed.*)

    Section THREAD_WAKEUP.

      Lemma thread_wakeup_high_level_inv:
        forall d d' n,
          thread_wakeup_spec n d = Some d' ->
          high_level_invariant d ->
          high_level_invariant d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        inv H0. constructor; simpl; eauto; intros.
        - eapply AbTCBStrong_range_gss_READY; eauto.
        - eapply AbQCorrect_range_gss_wakeup; eauto.
        - clear valid_curid0. eapply NotInQ_InQ_gss_wakeup; eauto.
        - eapply QCount_gss_wakeup; eauto.
        - eapply InQ_gss_wakeup; eauto.
        - eapply CurIDValid_gso_tcb; eauto.
          eapply last_neq_cid; eauto. omega.
        - eapply SingleRun_gso_state_READY; eauto.
      Qed.

      Lemma thread_wakeup_low_level_inv:
        forall d d' n n',
          thread_wakeup_spec n 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 thread_wakeup_kernel_mode:
        forall d d' n,
          thread_wakeup_spec n d = Some d' ->
          kernel_mode d ->
          kernel_mode d'.
      Proof.
        intros. functional inversion H; subst; eauto.
      Qed.

      Global Instance thread_wakeup_inv: PreservesInvariants thread_wakeup_spec.
      Proof.
        preserves_invariants_simpl'.
        - eapply thread_wakeup_low_level_inv; eassumption.
        - eapply thread_wakeup_high_level_inv; eassumption.
        - eapply thread_wakeup_kernel_mode; eassumption.
      Qed.

    End THREAD_WAKEUP.

    (*Section RECEIVE_CHAN.

      Lemma receive_chan_high_level_inv:
        forall d d' n,
          receive_chan_spec d = Some (d', n) ->
          high_level_invariant d ->
          high_level_invariant d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        exploit thread_wakeup_high_level_inv; eauto.
        intros Hh. inv Hh. constructor; eauto 2; simpl; intros.
        eapply ChanPool_Valid_gss; eauto.
      Qed.

      Lemma receive_chan_low_level_inv:
        forall d d' n n',
          receive_chan_spec d = Some (d', n) ->
          low_level_invariant n' d ->
          low_level_invariant n' d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        exploit thread_wakeup_low_level_inv; eauto.
        intros Hh. inv Hh. constructor; eauto 2.
      Qed.

      Lemma receive_chan_kernel_mode:
        forall d d' n,
          receive_chan_spec d = Some (d', n) ->
          kernel_mode d ->
          kernel_mode d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        exploit thread_wakeup_kernel_mode; eauto.
      Qed.

      Global Instance receive_chan_inv: PreservesInvariants receive_chan_spec.
      Proof.
        preserves_invariants_simpl'.
        - eapply receive_chan_low_level_inv; eassumption.
        - eapply receive_chan_high_level_inv; eassumption.
        - eapply receive_chan_kernel_mode; eassumption.
      Qed.

    End RECEIVE_CHAN.*)

    Global Instance syncsendto_chan_pre_inv: PreservesInvariants syncsendto_chan_pre_spec.
    Proof.
      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.
      eapply SyncChanPool_Valid_gss; eauto.
    Qed.

    Global Instance syncsendto_chan_post_inv: PreservesInvariants syncsendto_chan_post_spec.
    Proof.
      preserves_invariants_simpl low_level_invariant high_level_invariant; eauto 2.
      eapply SyncChanPool_Valid_gss; eauto.
    Qed.

    Section MEMCPY.

      Lemma flatmem_copy_high_level_inv:
        forall d d' from to len,
          flatmem_copy_spec len to from d = Some d'
          -> high_level_invariant d
          -> high_level_invariant d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        inv H0.
        constructor; simpl; intros;
        try eapply dirty_ppage_gss_copy; eauto.
      Qed.

      Lemma flatmem_copy_low_level_inv:
        forall d d' from to len n,
          flatmem_copy_spec len to from d = Some d'
          -> low_level_invariant n d
          -> low_level_invariant n d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        inv H0. constructor; eauto 2.
      Qed.

      Lemma flatmem_copy_kernel_mode:
        forall d d' from to len,
          flatmem_copy_spec len to from d = Some d'
          -> kernel_mode d
          -> kernel_mode d'.
      Proof.
        intros. functional inversion H; subst; eauto.
      Qed.

    End MEMCPY.

    Section SYNCRECEIVE_CHAN.

      Lemma syncreceive_chan_high_level_inv:
        forall fromid vaddr count d d' n,
          syncreceive_chan_spec fromid vaddr count d = Some (d', n) ->
          high_level_invariant d ->
          high_level_invariant d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        exploit thread_wakeup_high_level_inv; eauto.
        exploit flatmem_copy_high_level_inv; eauto.
        intros Hh. inv Hh. constructor; eauto 2; simpl; intros.
        eapply SyncChanPool_Valid_gss; eauto.
      Qed.

      Lemma syncreceive_chan_low_level_inv:
        forall fromid vaddr count d d' n n',
          syncreceive_chan_spec fromid vaddr count d = Some (d', n) ->
          low_level_invariant n' d ->
          low_level_invariant n' d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        exploit thread_wakeup_low_level_inv; eauto.
        exploit flatmem_copy_low_level_inv; eauto.
        intros Hh. inv Hh. constructor; eauto 2.
      Qed.

      Lemma syncreceive_chan_kernel_mode:
        forall fromid vaddr count d d' n,
          syncreceive_chan_spec fromid vaddr count d = Some (d', n) ->
          kernel_mode d ->
          kernel_mode d'.
      Proof.
        intros. functional inversion H; subst; eauto.
        exploit thread_wakeup_kernel_mode; eauto.
        exploit flatmem_copy_kernel_mode; eauto.
      Qed.

      Global Instance syncreceive_chan_inv: PreservesInvariants syncreceive_chan_spec.
      Proof.
        preserves_invariants_simpl'.
        - eapply syncreceive_chan_low_level_inv; eassumption.
        - eapply syncreceive_chan_high_level_inv; eassumption.
        - eapply syncreceive_chan_kernel_mode; eassumption.
      Qed.

    End SYNCRECEIVE_CHAN.

    Global Instance proc_init_inv: PreservesInvariants proc_init_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_strong_range'; eauto.
      - apply real_abq_range; auto.
      - eapply real_abtcb_pb_notInQ'; eauto.
      - eapply real_abtcb_abq_QCount'; eauto.
      - eapply real_abq_tcb_inQ; eauto.
      - omega.
      - eapply real_abtcb_AC_CurIDValid; eauto.
      - eapply real_abtcb_SingleRun; eauto.
      - eapply real_syncchpool_valid'; 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 pipc_fresh : compatlayer (cdata RData) :=
    syncreceive_chan ↦ gensem syncreceive_chan_spec
                  ⊕ syncsendto_chan_pre ↦ gensem syncsendto_chan_pre_spec
                  ⊕ syncsendto_chan_post ↦ gensem syncsendto_chan_post_spec
                  ⊕ proc_init ↦ gensem proc_init_spec.

  Definition pipc_passthrough : compatlayer (cdata RData) :=
    fload ↦ gensem fload_spec
          ⊕ fstore ↦ gensem fstore_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
          ⊕ shared_mem_status ↦ gensem shared_mem_status_spec
          ⊕ offer_shared_mem ↦ gensem offer_shared_mem_spec

          ⊕ get_curid ↦ gensem get_curid_spec
          ⊕ thread_spawn ↦ dnew_compatsem thread_spawn_spec
          ⊕ thread_wakeup ↦ gensem thread_wakeup_spec

          ⊕ pt_in ↦ primcall_general_compatsem' ptin_spec (prim_ident:= pt_in)
          ⊕ pt_out ↦ primcall_general_compatsem' ptout_spec (prim_ident:= pt_out)
          ⊕ 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

          ⊕ thread_yield ↦ primcall_thread_schedule_compatsem thread_yield_spec (prim_ident:= thread_yield)
          ⊕ thread_sleep ↦ primcall_thread_transfer_compatsem thread_sleep_spec

          ⊕ accessors ↦ {| exec_load := @exec_loadex; exec_store := @exec_storeex |}.

  Definition pipc : compatlayer (cdata RData) := pipc_fresh ⊕ pipc_passthrough.

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

End WITHMEM.