Subversion Repositories HelenOS

Rev

Rev 2183 | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed

  1. /*
  2.  * Copyright (c) 2001-2006 Jakub Jermar
  3.  * All rights reserved.
  4.  *
  5.  * Redistribution and use in source and binary forms, with or without
  6.  * modification, are permitted provided that the following conditions
  7.  * are met:
  8.  *
  9.  * - Redistributions of source code must retain the above copyright
  10.  *   notice, this list of conditions and the following disclaimer.
  11.  * - Redistributions in binary form must reproduce the above copyright
  12.  *   notice, this list of conditions and the following disclaimer in the
  13.  *   documentation and/or other materials provided with the distribution.
  14.  * - The name of the author may not be used to endorse or promote products
  15.  *   derived from this software without specific prior written permission.
  16.  *
  17.  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  18.  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  19.  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  20.  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  21.  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  22.  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  23.  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  24.  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  25.  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  26.  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  27.  */
  28.  
  29. /** @addtogroup genericmm
  30.  * @{
  31.  */
  32.  
  33. /**
  34.  * @file
  35.  * @brief   Address space related functions.
  36.  *
  37.  * This file contains address space manipulation functions.
  38.  * Roughly speaking, this is a higher-level client of
  39.  * Virtual Address Translation (VAT) subsystem.
  40.  *
  41.  * Functionality provided by this file allows one to
  42.  * create address spaces and create, resize and share
  43.  * address space areas.
  44.  *
  45.  * @see page.c
  46.  *
  47.  */
  48.  
  49. #include <mm/as.h>
  50. #include <arch/mm/as.h>
  51. #include <mm/page.h>
  52. #include <mm/frame.h>
  53. #include <mm/slab.h>
  54. #include <mm/tlb.h>
  55. #include <arch/mm/page.h>
  56. #include <genarch/mm/page_pt.h>
  57. #include <genarch/mm/page_ht.h>
  58. #include <mm/asid.h>
  59. #include <arch/mm/asid.h>
  60. #include <preemption.h>
  61. #include <synch/spinlock.h>
  62. #include <synch/mutex.h>
  63. #include <adt/list.h>
  64. #include <adt/btree.h>
  65. #include <proc/task.h>
  66. #include <proc/thread.h>
  67. #include <arch/asm.h>
  68. #include <panic.h>
  69. #include <debug.h>
  70. #include <print.h>
  71. #include <memstr.h>
  72. #include <macros.h>
  73. #include <arch.h>
  74. #include <errno.h>
  75. #include <config.h>
  76. #include <align.h>
  77. #include <arch/types.h>
  78. #include <syscall/copy.h>
  79. #include <arch/interrupt.h>
  80.  
  81. #ifdef CONFIG_VIRT_IDX_DCACHE
  82. #include <arch/mm/cache.h>
  83. #endif /* CONFIG_VIRT_IDX_DCACHE */
  84.  
  85. #ifndef __OBJC__
  86. /**
  87.  * Each architecture decides what functions will be used to carry out
  88.  * address space operations such as creating or locking page tables.
  89.  */
  90. as_operations_t *as_operations = NULL;
  91.  
  92. /**
  93.  * Slab for as_t objects.
  94.  */
  95. static slab_cache_t *as_slab;
  96. #endif
  97.  
  98. /**
  99.  * This lock serializes access to the ASID subsystem.
  100.  * It protects:
  101.  * - inactive_as_with_asid_head list
  102.  * - as->asid for each as of the as_t type
  103.  * - asids_allocated counter
  104.  */
  105. SPINLOCK_INITIALIZE(asidlock);
  106.  
  107. /**
  108.  * This list contains address spaces that are not active on any
  109.  * processor and that have valid ASID.
  110.  */
  111. LIST_INITIALIZE(inactive_as_with_asid_head);
  112.  
  113. /** Kernel address space. */
  114. as_t *AS_KERNEL = NULL;
  115.  
  116. static int area_flags_to_page_flags(int aflags);
  117. static as_area_t *find_area_and_lock(as_t *as, uintptr_t va);
  118. static bool check_area_conflicts(as_t *as, uintptr_t va, size_t size,
  119.     as_area_t *avoid_area);
  120. static void sh_info_remove_reference(share_info_t *sh_info);
  121.  
  122. #ifndef __OBJC__
  123. static int as_constructor(void *obj, int flags)
  124. {
  125.     as_t *as = (as_t *) obj;
  126.     int rc;
  127.  
  128.     link_initialize(&as->inactive_as_with_asid_link);
  129.     mutex_initialize(&as->lock);   
  130.    
  131.     rc = as_constructor_arch(as, flags);
  132.    
  133.     return rc;
  134. }
  135.  
  136. static int as_destructor(void *obj)
  137. {
  138.     as_t *as = (as_t *) obj;
  139.  
  140.     return as_destructor_arch(as);
  141. }
  142. #endif
  143.  
  144. /** Initialize address space subsystem. */
  145. void as_init(void)
  146. {
  147.     as_arch_init();
  148.  
  149. #ifndef __OBJC__
  150.     as_slab = slab_cache_create("as_slab", sizeof(as_t), 0,
  151.         as_constructor, as_destructor, SLAB_CACHE_MAGDEFERRED);
  152. #endif
  153.    
  154.     AS_KERNEL = as_create(FLAG_AS_KERNEL);
  155.     if (!AS_KERNEL)
  156.         panic("can't create kernel address space\n");
  157.    
  158. }
  159.  
  160. /** Create address space.
  161.  *
  162.  * @param flags Flags that influence way in wich the address space is created.
  163.  */
  164. as_t *as_create(int flags)
  165. {
  166.     as_t *as;
  167.  
  168. #ifdef __OBJC__
  169.     as = [as_t new];
  170.     link_initialize(&as->inactive_as_with_asid_link);
  171.     mutex_initialize(&as->lock);   
  172.     (void) as_constructor_arch(as, flags);
  173. #else
  174.     as = (as_t *) slab_alloc(as_slab, 0);
  175. #endif
  176.     (void) as_create_arch(as, 0);
  177.    
  178.     btree_create(&as->as_area_btree);
  179.    
  180.     if (flags & FLAG_AS_KERNEL)
  181.         as->asid = ASID_KERNEL;
  182.     else
  183.         as->asid = ASID_INVALID;
  184.    
  185.     atomic_set(&as->refcount, 0);
  186.     as->cpu_refcount = 0;
  187. #ifdef AS_PAGE_TABLE
  188.     as->genarch.page_table = page_table_create(flags);
  189. #else
  190.     page_table_create(flags);
  191. #endif
  192.  
  193.     return as;
  194. }
  195.  
  196. /** Destroy adress space.
  197.  *
  198.  * When there are no tasks referencing this address space (i.e. its refcount is
  199.  * zero), the address space can be destroyed.
  200.  *
  201.  * We know that we don't hold any spinlock.
  202.  */
  203. void as_destroy(as_t *as)
  204. {
  205.     ipl_t ipl;
  206.     bool cond;
  207.     DEADLOCK_PROBE_INIT(p_asidlock);
  208.  
  209.     ASSERT(atomic_get(&as->refcount) == 0);
  210.    
  211.     /*
  212.      * Since there is no reference to this area,
  213.      * it is safe not to lock its mutex.
  214.      */
  215.  
  216.     /*
  217.      * We need to avoid deadlock between TLB shootdown and asidlock.
  218.      * We therefore try to take asid conditionally and if we don't succeed,
  219.      * we enable interrupts and try again. This is done while preemption is
  220.      * disabled to prevent nested context switches. We also depend on the
  221.      * fact that so far no spinlocks are held.
  222.      */
  223.     preemption_disable();
  224.     ipl = interrupts_read();
  225. retry:
  226.     interrupts_disable();
  227.     if (!spinlock_trylock(&asidlock)) {
  228.         interrupts_enable();
  229.         DEADLOCK_PROBE(p_asidlock, DEADLOCK_THRESHOLD);
  230.         goto retry;
  231.     }
  232.     preemption_enable();    /* Interrupts disabled, enable preemption */
  233.     if (as->asid != ASID_INVALID && as != AS_KERNEL) {
  234.         if (as != AS && as->cpu_refcount == 0)
  235.             list_remove(&as->inactive_as_with_asid_link);
  236.         asid_put(as->asid);
  237.     }
  238.     spinlock_unlock(&asidlock);
  239.  
  240.     /*
  241.      * Destroy address space areas of the address space.
  242.      * The B+tree must be walked carefully because it is
  243.      * also being destroyed.
  244.      */
  245.     for (cond = true; cond; ) {
  246.         btree_node_t *node;
  247.  
  248.         ASSERT(!list_empty(&as->as_area_btree.leaf_head));
  249.         node = list_get_instance(as->as_area_btree.leaf_head.next,
  250.             btree_node_t, leaf_link);
  251.  
  252.         if ((cond = node->keys)) {
  253.             as_area_destroy(as, node->key[0]);
  254.         }
  255.     }
  256.  
  257.     btree_destroy(&as->as_area_btree);
  258. #ifdef AS_PAGE_TABLE
  259.     page_table_destroy(as->genarch.page_table);
  260. #else
  261.     page_table_destroy(NULL);
  262. #endif
  263.  
  264.     interrupts_restore(ipl);
  265.  
  266. #ifdef __OBJC__
  267.     [as free];
  268. #else
  269.     slab_free(as_slab, as);
  270. #endif
  271. }
  272.  
  273. /** Create address space area of common attributes.
  274.  *
  275.  * The created address space area is added to the target address space.
  276.  *
  277.  * @param as Target address space.
  278.  * @param flags Flags of the area memory.
  279.  * @param size Size of area.
  280.  * @param base Base address of area.
  281.  * @param attrs Attributes of the area.
  282.  * @param backend Address space area backend. NULL if no backend is used.
  283.  * @param backend_data NULL or a pointer to an array holding two void *.
  284.  *
  285.  * @return Address space area on success or NULL on failure.
  286.  */
  287. as_area_t *
  288. as_area_create(as_t *as, int flags, size_t size, uintptr_t base, int attrs,
  289.            mem_backend_t *backend, mem_backend_data_t *backend_data)
  290. {
  291.     ipl_t ipl;
  292.     as_area_t *a;
  293.    
  294.     if (base % PAGE_SIZE)
  295.         return NULL;
  296.  
  297.     if (!size)
  298.         return NULL;
  299.  
  300.     /* Writeable executable areas are not supported. */
  301.     if ((flags & AS_AREA_EXEC) && (flags & AS_AREA_WRITE))
  302.         return NULL;
  303.    
  304.     ipl = interrupts_disable();
  305.     mutex_lock(&as->lock);
  306.    
  307.     if (!check_area_conflicts(as, base, size, NULL)) {
  308.         mutex_unlock(&as->lock);
  309.         interrupts_restore(ipl);
  310.         return NULL;
  311.     }
  312.    
  313.     a = (as_area_t *) malloc(sizeof(as_area_t), 0);
  314.  
  315.     mutex_initialize(&a->lock);
  316.    
  317.     a->as = as;
  318.     a->flags = flags;
  319.     a->attributes = attrs;
  320.     a->pages = SIZE2FRAMES(size);
  321.     a->base = base;
  322.     a->sh_info = NULL;
  323.     a->backend = backend;
  324.     if (backend_data)
  325.         a->backend_data = *backend_data;
  326.     else
  327.         memsetb((uintptr_t) &a->backend_data, sizeof(a->backend_data),
  328.             0);
  329.  
  330.     btree_create(&a->used_space);
  331.    
  332.     btree_insert(&as->as_area_btree, base, (void *) a, NULL);
  333.  
  334.     mutex_unlock(&as->lock);
  335.     interrupts_restore(ipl);
  336.  
  337.     return a;
  338. }
  339.  
  340. /** Find address space area and change it.
  341.  *
  342.  * @param as Address space.
  343.  * @param address Virtual address belonging to the area to be changed. Must be
  344.  *     page-aligned.
  345.  * @param size New size of the virtual memory block starting at address.
  346.  * @param flags Flags influencing the remap operation. Currently unused.
  347.  *
  348.  * @return Zero on success or a value from @ref errno.h otherwise.
  349.  */
  350. int as_area_resize(as_t *as, uintptr_t address, size_t size, int flags)
  351. {
  352.     as_area_t *area;
  353.     ipl_t ipl;
  354.     size_t pages;
  355.    
  356.     ipl = interrupts_disable();
  357.     mutex_lock(&as->lock);
  358.    
  359.     /*
  360.      * Locate the area.
  361.      */
  362.     area = find_area_and_lock(as, address);
  363.     if (!area) {
  364.         mutex_unlock(&as->lock);
  365.         interrupts_restore(ipl);
  366.         return ENOENT;
  367.     }
  368.  
  369.     if (area->backend == &phys_backend) {
  370.         /*
  371.          * Remapping of address space areas associated
  372.          * with memory mapped devices is not supported.
  373.          */
  374.         mutex_unlock(&area->lock);
  375.         mutex_unlock(&as->lock);
  376.         interrupts_restore(ipl);
  377.         return ENOTSUP;
  378.     }
  379.     if (area->sh_info) {
  380.         /*
  381.          * Remapping of shared address space areas
  382.          * is not supported.
  383.          */
  384.         mutex_unlock(&area->lock);
  385.         mutex_unlock(&as->lock);
  386.         interrupts_restore(ipl);
  387.         return ENOTSUP;
  388.     }
  389.  
  390.     pages = SIZE2FRAMES((address - area->base) + size);
  391.     if (!pages) {
  392.         /*
  393.          * Zero size address space areas are not allowed.
  394.          */
  395.         mutex_unlock(&area->lock);
  396.         mutex_unlock(&as->lock);
  397.         interrupts_restore(ipl);
  398.         return EPERM;
  399.     }
  400.    
  401.     if (pages < area->pages) {
  402.         bool cond;
  403.         uintptr_t start_free = area->base + pages*PAGE_SIZE;
  404.  
  405.         /*
  406.          * Shrinking the area.
  407.          * No need to check for overlaps.
  408.          */
  409.  
  410.         /*
  411.          * Start TLB shootdown sequence.
  412.          */
  413.         tlb_shootdown_start(TLB_INVL_PAGES, AS->asid, area->base +
  414.             pages * PAGE_SIZE, area->pages - pages);
  415.  
  416.         /*
  417.          * Remove frames belonging to used space starting from
  418.          * the highest addresses downwards until an overlap with
  419.          * the resized address space area is found. Note that this
  420.          * is also the right way to remove part of the used_space
  421.          * B+tree leaf list.
  422.          */    
  423.         for (cond = true; cond;) {
  424.             btree_node_t *node;
  425.        
  426.             ASSERT(!list_empty(&area->used_space.leaf_head));
  427.             node =
  428.                 list_get_instance(area->used_space.leaf_head.prev,
  429.                 btree_node_t, leaf_link);
  430.             if ((cond = (bool) node->keys)) {
  431.                 uintptr_t b = node->key[node->keys - 1];
  432.                 count_t c =
  433.                     (count_t) node->value[node->keys - 1];
  434.                 int i = 0;
  435.            
  436.                 if (overlaps(b, c * PAGE_SIZE, area->base,
  437.                     pages * PAGE_SIZE)) {
  438.                    
  439.                     if (b + c * PAGE_SIZE <= start_free) {
  440.                         /*
  441.                          * The whole interval fits
  442.                          * completely in the resized
  443.                          * address space area.
  444.                          */
  445.                         break;
  446.                     }
  447.        
  448.                     /*
  449.                      * Part of the interval corresponding
  450.                      * to b and c overlaps with the resized
  451.                      * address space area.
  452.                      */
  453.        
  454.                     cond = false;   /* we are almost done */
  455.                     i = (start_free - b) >> PAGE_WIDTH;
  456.                     if (!used_space_remove(area, start_free,
  457.                         c - i))
  458.                         panic("Could not remove used "
  459.                             "space.\n");
  460.                 } else {
  461.                     /*
  462.                      * The interval of used space can be
  463.                      * completely removed.
  464.                      */
  465.                     if (!used_space_remove(area, b, c))
  466.                         panic("Could not remove used "
  467.                             "space.\n");
  468.                 }
  469.            
  470.                 for (; i < c; i++) {
  471.                     pte_t *pte;
  472.            
  473.                     page_table_lock(as, false);
  474.                     pte = page_mapping_find(as, b +
  475.                         i * PAGE_SIZE);
  476.                     ASSERT(pte && PTE_VALID(pte) &&
  477.                         PTE_PRESENT(pte));
  478.                     if (area->backend &&
  479.                         area->backend->frame_free) {
  480.                         area->backend->frame_free(area,
  481.                             b + i * PAGE_SIZE,
  482.                             PTE_GET_FRAME(pte));
  483.                     }
  484.                     page_mapping_remove(as, b +
  485.                         i * PAGE_SIZE);
  486.                     page_table_unlock(as, false);
  487.                 }
  488.             }
  489.         }
  490.  
  491.         /*
  492.          * Finish TLB shootdown sequence.
  493.          */
  494.  
  495.         tlb_invalidate_pages(as->asid, area->base + pages * PAGE_SIZE,
  496.             area->pages - pages);
  497.         /*
  498.          * Invalidate software translation caches (e.g. TSB on sparc64).
  499.          */
  500.         as_invalidate_translation_cache(as, area->base +
  501.             pages * PAGE_SIZE, area->pages - pages);
  502.         tlb_shootdown_finalize();
  503.        
  504.     } else {
  505.         /*
  506.          * Growing the area.
  507.          * Check for overlaps with other address space areas.
  508.          */
  509.         if (!check_area_conflicts(as, address, pages * PAGE_SIZE,
  510.             area)) {
  511.             mutex_unlock(&area->lock);
  512.             mutex_unlock(&as->lock);       
  513.             interrupts_restore(ipl);
  514.             return EADDRNOTAVAIL;
  515.         }
  516.     }
  517.  
  518.     area->pages = pages;
  519.    
  520.     mutex_unlock(&area->lock);
  521.     mutex_unlock(&as->lock);
  522.     interrupts_restore(ipl);
  523.  
  524.     return 0;
  525. }
  526.  
  527. /** Destroy address space area.
  528.  *
  529.  * @param as Address space.
  530.  * @param address Address withing the area to be deleted.
  531.  *
  532.  * @return Zero on success or a value from @ref errno.h on failure.
  533.  */
  534. int as_area_destroy(as_t *as, uintptr_t address)
  535. {
  536.     as_area_t *area;
  537.     uintptr_t base;
  538.     link_t *cur;
  539.     ipl_t ipl;
  540.  
  541.     ipl = interrupts_disable();
  542.     mutex_lock(&as->lock);
  543.  
  544.     area = find_area_and_lock(as, address);
  545.     if (!area) {
  546.         mutex_unlock(&as->lock);
  547.         interrupts_restore(ipl);
  548.         return ENOENT;
  549.     }
  550.  
  551.     base = area->base;
  552.  
  553.     /*
  554.      * Start TLB shootdown sequence.
  555.      */
  556.     tlb_shootdown_start(TLB_INVL_PAGES, as->asid, area->base, area->pages);
  557.  
  558.     /*
  559.      * Visit only the pages mapped by used_space B+tree.
  560.      */
  561.     for (cur = area->used_space.leaf_head.next;
  562.         cur != &area->used_space.leaf_head; cur = cur->next) {
  563.         btree_node_t *node;
  564.         int i;
  565.        
  566.         node = list_get_instance(cur, btree_node_t, leaf_link);
  567.         for (i = 0; i < node->keys; i++) {
  568.             uintptr_t b = node->key[i];
  569.             count_t j;
  570.             pte_t *pte;
  571.            
  572.             for (j = 0; j < (count_t) node->value[i]; j++) {
  573.                 page_table_lock(as, false);
  574.                 pte = page_mapping_find(as, b + j * PAGE_SIZE);
  575.                 ASSERT(pte && PTE_VALID(pte) &&
  576.                     PTE_PRESENT(pte));
  577.                 if (area->backend &&
  578.                     area->backend->frame_free) {
  579.                     area->backend->frame_free(area, b +
  580.                         j * PAGE_SIZE, PTE_GET_FRAME(pte));
  581.                 }
  582.                 page_mapping_remove(as, b + j * PAGE_SIZE);            
  583.                 page_table_unlock(as, false);
  584.             }
  585.         }
  586.     }
  587.  
  588.     /*
  589.      * Finish TLB shootdown sequence.
  590.      */
  591.  
  592.     tlb_invalidate_pages(as->asid, area->base, area->pages);
  593.     /*
  594.      * Invalidate potential software translation caches (e.g. TSB on
  595.      * sparc64).
  596.      */
  597.     as_invalidate_translation_cache(as, area->base, area->pages);
  598.     tlb_shootdown_finalize();
  599.    
  600.     btree_destroy(&area->used_space);
  601.  
  602.     area->attributes |= AS_AREA_ATTR_PARTIAL;
  603.    
  604.     if (area->sh_info)
  605.         sh_info_remove_reference(area->sh_info);
  606.        
  607.     mutex_unlock(&area->lock);
  608.  
  609.     /*
  610.      * Remove the empty area from address space.
  611.      */
  612.     btree_remove(&as->as_area_btree, base, NULL);
  613.    
  614.     free(area);
  615.    
  616.     mutex_unlock(&as->lock);
  617.     interrupts_restore(ipl);
  618.     return 0;
  619. }
  620.  
  621. /** Share address space area with another or the same address space.
  622.  *
  623.  * Address space area mapping is shared with a new address space area.
  624.  * If the source address space area has not been shared so far,
  625.  * a new sh_info is created. The new address space area simply gets the
  626.  * sh_info of the source area. The process of duplicating the
  627.  * mapping is done through the backend share function.
  628.  *
  629.  * @param src_as Pointer to source address space.
  630.  * @param src_base Base address of the source address space area.
  631.  * @param acc_size Expected size of the source area.
  632.  * @param dst_as Pointer to destination address space.
  633.  * @param dst_base Target base address.
  634.  * @param dst_flags_mask Destination address space area flags mask.
  635.  *
  636.  * @return Zero on success or ENOENT if there is no such task or if there is no
  637.  * such address space area, EPERM if there was a problem in accepting the area
  638.  * or ENOMEM if there was a problem in allocating destination address space
  639.  * area. ENOTSUP is returned if the address space area backend does not support
  640.  * sharing.
  641.  */
  642. int as_area_share(as_t *src_as, uintptr_t src_base, size_t acc_size,
  643.           as_t *dst_as, uintptr_t dst_base, int dst_flags_mask)
  644. {
  645.     ipl_t ipl;
  646.     int src_flags;
  647.     size_t src_size;
  648.     as_area_t *src_area, *dst_area;
  649.     share_info_t *sh_info;
  650.     mem_backend_t *src_backend;
  651.     mem_backend_data_t src_backend_data;
  652.    
  653.     ipl = interrupts_disable();
  654.     mutex_lock(&src_as->lock);
  655.     src_area = find_area_and_lock(src_as, src_base);
  656.     if (!src_area) {
  657.         /*
  658.          * Could not find the source address space area.
  659.          */
  660.         mutex_unlock(&src_as->lock);
  661.         interrupts_restore(ipl);
  662.         return ENOENT;
  663.     }
  664.  
  665.     if (!src_area->backend || !src_area->backend->share) {
  666.         /*
  667.          * There is no backend or the backend does not
  668.          * know how to share the area.
  669.          */
  670.         mutex_unlock(&src_area->lock);
  671.         mutex_unlock(&src_as->lock);
  672.         interrupts_restore(ipl);
  673.         return ENOTSUP;
  674.     }
  675.    
  676.     src_size = src_area->pages * PAGE_SIZE;
  677.     src_flags = src_area->flags;
  678.     src_backend = src_area->backend;
  679.     src_backend_data = src_area->backend_data;
  680.  
  681.     /* Share the cacheable flag from the original mapping */
  682.     if (src_flags & AS_AREA_CACHEABLE)
  683.         dst_flags_mask |= AS_AREA_CACHEABLE;
  684.  
  685.     if (src_size != acc_size ||
  686.         (src_flags & dst_flags_mask) != dst_flags_mask) {
  687.         mutex_unlock(&src_area->lock);
  688.         mutex_unlock(&src_as->lock);
  689.         interrupts_restore(ipl);
  690.         return EPERM;
  691.     }
  692.  
  693.     /*
  694.      * Now we are committed to sharing the area.
  695.      * First, prepare the area for sharing.
  696.      * Then it will be safe to unlock it.
  697.      */
  698.     sh_info = src_area->sh_info;
  699.     if (!sh_info) {
  700.         sh_info = (share_info_t *) malloc(sizeof(share_info_t), 0);
  701.         mutex_initialize(&sh_info->lock);
  702.         sh_info->refcount = 2;
  703.         btree_create(&sh_info->pagemap);
  704.         src_area->sh_info = sh_info;
  705.     } else {
  706.         mutex_lock(&sh_info->lock);
  707.         sh_info->refcount++;
  708.         mutex_unlock(&sh_info->lock);
  709.     }
  710.  
  711.     src_area->backend->share(src_area);
  712.  
  713.     mutex_unlock(&src_area->lock);
  714.     mutex_unlock(&src_as->lock);
  715.  
  716.     /*
  717.      * Create copy of the source address space area.
  718.      * The destination area is created with AS_AREA_ATTR_PARTIAL
  719.      * attribute set which prevents race condition with
  720.      * preliminary as_page_fault() calls.
  721.      * The flags of the source area are masked against dst_flags_mask
  722.      * to support sharing in less privileged mode.
  723.      */
  724.     dst_area = as_area_create(dst_as, dst_flags_mask, src_size, dst_base,
  725.         AS_AREA_ATTR_PARTIAL, src_backend, &src_backend_data);
  726.     if (!dst_area) {
  727.         /*
  728.          * Destination address space area could not be created.
  729.          */
  730.         sh_info_remove_reference(sh_info);
  731.        
  732.         interrupts_restore(ipl);
  733.         return ENOMEM;
  734.     }
  735.  
  736.     /*
  737.      * Now the destination address space area has been
  738.      * fully initialized. Clear the AS_AREA_ATTR_PARTIAL
  739.      * attribute and set the sh_info.
  740.      */
  741.     mutex_lock(&dst_as->lock); 
  742.     mutex_lock(&dst_area->lock);
  743.     dst_area->attributes &= ~AS_AREA_ATTR_PARTIAL;
  744.     dst_area->sh_info = sh_info;
  745.     mutex_unlock(&dst_area->lock);
  746.     mutex_unlock(&dst_as->lock);   
  747.  
  748.     interrupts_restore(ipl);
  749.    
  750.     return 0;
  751. }
  752.  
  753. /** Check access mode for address space area.
  754.  *
  755.  * The address space area must be locked prior to this call.
  756.  *
  757.  * @param area Address space area.
  758.  * @param access Access mode.
  759.  *
  760.  * @return False if access violates area's permissions, true otherwise.
  761.  */
  762. bool as_area_check_access(as_area_t *area, pf_access_t access)
  763. {
  764.     int flagmap[] = {
  765.         [PF_ACCESS_READ] = AS_AREA_READ,
  766.         [PF_ACCESS_WRITE] = AS_AREA_WRITE,
  767.         [PF_ACCESS_EXEC] = AS_AREA_EXEC
  768.     };
  769.  
  770.     if (!(area->flags & flagmap[access]))
  771.         return false;
  772.    
  773.     return true;
  774. }
  775.  
  776. /** Handle page fault within the current address space.
  777.  *
  778.  * This is the high-level page fault handler. It decides
  779.  * whether the page fault can be resolved by any backend
  780.  * and if so, it invokes the backend to resolve the page
  781.  * fault.
  782.  *
  783.  * Interrupts are assumed disabled.
  784.  *
  785.  * @param page Faulting page.
  786.  * @param access Access mode that caused the fault (i.e. read/write/exec).
  787.  * @param istate Pointer to interrupted state.
  788.  *
  789.  * @return AS_PF_FAULT on page fault, AS_PF_OK on success or AS_PF_DEFER if the
  790.  *     fault was caused by copy_to_uspace() or copy_from_uspace().
  791.  */
  792. int as_page_fault(uintptr_t page, pf_access_t access, istate_t *istate)
  793. {
  794.     pte_t *pte;
  795.     as_area_t *area;
  796.    
  797.     if (!THREAD)
  798.         return AS_PF_FAULT;
  799.        
  800.     ASSERT(AS);
  801.  
  802.     mutex_lock(&AS->lock);
  803.     area = find_area_and_lock(AS, page);   
  804.     if (!area) {
  805.         /*
  806.          * No area contained mapping for 'page'.
  807.          * Signal page fault to low-level handler.
  808.          */
  809.         mutex_unlock(&AS->lock);
  810.         goto page_fault;
  811.     }
  812.  
  813.     if (area->attributes & AS_AREA_ATTR_PARTIAL) {
  814.         /*
  815.          * The address space area is not fully initialized.
  816.          * Avoid possible race by returning error.
  817.          */
  818.         mutex_unlock(&area->lock);
  819.         mutex_unlock(&AS->lock);
  820.         goto page_fault;       
  821.     }
  822.  
  823.     if (!area->backend || !area->backend->page_fault) {
  824.         /*
  825.          * The address space area is not backed by any backend
  826.          * or the backend cannot handle page faults.
  827.          */
  828.         mutex_unlock(&area->lock);
  829.         mutex_unlock(&AS->lock);
  830.         goto page_fault;       
  831.     }
  832.  
  833.     page_table_lock(AS, false);
  834.    
  835.     /*
  836.      * To avoid race condition between two page faults
  837.      * on the same address, we need to make sure
  838.      * the mapping has not been already inserted.
  839.      */
  840.     if ((pte = page_mapping_find(AS, page))) {
  841.         if (PTE_PRESENT(pte)) {
  842.             if (((access == PF_ACCESS_READ) && PTE_READABLE(pte)) ||
  843.                 (access == PF_ACCESS_WRITE && PTE_WRITABLE(pte)) ||
  844.                 (access == PF_ACCESS_EXEC && PTE_EXECUTABLE(pte))) {
  845.                 page_table_unlock(AS, false);
  846.                 mutex_unlock(&area->lock);
  847.                 mutex_unlock(&AS->lock);
  848.                 return AS_PF_OK;
  849.             }
  850.         }
  851.     }
  852.    
  853.     /*
  854.      * Resort to the backend page fault handler.
  855.      */
  856.     if (area->backend->page_fault(area, page, access) != AS_PF_OK) {
  857.         page_table_unlock(AS, false);
  858.         mutex_unlock(&area->lock);
  859.         mutex_unlock(&AS->lock);
  860.         goto page_fault;
  861.     }
  862.    
  863.     page_table_unlock(AS, false);
  864.     mutex_unlock(&area->lock);
  865.     mutex_unlock(&AS->lock);
  866.     return AS_PF_OK;
  867.  
  868. page_fault:
  869.     if (THREAD->in_copy_from_uspace) {
  870.         THREAD->in_copy_from_uspace = false;
  871.         istate_set_retaddr(istate,
  872.             (uintptr_t) &memcpy_from_uspace_failover_address);
  873.     } else if (THREAD->in_copy_to_uspace) {
  874.         THREAD->in_copy_to_uspace = false;
  875.         istate_set_retaddr(istate,
  876.             (uintptr_t) &memcpy_to_uspace_failover_address);
  877.     } else {
  878.         return AS_PF_FAULT;
  879.     }
  880.  
  881.     return AS_PF_DEFER;
  882. }
  883.  
  884. /** Switch address spaces.
  885.  *
  886.  * Note that this function cannot sleep as it is essentially a part of
  887.  * scheduling. Sleeping here would lead to deadlock on wakeup. Another
  888.  * thing which is forbidden in this context is locking the address space.
  889.  *
  890.  * When this function is enetered, no spinlocks may be held.
  891.  *
  892.  * @param old Old address space or NULL.
  893.  * @param new New address space.
  894.  */
  895. void as_switch(as_t *old_as, as_t *new_as)
  896. {
  897.     DEADLOCK_PROBE_INIT(p_asidlock);
  898.     preemption_disable();
  899. retry:
  900.     (void) interrupts_disable();
  901.     if (!spinlock_trylock(&asidlock)) {
  902.         /*
  903.          * Avoid deadlock with TLB shootdown.
  904.          * We can enable interrupts here because
  905.          * preemption is disabled. We should not be
  906.          * holding any other lock.
  907.          */
  908.         (void) interrupts_enable();
  909.         DEADLOCK_PROBE(p_asidlock, DEADLOCK_THRESHOLD);
  910.         goto retry;
  911.     }
  912.     preemption_enable();
  913.  
  914.     /*
  915.      * First, take care of the old address space.
  916.      */
  917.     if (old_as) {
  918.         ASSERT(old_as->cpu_refcount);
  919.         if((--old_as->cpu_refcount == 0) && (old_as != AS_KERNEL)) {
  920.             /*
  921.              * The old address space is no longer active on
  922.              * any processor. It can be appended to the
  923.              * list of inactive address spaces with assigned
  924.              * ASID.
  925.              */
  926.             ASSERT(old_as->asid != ASID_INVALID);
  927.             list_append(&old_as->inactive_as_with_asid_link,
  928.                 &inactive_as_with_asid_head);
  929.         }
  930.  
  931.         /*
  932.          * Perform architecture-specific tasks when the address space
  933.          * is being removed from the CPU.
  934.          */
  935.         as_deinstall_arch(old_as);
  936.     }
  937.  
  938.     /*
  939.      * Second, prepare the new address space.
  940.      */
  941.     if ((new_as->cpu_refcount++ == 0) && (new_as != AS_KERNEL)) {
  942.         if (new_as->asid != ASID_INVALID)
  943.             list_remove(&new_as->inactive_as_with_asid_link);
  944.         else
  945.             new_as->asid = asid_get();
  946.     }
  947. #ifdef AS_PAGE_TABLE
  948.     SET_PTL0_ADDRESS(new_as->genarch.page_table);
  949. #endif
  950.    
  951.     /*
  952.      * Perform architecture-specific steps.
  953.      * (e.g. write ASID to hardware register etc.)
  954.      */
  955.     as_install_arch(new_as);
  956.  
  957.     spinlock_unlock(&asidlock);
  958.    
  959.     AS = new_as;
  960. }
  961.  
  962. /** Convert address space area flags to page flags.
  963.  *
  964.  * @param aflags Flags of some address space area.
  965.  *
  966.  * @return Flags to be passed to page_mapping_insert().
  967.  */
  968. int area_flags_to_page_flags(int aflags)
  969. {
  970.     int flags;
  971.  
  972.     flags = PAGE_USER | PAGE_PRESENT;
  973.    
  974.     if (aflags & AS_AREA_READ)
  975.         flags |= PAGE_READ;
  976.        
  977.     if (aflags & AS_AREA_WRITE)
  978.         flags |= PAGE_WRITE;
  979.    
  980.     if (aflags & AS_AREA_EXEC)
  981.         flags |= PAGE_EXEC;
  982.    
  983.     if (aflags & AS_AREA_CACHEABLE)
  984.         flags |= PAGE_CACHEABLE;
  985.        
  986.     return flags;
  987. }
  988.  
  989. /** Compute flags for virtual address translation subsytem.
  990.  *
  991.  * The address space area must be locked.
  992.  * Interrupts must be disabled.
  993.  *
  994.  * @param a Address space area.
  995.  *
  996.  * @return Flags to be used in page_mapping_insert().
  997.  */
  998. int as_area_get_flags(as_area_t *a)
  999. {
  1000.     return area_flags_to_page_flags(a->flags);
  1001. }
  1002.  
  1003. /** Create page table.
  1004.  *
  1005.  * Depending on architecture, create either address space
  1006.  * private or global page table.
  1007.  *
  1008.  * @param flags Flags saying whether the page table is for kernel address space.
  1009.  *
  1010.  * @return First entry of the page table.
  1011.  */
  1012. pte_t *page_table_create(int flags)
  1013. {
  1014. #ifdef __OBJC__
  1015.     return [as_t page_table_create: flags];
  1016. #else
  1017.     ASSERT(as_operations);
  1018.     ASSERT(as_operations->page_table_create);
  1019.    
  1020.     return as_operations->page_table_create(flags);
  1021. #endif
  1022. }
  1023.  
  1024. /** Destroy page table.
  1025.  *
  1026.  * Destroy page table in architecture specific way.
  1027.  *
  1028.  * @param page_table Physical address of PTL0.
  1029.  */
  1030. void page_table_destroy(pte_t *page_table)
  1031. {
  1032. #ifdef __OBJC__
  1033.     return [as_t page_table_destroy: page_table];
  1034. #else
  1035.     ASSERT(as_operations);
  1036.     ASSERT(as_operations->page_table_destroy);
  1037.    
  1038.     as_operations->page_table_destroy(page_table);
  1039. #endif
  1040. }
  1041.  
  1042. /** Lock page table.
  1043.  *
  1044.  * This function should be called before any page_mapping_insert(),
  1045.  * page_mapping_remove() and page_mapping_find().
  1046.  *
  1047.  * Locking order is such that address space areas must be locked
  1048.  * prior to this call. Address space can be locked prior to this
  1049.  * call in which case the lock argument is false.
  1050.  *
  1051.  * @param as Address space.
  1052.  * @param lock If false, do not attempt to lock as->lock.
  1053.  */
  1054. void page_table_lock(as_t *as, bool lock)
  1055. {
  1056. #ifdef __OBJC__
  1057.     [as page_table_lock: lock];
  1058. #else
  1059.     ASSERT(as_operations);
  1060.     ASSERT(as_operations->page_table_lock);
  1061.    
  1062.     as_operations->page_table_lock(as, lock);
  1063. #endif
  1064. }
  1065.  
  1066. /** Unlock page table.
  1067.  *
  1068.  * @param as Address space.
  1069.  * @param unlock If false, do not attempt to unlock as->lock.
  1070.  */
  1071. void page_table_unlock(as_t *as, bool unlock)
  1072. {
  1073. #ifdef __OBJC__
  1074.     [as page_table_unlock: unlock];
  1075. #else
  1076.     ASSERT(as_operations);
  1077.     ASSERT(as_operations->page_table_unlock);
  1078.    
  1079.     as_operations->page_table_unlock(as, unlock);
  1080. #endif
  1081. }
  1082.  
  1083.  
  1084. /** Find address space area and lock it.
  1085.  *
  1086.  * The address space must be locked and interrupts must be disabled.
  1087.  *
  1088.  * @param as Address space.
  1089.  * @param va Virtual address.
  1090.  *
  1091.  * @return Locked address space area containing va on success or NULL on
  1092.  *     failure.
  1093.  */
  1094. as_area_t *find_area_and_lock(as_t *as, uintptr_t va)
  1095. {
  1096.     as_area_t *a;
  1097.     btree_node_t *leaf, *lnode;
  1098.     int i;
  1099.    
  1100.     a = (as_area_t *) btree_search(&as->as_area_btree, va, &leaf);
  1101.     if (a) {
  1102.         /* va is the base address of an address space area */
  1103.         mutex_lock(&a->lock);
  1104.         return a;
  1105.     }
  1106.    
  1107.     /*
  1108.      * Search the leaf node and the righmost record of its left neighbour
  1109.      * to find out whether this is a miss or va belongs to an address
  1110.      * space area found there.
  1111.      */
  1112.    
  1113.     /* First, search the leaf node itself. */
  1114.     for (i = 0; i < leaf->keys; i++) {
  1115.         a = (as_area_t *) leaf->value[i];
  1116.         mutex_lock(&a->lock);
  1117.         if ((a->base <= va) && (va < a->base + a->pages * PAGE_SIZE)) {
  1118.             return a;
  1119.         }
  1120.         mutex_unlock(&a->lock);
  1121.     }
  1122.  
  1123.     /*
  1124.      * Second, locate the left neighbour and test its last record.
  1125.      * Because of its position in the B+tree, it must have base < va.
  1126.      */
  1127.     lnode = btree_leaf_node_left_neighbour(&as->as_area_btree, leaf);
  1128.     if (lnode) {
  1129.         a = (as_area_t *) lnode->value[lnode->keys - 1];
  1130.         mutex_lock(&a->lock);
  1131.         if (va < a->base + a->pages * PAGE_SIZE) {
  1132.             return a;
  1133.         }
  1134.         mutex_unlock(&a->lock);
  1135.     }
  1136.  
  1137.     return NULL;
  1138. }
  1139.  
  1140. /** Check area conflicts with other areas.
  1141.  *
  1142.  * The address space must be locked and interrupts must be disabled.
  1143.  *
  1144.  * @param as Address space.
  1145.  * @param va Starting virtual address of the area being tested.
  1146.  * @param size Size of the area being tested.
  1147.  * @param avoid_area Do not touch this area.
  1148.  *
  1149.  * @return True if there is no conflict, false otherwise.
  1150.  */
  1151. bool check_area_conflicts(as_t *as, uintptr_t va, size_t size,
  1152.               as_area_t *avoid_area)
  1153. {
  1154.     as_area_t *a;
  1155.     btree_node_t *leaf, *node;
  1156.     int i;
  1157.    
  1158.     /*
  1159.      * We don't want any area to have conflicts with NULL page.
  1160.      */
  1161.     if (overlaps(va, size, NULL, PAGE_SIZE))
  1162.         return false;
  1163.    
  1164.     /*
  1165.      * The leaf node is found in O(log n), where n is proportional to
  1166.      * the number of address space areas belonging to as.
  1167.      * The check for conflicts is then attempted on the rightmost
  1168.      * record in the left neighbour, the leftmost record in the right
  1169.      * neighbour and all records in the leaf node itself.
  1170.      */
  1171.    
  1172.     if ((a = (as_area_t *) btree_search(&as->as_area_btree, va, &leaf))) {
  1173.         if (a != avoid_area)
  1174.             return false;
  1175.     }
  1176.    
  1177.     /* First, check the two border cases. */
  1178.     if ((node = btree_leaf_node_left_neighbour(&as->as_area_btree, leaf))) {
  1179.         a = (as_area_t *) node->value[node->keys - 1];
  1180.         mutex_lock(&a->lock);
  1181.         if (overlaps(va, size, a->base, a->pages * PAGE_SIZE)) {
  1182.             mutex_unlock(&a->lock);
  1183.             return false;
  1184.         }
  1185.         mutex_unlock(&a->lock);
  1186.     }
  1187.     node = btree_leaf_node_right_neighbour(&as->as_area_btree, leaf);
  1188.     if (node) {
  1189.         a = (as_area_t *) node->value[0];
  1190.         mutex_lock(&a->lock);
  1191.         if (overlaps(va, size, a->base, a->pages * PAGE_SIZE)) {
  1192.             mutex_unlock(&a->lock);
  1193.             return false;
  1194.         }
  1195.         mutex_unlock(&a->lock);
  1196.     }
  1197.    
  1198.     /* Second, check the leaf node. */
  1199.     for (i = 0; i < leaf->keys; i++) {
  1200.         a = (as_area_t *) leaf->value[i];
  1201.    
  1202.         if (a == avoid_area)
  1203.             continue;
  1204.    
  1205.         mutex_lock(&a->lock);
  1206.         if (overlaps(va, size, a->base, a->pages * PAGE_SIZE)) {
  1207.             mutex_unlock(&a->lock);
  1208.             return false;
  1209.         }
  1210.         mutex_unlock(&a->lock);
  1211.     }
  1212.  
  1213.     /*
  1214.      * So far, the area does not conflict with other areas.
  1215.      * Check if it doesn't conflict with kernel address space.
  1216.      */  
  1217.     if (!KERNEL_ADDRESS_SPACE_SHADOWED) {
  1218.         return !overlaps(va, size,
  1219.             KERNEL_ADDRESS_SPACE_START,
  1220.             KERNEL_ADDRESS_SPACE_END - KERNEL_ADDRESS_SPACE_START);
  1221.     }
  1222.  
  1223.     return true;
  1224. }
  1225.  
  1226. /** Return size of the address space area with given base.  */
  1227. size_t as_get_size(uintptr_t base)
  1228. {
  1229.     ipl_t ipl;
  1230.     as_area_t *src_area;
  1231.     size_t size;
  1232.  
  1233.     ipl = interrupts_disable();
  1234.     src_area = find_area_and_lock(AS, base);
  1235.     if (src_area){
  1236.         size = src_area->pages * PAGE_SIZE;
  1237.         mutex_unlock(&src_area->lock);
  1238.     } else {
  1239.         size = 0;
  1240.     }
  1241.     interrupts_restore(ipl);
  1242.     return size;
  1243. }
  1244.  
  1245. /** Mark portion of address space area as used.
  1246.  *
  1247.  * The address space area must be already locked.
  1248.  *
  1249.  * @param a Address space area.
  1250.  * @param page First page to be marked.
  1251.  * @param count Number of page to be marked.
  1252.  *
  1253.  * @return 0 on failure and 1 on success.
  1254.  */
  1255. int used_space_insert(as_area_t *a, uintptr_t page, count_t count)
  1256. {
  1257.     btree_node_t *leaf, *node;
  1258.     count_t pages;
  1259.     int i;
  1260.  
  1261.     ASSERT(page == ALIGN_DOWN(page, PAGE_SIZE));
  1262.     ASSERT(count);
  1263.  
  1264.     pages = (count_t) btree_search(&a->used_space, page, &leaf);
  1265.     if (pages) {
  1266.         /*
  1267.          * We hit the beginning of some used space.
  1268.          */
  1269.         return 0;
  1270.     }
  1271.  
  1272.     if (!leaf->keys) {
  1273.         btree_insert(&a->used_space, page, (void *) count, leaf);
  1274.         return 1;
  1275.     }
  1276.  
  1277.     node = btree_leaf_node_left_neighbour(&a->used_space, leaf);
  1278.     if (node) {
  1279.         uintptr_t left_pg = node->key[node->keys - 1];
  1280.         uintptr_t right_pg = leaf->key[0];
  1281.         count_t left_cnt = (count_t) node->value[node->keys - 1];
  1282.         count_t right_cnt = (count_t) leaf->value[0];
  1283.        
  1284.         /*
  1285.          * Examine the possibility that the interval fits
  1286.          * somewhere between the rightmost interval of
  1287.          * the left neigbour and the first interval of the leaf.
  1288.          */
  1289.          
  1290.         if (page >= right_pg) {
  1291.             /* Do nothing. */
  1292.         } else if (overlaps(page, count * PAGE_SIZE, left_pg,
  1293.             left_cnt * PAGE_SIZE)) {
  1294.             /* The interval intersects with the left interval. */
  1295.             return 0;
  1296.         } else if (overlaps(page, count * PAGE_SIZE, right_pg,
  1297.             right_cnt * PAGE_SIZE)) {
  1298.             /* The interval intersects with the right interval. */
  1299.             return 0;          
  1300.         } else if ((page == left_pg + left_cnt * PAGE_SIZE) &&
  1301.             (page + count * PAGE_SIZE == right_pg)) {
  1302.             /*
  1303.              * The interval can be added by merging the two already
  1304.              * present intervals.
  1305.              */
  1306.             node->value[node->keys - 1] += count + right_cnt;
  1307.             btree_remove(&a->used_space, right_pg, leaf);
  1308.             return 1;
  1309.         } else if (page == left_pg + left_cnt * PAGE_SIZE) {
  1310.             /*
  1311.              * The interval can be added by simply growing the left
  1312.              * interval.
  1313.              */
  1314.             node->value[node->keys - 1] += count;
  1315.             return 1;
  1316.         } else if (page + count * PAGE_SIZE == right_pg) {
  1317.             /*
  1318.              * The interval can be addded by simply moving base of
  1319.              * the right interval down and increasing its size
  1320.              * accordingly.
  1321.              */
  1322.             leaf->value[0] += count;
  1323.             leaf->key[0] = page;
  1324.             return 1;
  1325.         } else {
  1326.             /*
  1327.              * The interval is between both neigbouring intervals,
  1328.              * but cannot be merged with any of them.
  1329.              */
  1330.             btree_insert(&a->used_space, page, (void *) count,
  1331.                 leaf);
  1332.             return 1;
  1333.         }
  1334.     } else if (page < leaf->key[0]) {
  1335.         uintptr_t right_pg = leaf->key[0];
  1336.         count_t right_cnt = (count_t) leaf->value[0];
  1337.    
  1338.         /*
  1339.          * Investigate the border case in which the left neighbour does
  1340.          * not exist but the interval fits from the left.
  1341.          */
  1342.          
  1343.         if (overlaps(page, count * PAGE_SIZE, right_pg,
  1344.             right_cnt * PAGE_SIZE)) {
  1345.             /* The interval intersects with the right interval. */
  1346.             return 0;
  1347.         } else if (page + count * PAGE_SIZE == right_pg) {
  1348.             /*
  1349.              * The interval can be added by moving the base of the
  1350.              * right interval down and increasing its size
  1351.              * accordingly.
  1352.              */
  1353.             leaf->key[0] = page;
  1354.             leaf->value[0] += count;
  1355.             return 1;
  1356.         } else {
  1357.             /*
  1358.              * The interval doesn't adjoin with the right interval.
  1359.              * It must be added individually.
  1360.              */
  1361.             btree_insert(&a->used_space, page, (void *) count,
  1362.                 leaf);
  1363.             return 1;
  1364.         }
  1365.     }
  1366.  
  1367.     node = btree_leaf_node_right_neighbour(&a->used_space, leaf);
  1368.     if (node) {
  1369.         uintptr_t left_pg = leaf->key[leaf->keys - 1];
  1370.         uintptr_t right_pg = node->key[0];
  1371.         count_t left_cnt = (count_t) leaf->value[leaf->keys - 1];
  1372.         count_t right_cnt = (count_t) node->value[0];
  1373.        
  1374.         /*
  1375.          * Examine the possibility that the interval fits
  1376.          * somewhere between the leftmost interval of
  1377.          * the right neigbour and the last interval of the leaf.
  1378.          */
  1379.  
  1380.         if (page < left_pg) {
  1381.             /* Do nothing. */
  1382.         } else if (overlaps(page, count * PAGE_SIZE, left_pg,
  1383.             left_cnt * PAGE_SIZE)) {
  1384.             /* The interval intersects with the left interval. */
  1385.             return 0;
  1386.         } else if (overlaps(page, count * PAGE_SIZE, right_pg,
  1387.             right_cnt * PAGE_SIZE)) {
  1388.             /* The interval intersects with the right interval. */
  1389.             return 0;          
  1390.         } else if ((page == left_pg + left_cnt * PAGE_SIZE) &&
  1391.             (page + count * PAGE_SIZE == right_pg)) {
  1392.             /*
  1393.              * The interval can be added by merging the two already
  1394.              * present intervals.
  1395.              * */
  1396.             leaf->value[leaf->keys - 1] += count + right_cnt;
  1397.             btree_remove(&a->used_space, right_pg, node);
  1398.             return 1;
  1399.         } else if (page == left_pg + left_cnt * PAGE_SIZE) {
  1400.             /*
  1401.              * The interval can be added by simply growing the left
  1402.              * interval.
  1403.              * */
  1404.             leaf->value[leaf->keys - 1] +=  count;
  1405.             return 1;
  1406.         } else if (page + count * PAGE_SIZE == right_pg) {
  1407.             /*
  1408.              * The interval can be addded by simply moving base of
  1409.              * the right interval down and increasing its size
  1410.              * accordingly.
  1411.              */
  1412.             node->value[0] += count;
  1413.             node->key[0] = page;
  1414.             return 1;
  1415.         } else {
  1416.             /*
  1417.              * The interval is between both neigbouring intervals,
  1418.              * but cannot be merged with any of them.
  1419.              */
  1420.             btree_insert(&a->used_space, page, (void *) count,
  1421.                 leaf);
  1422.             return 1;
  1423.         }
  1424.     } else if (page >= leaf->key[leaf->keys - 1]) {
  1425.         uintptr_t left_pg = leaf->key[leaf->keys - 1];
  1426.         count_t left_cnt = (count_t) leaf->value[leaf->keys - 1];
  1427.    
  1428.         /*
  1429.          * Investigate the border case in which the right neighbour
  1430.          * does not exist but the interval fits from the right.
  1431.          */
  1432.          
  1433.         if (overlaps(page, count * PAGE_SIZE, left_pg,
  1434.             left_cnt * PAGE_SIZE)) {
  1435.             /* The interval intersects with the left interval. */
  1436.             return 0;
  1437.         } else if (left_pg + left_cnt * PAGE_SIZE == page) {
  1438.             /*
  1439.              * The interval can be added by growing the left
  1440.              * interval.
  1441.              */
  1442.             leaf->value[leaf->keys - 1] += count;
  1443.             return 1;
  1444.         } else {
  1445.             /*
  1446.              * The interval doesn't adjoin with the left interval.
  1447.              * It must be added individually.
  1448.              */
  1449.             btree_insert(&a->used_space, page, (void *) count,
  1450.                 leaf);
  1451.             return 1;
  1452.         }
  1453.     }
  1454.    
  1455.     /*
  1456.      * Note that if the algorithm made it thus far, the interval can fit
  1457.      * only between two other intervals of the leaf. The two border cases
  1458.      * were already resolved.
  1459.      */
  1460.     for (i = 1; i < leaf->keys; i++) {
  1461.         if (page < leaf->key[i]) {
  1462.             uintptr_t left_pg = leaf->key[i - 1];
  1463.             uintptr_t right_pg = leaf->key[i];
  1464.             count_t left_cnt = (count_t) leaf->value[i - 1];
  1465.             count_t right_cnt = (count_t) leaf->value[i];
  1466.  
  1467.             /*
  1468.              * The interval fits between left_pg and right_pg.
  1469.              */
  1470.  
  1471.             if (overlaps(page, count * PAGE_SIZE, left_pg,
  1472.                 left_cnt * PAGE_SIZE)) {
  1473.                 /*
  1474.                  * The interval intersects with the left
  1475.                  * interval.
  1476.                  */
  1477.                 return 0;
  1478.             } else if (overlaps(page, count * PAGE_SIZE, right_pg,
  1479.                 right_cnt * PAGE_SIZE)) {
  1480.                 /*
  1481.                  * The interval intersects with the right
  1482.                  * interval.
  1483.                  */
  1484.                 return 0;          
  1485.             } else if ((page == left_pg + left_cnt * PAGE_SIZE) &&
  1486.                 (page + count * PAGE_SIZE == right_pg)) {
  1487.                 /*
  1488.                  * The interval can be added by merging the two
  1489.                  * already present intervals.
  1490.                  */
  1491.                 leaf->value[i - 1] += count + right_cnt;
  1492.                 btree_remove(&a->used_space, right_pg, leaf);
  1493.                 return 1;
  1494.             } else if (page == left_pg + left_cnt * PAGE_SIZE) {
  1495.                 /*
  1496.                  * The interval can be added by simply growing
  1497.                  * the left interval.
  1498.                  */
  1499.                 leaf->value[i - 1] += count;
  1500.                 return 1;
  1501.             } else if (page + count * PAGE_SIZE == right_pg) {
  1502.                 /*
  1503.                      * The interval can be addded by simply moving
  1504.                  * base of the right interval down and
  1505.                  * increasing its size accordingly.
  1506.                  */
  1507.                 leaf->value[i] += count;
  1508.                 leaf->key[i] = page;
  1509.                 return 1;
  1510.             } else {
  1511.                 /*
  1512.                  * The interval is between both neigbouring
  1513.                  * intervals, but cannot be merged with any of
  1514.                  * them.
  1515.                  */
  1516.                 btree_insert(&a->used_space, page,
  1517.                     (void *) count, leaf);
  1518.                 return 1;
  1519.             }
  1520.         }
  1521.     }
  1522.  
  1523.     panic("Inconsistency detected while adding %d pages of used space at "
  1524.         "%p.\n", count, page);
  1525. }
  1526.  
  1527. /** Mark portion of address space area as unused.
  1528.  *
  1529.  * The address space area must be already locked.
  1530.  *
  1531.  * @param a Address space area.
  1532.  * @param page First page to be marked.
  1533.  * @param count Number of page to be marked.
  1534.  *
  1535.  * @return 0 on failure and 1 on success.
  1536.  */
  1537. int used_space_remove(as_area_t *a, uintptr_t page, count_t count)
  1538. {
  1539.     btree_node_t *leaf, *node;
  1540.     count_t pages;
  1541.     int i;
  1542.  
  1543.     ASSERT(page == ALIGN_DOWN(page, PAGE_SIZE));
  1544.     ASSERT(count);
  1545.  
  1546.     pages = (count_t) btree_search(&a->used_space, page, &leaf);
  1547.     if (pages) {
  1548.         /*
  1549.          * We are lucky, page is the beginning of some interval.
  1550.          */
  1551.         if (count > pages) {
  1552.             return 0;
  1553.         } else if (count == pages) {
  1554.             btree_remove(&a->used_space, page, leaf);
  1555.             return 1;
  1556.         } else {
  1557.             /*
  1558.              * Find the respective interval.
  1559.              * Decrease its size and relocate its start address.
  1560.              */
  1561.             for (i = 0; i < leaf->keys; i++) {
  1562.                 if (leaf->key[i] == page) {
  1563.                     leaf->key[i] += count * PAGE_SIZE;
  1564.                     leaf->value[i] -= count;
  1565.                     return 1;
  1566.                 }
  1567.             }
  1568.             goto error;
  1569.         }
  1570.     }
  1571.  
  1572.     node = btree_leaf_node_left_neighbour(&a->used_space, leaf);
  1573.     if (node && page < leaf->key[0]) {
  1574.         uintptr_t left_pg = node->key[node->keys - 1];
  1575.         count_t left_cnt = (count_t) node->value[node->keys - 1];
  1576.  
  1577.         if (overlaps(left_pg, left_cnt * PAGE_SIZE, page,
  1578.             count * PAGE_SIZE)) {
  1579.             if (page + count * PAGE_SIZE ==
  1580.                 left_pg + left_cnt * PAGE_SIZE) {
  1581.                 /*
  1582.                  * The interval is contained in the rightmost
  1583.                  * interval of the left neighbour and can be
  1584.                  * removed by updating the size of the bigger
  1585.                  * interval.
  1586.                  */
  1587.                 node->value[node->keys - 1] -= count;
  1588.                 return 1;
  1589.             } else if (page + count * PAGE_SIZE <
  1590.                 left_pg + left_cnt*PAGE_SIZE) {
  1591.                 count_t new_cnt;
  1592.                
  1593.                 /*
  1594.                  * The interval is contained in the rightmost
  1595.                  * interval of the left neighbour but its
  1596.                  * removal requires both updating the size of
  1597.                  * the original interval and also inserting a
  1598.                  * new interval.
  1599.                  */
  1600.                 new_cnt = ((left_pg + left_cnt * PAGE_SIZE) -
  1601.                     (page + count*PAGE_SIZE)) >> PAGE_WIDTH;
  1602.                 node->value[node->keys - 1] -= count + new_cnt;
  1603.                 btree_insert(&a->used_space, page +
  1604.                     count * PAGE_SIZE, (void *) new_cnt, leaf);
  1605.                 return 1;
  1606.             }
  1607.         }
  1608.         return 0;
  1609.     } else if (page < leaf->key[0]) {
  1610.         return 0;
  1611.     }
  1612.    
  1613.     if (page > leaf->key[leaf->keys - 1]) {
  1614.         uintptr_t left_pg = leaf->key[leaf->keys - 1];
  1615.         count_t left_cnt = (count_t) leaf->value[leaf->keys - 1];
  1616.  
  1617.         if (overlaps(left_pg, left_cnt * PAGE_SIZE, page,
  1618.             count * PAGE_SIZE)) {
  1619.             if (page + count * PAGE_SIZE ==
  1620.                 left_pg + left_cnt * PAGE_SIZE) {
  1621.                 /*
  1622.                  * The interval is contained in the rightmost
  1623.                  * interval of the leaf and can be removed by
  1624.                  * updating the size of the bigger interval.
  1625.                  */
  1626.                 leaf->value[leaf->keys - 1] -= count;
  1627.                 return 1;
  1628.             } else if (page + count * PAGE_SIZE < left_pg +
  1629.                 left_cnt * PAGE_SIZE) {
  1630.                 count_t new_cnt;
  1631.                
  1632.                 /*
  1633.                  * The interval is contained in the rightmost
  1634.                  * interval of the leaf but its removal
  1635.                  * requires both updating the size of the
  1636.                  * original interval and also inserting a new
  1637.                  * interval.
  1638.                  */
  1639.                 new_cnt = ((left_pg + left_cnt * PAGE_SIZE) -
  1640.                     (page + count * PAGE_SIZE)) >> PAGE_WIDTH;
  1641.                 leaf->value[leaf->keys - 1] -= count + new_cnt;
  1642.                 btree_insert(&a->used_space, page +
  1643.                     count * PAGE_SIZE, (void *) new_cnt, leaf);
  1644.                 return 1;
  1645.             }
  1646.         }
  1647.         return 0;
  1648.     }  
  1649.    
  1650.     /*
  1651.      * The border cases have been already resolved.
  1652.      * Now the interval can be only between intervals of the leaf.
  1653.      */
  1654.     for (i = 1; i < leaf->keys - 1; i++) {
  1655.         if (page < leaf->key[i]) {
  1656.             uintptr_t left_pg = leaf->key[i - 1];
  1657.             count_t left_cnt = (count_t) leaf->value[i - 1];
  1658.  
  1659.             /*
  1660.              * Now the interval is between intervals corresponding
  1661.              * to (i - 1) and i.
  1662.              */
  1663.             if (overlaps(left_pg, left_cnt * PAGE_SIZE, page,
  1664.                 count * PAGE_SIZE)) {
  1665.                 if (page + count * PAGE_SIZE ==
  1666.                     left_pg + left_cnt*PAGE_SIZE) {
  1667.                     /*
  1668.                      * The interval is contained in the
  1669.                      * interval (i - 1) of the leaf and can
  1670.                      * be removed by updating the size of
  1671.                      * the bigger interval.
  1672.                      */
  1673.                     leaf->value[i - 1] -= count;
  1674.                     return 1;
  1675.                 } else if (page + count * PAGE_SIZE <
  1676.                     left_pg + left_cnt * PAGE_SIZE) {
  1677.                     count_t new_cnt;
  1678.                
  1679.                     /*
  1680.                      * The interval is contained in the
  1681.                      * interval (i - 1) of the leaf but its
  1682.                      * removal requires both updating the
  1683.                      * size of the original interval and
  1684.                      * also inserting a new interval.
  1685.                      */
  1686.                     new_cnt = ((left_pg +
  1687.                         left_cnt * PAGE_SIZE) -
  1688.                         (page + count * PAGE_SIZE)) >>
  1689.                         PAGE_WIDTH;
  1690.                     leaf->value[i - 1] -= count + new_cnt;
  1691.                     btree_insert(&a->used_space, page +
  1692.                         count * PAGE_SIZE, (void *) new_cnt,
  1693.                         leaf);
  1694.                     return 1;
  1695.                 }
  1696.             }
  1697.             return 0;
  1698.         }
  1699.     }
  1700.  
  1701. error:
  1702.     panic("Inconsistency detected while removing %d pages of used space "
  1703.         "from %p.\n", count, page);
  1704. }
  1705.  
  1706. /** Remove reference to address space area share info.
  1707.  *
  1708.  * If the reference count drops to 0, the sh_info is deallocated.
  1709.  *
  1710.  * @param sh_info Pointer to address space area share info.
  1711.  */
  1712. void sh_info_remove_reference(share_info_t *sh_info)
  1713. {
  1714.     bool dealloc = false;
  1715.  
  1716.     mutex_lock(&sh_info->lock);
  1717.     ASSERT(sh_info->refcount);
  1718.     if (--sh_info->refcount == 0) {
  1719.         dealloc = true;
  1720.         link_t *cur;
  1721.        
  1722.         /*
  1723.          * Now walk carefully the pagemap B+tree and free/remove
  1724.          * reference from all frames found there.
  1725.          */
  1726.         for (cur = sh_info->pagemap.leaf_head.next;
  1727.             cur != &sh_info->pagemap.leaf_head; cur = cur->next) {
  1728.             btree_node_t *node;
  1729.             int i;
  1730.            
  1731.             node = list_get_instance(cur, btree_node_t, leaf_link);
  1732.             for (i = 0; i < node->keys; i++)
  1733.                 frame_free((uintptr_t) node->value[i]);
  1734.         }
  1735.        
  1736.     }
  1737.     mutex_unlock(&sh_info->lock);
  1738.    
  1739.     if (dealloc) {
  1740.         btree_destroy(&sh_info->pagemap);
  1741.         free(sh_info);
  1742.     }
  1743. }
  1744.  
  1745. /*
  1746.  * Address space related syscalls.
  1747.  */
  1748.  
  1749. /** Wrapper for as_area_create(). */
  1750. unative_t sys_as_area_create(uintptr_t address, size_t size, int flags)
  1751. {
  1752.     if (as_area_create(AS, flags | AS_AREA_CACHEABLE, size, address,
  1753.         AS_AREA_ATTR_NONE, &anon_backend, NULL))
  1754.         return (unative_t) address;
  1755.     else
  1756.         return (unative_t) -1;
  1757. }
  1758.  
  1759. /** Wrapper for as_area_resize(). */
  1760. unative_t sys_as_area_resize(uintptr_t address, size_t size, int flags)
  1761. {
  1762.     return (unative_t) as_area_resize(AS, address, size, 0);
  1763. }
  1764.  
  1765. /** Wrapper for as_area_destroy(). */
  1766. unative_t sys_as_area_destroy(uintptr_t address)
  1767. {
  1768.     return (unative_t) as_area_destroy(AS, address);
  1769. }
  1770.  
  1771. /** Print out information about address space.
  1772.  *
  1773.  * @param as Address space.
  1774.  */
  1775. void as_print(as_t *as)
  1776. {
  1777.     ipl_t ipl;
  1778.    
  1779.     ipl = interrupts_disable();
  1780.     mutex_lock(&as->lock);
  1781.    
  1782.     /* print out info about address space areas */
  1783.     link_t *cur;
  1784.     for (cur = as->as_area_btree.leaf_head.next;
  1785.         cur != &as->as_area_btree.leaf_head; cur = cur->next) {
  1786.         btree_node_t *node;
  1787.        
  1788.         node = list_get_instance(cur, btree_node_t, leaf_link);
  1789.        
  1790.         int i;
  1791.         for (i = 0; i < node->keys; i++) {
  1792.             as_area_t *area = node->value[i];
  1793.        
  1794.             mutex_lock(&area->lock);
  1795.             printf("as_area: %p, base=%p, pages=%d (%p - %p)\n",
  1796.                 area, area->base, area->pages, area->base,
  1797.                 area->base + area->pages*PAGE_SIZE);
  1798.             mutex_unlock(&area->lock);
  1799.         }
  1800.     }
  1801.    
  1802.     mutex_unlock(&as->lock);
  1803.     interrupts_restore(ipl);
  1804. }
  1805.  
  1806. /** @}
  1807.  */
  1808.