Subversion Repositories HelenOS-historic

Rev

Rev 1436 | Rev 1461 | Go to most recent revision | 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. /**
  30.  * @file    as.c
  31.  * @brief   Address space related functions.
  32.  *
  33.  * This file contains address space manipulation functions.
  34.  * Roughly speaking, this is a higher-level client of
  35.  * Virtual Address Translation (VAT) subsystem.
  36.  *
  37.  * Functionality provided by this file allows one to
  38.  * create address space and create, resize and share
  39.  * address space areas.
  40.  *
  41.  * @see page.c
  42.  *
  43.  */
  44.  
  45. #include <mm/as.h>
  46. #include <arch/mm/as.h>
  47. #include <mm/page.h>
  48. #include <mm/frame.h>
  49. #include <mm/slab.h>
  50. #include <mm/tlb.h>
  51. #include <arch/mm/page.h>
  52. #include <genarch/mm/page_pt.h>
  53. #include <genarch/mm/page_ht.h>
  54. #include <mm/asid.h>
  55. #include <arch/mm/asid.h>
  56. #include <synch/spinlock.h>
  57. #include <synch/mutex.h>
  58. #include <adt/list.h>
  59. #include <adt/btree.h>
  60. #include <proc/task.h>
  61. #include <proc/thread.h>
  62. #include <arch/asm.h>
  63. #include <panic.h>
  64. #include <debug.h>
  65. #include <print.h>
  66. #include <memstr.h>
  67. #include <macros.h>
  68. #include <arch.h>
  69. #include <errno.h>
  70. #include <config.h>
  71. #include <align.h>
  72. #include <arch/types.h>
  73. #include <typedefs.h>
  74. #include <syscall/copy.h>
  75. #include <arch/interrupt.h>
  76.  
  77. as_operations_t *as_operations = NULL;
  78.  
  79. /** This lock protects inactive_as_with_asid_head list. It must be acquired before as_t mutex. */
  80. SPINLOCK_INITIALIZE(inactive_as_with_asid_lock);
  81.  
  82. /**
  83.  * This list contains address spaces that are not active on any
  84.  * processor and that have valid ASID.
  85.  */
  86. LIST_INITIALIZE(inactive_as_with_asid_head);
  87.  
  88. /** Kernel address space. */
  89. as_t *AS_KERNEL = NULL;
  90.  
  91. static int area_flags_to_page_flags(int aflags);
  92. static as_area_t *find_area_and_lock(as_t *as, __address va);
  93. static bool check_area_conflicts(as_t *as, __address va, size_t size, as_area_t *avoid_area);
  94. static void sh_info_remove_reference(share_info_t *sh_info);
  95.  
  96. /** Initialize address space subsystem. */
  97. void as_init(void)
  98. {
  99.     as_arch_init();
  100.     AS_KERNEL = as_create(FLAG_AS_KERNEL);
  101.     if (!AS_KERNEL)
  102.         panic("can't create kernel address space\n");
  103.    
  104. }
  105.  
  106. /** Create address space.
  107.  *
  108.  * @param flags Flags that influence way in wich the address space is created.
  109.  */
  110. as_t *as_create(int flags)
  111. {
  112.     as_t *as;
  113.  
  114.     as = (as_t *) malloc(sizeof(as_t), 0);
  115.     link_initialize(&as->inactive_as_with_asid_link);
  116.     mutex_initialize(&as->lock);
  117.     btree_create(&as->as_area_btree);
  118.    
  119.     if (flags & FLAG_AS_KERNEL)
  120.         as->asid = ASID_KERNEL;
  121.     else
  122.         as->asid = ASID_INVALID;
  123.    
  124.     as->cpu_refcount = 0;
  125.     as->page_table = page_table_create(flags);
  126.  
  127.     return as;
  128. }
  129.  
  130. /** Free Adress space */
  131. void as_free(as_t *as)
  132. {
  133.     ASSERT(as->cpu_refcount == 0);
  134.  
  135.     /* TODO: free as_areas and other resources held by as */
  136.     /* TODO: free page table */
  137.     free(as);
  138. }
  139.  
  140. /** Create address space area of common attributes.
  141.  *
  142.  * The created address space area is added to the target address space.
  143.  *
  144.  * @param as Target address space.
  145.  * @param flags Flags of the area memory.
  146.  * @param size Size of area.
  147.  * @param base Base address of area.
  148.  * @param attrs Attributes of the area.
  149.  * @param backend Address space area backend. NULL if no backend is used.
  150.  * @param backend_data NULL or a pointer to an array holding two void *.
  151.  *
  152.  * @return Address space area on success or NULL on failure.
  153.  */
  154. as_area_t *as_area_create(as_t *as, int flags, size_t size, __address base, int attrs,
  155.            mem_backend_t *backend, mem_backend_data_t *backend_data)
  156. {
  157.     ipl_t ipl;
  158.     as_area_t *a;
  159.    
  160.     if (base % PAGE_SIZE)
  161.         return NULL;
  162.  
  163.     if (!size)
  164.         return NULL;
  165.  
  166.     /* Writeable executable areas are not supported. */
  167.     if ((flags & AS_AREA_EXEC) && (flags & AS_AREA_WRITE))
  168.         return NULL;
  169.    
  170.     ipl = interrupts_disable();
  171.     mutex_lock(&as->lock);
  172.    
  173.     if (!check_area_conflicts(as, base, size, NULL)) {
  174.         mutex_unlock(&as->lock);
  175.         interrupts_restore(ipl);
  176.         return NULL;
  177.     }
  178.    
  179.     a = (as_area_t *) malloc(sizeof(as_area_t), 0);
  180.  
  181.     mutex_initialize(&a->lock);
  182.    
  183.     a->as = as;
  184.     a->flags = flags;
  185.     a->attributes = attrs;
  186.     a->pages = SIZE2FRAMES(size);
  187.     a->base = base;
  188.     a->sh_info = NULL;
  189.     a->backend = backend;
  190.     if (backend_data)
  191.         a->backend_data = *backend_data;
  192.     else
  193.         memsetb((__address) &a->backend_data, sizeof(a->backend_data), 0);
  194.  
  195.     btree_create(&a->used_space);
  196.    
  197.     btree_insert(&as->as_area_btree, base, (void *) a, NULL);
  198.  
  199.     mutex_unlock(&as->lock);
  200.     interrupts_restore(ipl);
  201.  
  202.     return a;
  203. }
  204.  
  205. /** Find address space area and change it.
  206.  *
  207.  * @param as Address space.
  208.  * @param address Virtual address belonging to the area to be changed. Must be page-aligned.
  209.  * @param size New size of the virtual memory block starting at address.
  210.  * @param flags Flags influencing the remap operation. Currently unused.
  211.  *
  212.  * @return Zero on success or a value from @ref errno.h otherwise.
  213.  */
  214. int as_area_resize(as_t *as, __address address, size_t size, int flags)
  215. {
  216.     as_area_t *area;
  217.     ipl_t ipl;
  218.     size_t pages;
  219.    
  220.     ipl = interrupts_disable();
  221.     mutex_lock(&as->lock);
  222.    
  223.     /*
  224.      * Locate the area.
  225.      */
  226.     area = find_area_and_lock(as, address);
  227.     if (!area) {
  228.         mutex_unlock(&as->lock);
  229.         interrupts_restore(ipl);
  230.         return ENOENT;
  231.     }
  232.  
  233.     if (area->backend == &phys_backend) {
  234.         /*
  235.          * Remapping of address space areas associated
  236.          * with memory mapped devices is not supported.
  237.          */
  238.         mutex_unlock(&area->lock);
  239.         mutex_unlock(&as->lock);
  240.         interrupts_restore(ipl);
  241.         return ENOTSUP;
  242.     }
  243.     if (area->sh_info) {
  244.         /*
  245.          * Remapping of shared address space areas
  246.          * is not supported.
  247.          */
  248.         mutex_unlock(&area->lock);
  249.         mutex_unlock(&as->lock);
  250.         interrupts_restore(ipl);
  251.         return ENOTSUP;
  252.     }
  253.  
  254.     pages = SIZE2FRAMES((address - area->base) + size);
  255.     if (!pages) {
  256.         /*
  257.          * Zero size address space areas are not allowed.
  258.          */
  259.         mutex_unlock(&area->lock);
  260.         mutex_unlock(&as->lock);
  261.         interrupts_restore(ipl);
  262.         return EPERM;
  263.     }
  264.    
  265.     if (pages < area->pages) {
  266.         bool cond;
  267.         __address start_free = area->base + pages*PAGE_SIZE;
  268.  
  269.         /*
  270.          * Shrinking the area.
  271.          * No need to check for overlaps.
  272.          */
  273.  
  274.         /*
  275.          * Start TLB shootdown sequence.
  276.          */
  277.         tlb_shootdown_start(TLB_INVL_PAGES, AS->asid, area->base + pages*PAGE_SIZE, area->pages - pages);
  278.  
  279.         /*
  280.          * Remove frames belonging to used space starting from
  281.          * the highest addresses downwards until an overlap with
  282.          * the resized address space area is found. Note that this
  283.          * is also the right way to remove part of the used_space
  284.          * B+tree leaf list.
  285.          */    
  286.         for (cond = true; cond;) {
  287.             btree_node_t *node;
  288.        
  289.             ASSERT(!list_empty(&area->used_space.leaf_head));
  290.             node = list_get_instance(area->used_space.leaf_head.prev, btree_node_t, leaf_link);
  291.             if ((cond = (bool) node->keys)) {
  292.                 __address b = node->key[node->keys - 1];
  293.                 count_t c = (count_t) node->value[node->keys - 1];
  294.                 int i = 0;
  295.            
  296.                 if (overlaps(b, c*PAGE_SIZE, area->base, pages*PAGE_SIZE)) {
  297.                    
  298.                     if (b + c*PAGE_SIZE <= start_free) {
  299.                         /*
  300.                          * The whole interval fits completely
  301.                          * in the resized address space area.
  302.                          */
  303.                         break;
  304.                     }
  305.        
  306.                     /*
  307.                      * Part of the interval corresponding to b and c
  308.                      * overlaps with the resized address space area.
  309.                      */
  310.        
  311.                     cond = false;   /* we are almost done */
  312.                     i = (start_free - b) >> PAGE_WIDTH;
  313.                     if (!used_space_remove(area, start_free, c - i))
  314.                         panic("Could not remove used space.");
  315.                 } else {
  316.                     /*
  317.                      * The interval of used space can be completely removed.
  318.                      */
  319.                     if (!used_space_remove(area, b, c))
  320.                         panic("Could not remove used space.\n");
  321.                 }
  322.            
  323.                 for (; i < c; i++) {
  324.                     pte_t *pte;
  325.            
  326.                     page_table_lock(as, false);
  327.                     pte = page_mapping_find(as, b + i*PAGE_SIZE);
  328.                     ASSERT(pte && PTE_VALID(pte) && PTE_PRESENT(pte));
  329.                     if (area->backend && area->backend->frame_free) {
  330.                         area->backend->frame_free(area,
  331.                             b + i*PAGE_SIZE, PTE_GET_FRAME(pte));
  332.                     }
  333.                     page_mapping_remove(as, b + i*PAGE_SIZE);
  334.                     page_table_unlock(as, false);
  335.                 }
  336.             }
  337.         }
  338.  
  339.         /*
  340.          * Finish TLB shootdown sequence.
  341.          */
  342.         tlb_invalidate_pages(AS->asid, area->base + pages*PAGE_SIZE, area->pages - pages);
  343.         tlb_shootdown_finalize();
  344.     } else {
  345.         /*
  346.          * Growing the area.
  347.          * Check for overlaps with other address space areas.
  348.          */
  349.         if (!check_area_conflicts(as, address, pages * PAGE_SIZE, area)) {
  350.             mutex_unlock(&area->lock);
  351.             mutex_unlock(&as->lock);       
  352.             interrupts_restore(ipl);
  353.             return EADDRNOTAVAIL;
  354.         }
  355.     }
  356.  
  357.     area->pages = pages;
  358.    
  359.     mutex_unlock(&area->lock);
  360.     mutex_unlock(&as->lock);
  361.     interrupts_restore(ipl);
  362.  
  363.     return 0;
  364. }
  365.  
  366. /** Destroy address space area.
  367.  *
  368.  * @param as Address space.
  369.  * @param address Address withing the area to be deleted.
  370.  *
  371.  * @return Zero on success or a value from @ref errno.h on failure.
  372.  */
  373. int as_area_destroy(as_t *as, __address address)
  374. {
  375.     as_area_t *area;
  376.     __address base;
  377.     ipl_t ipl;
  378.     bool cond;
  379.  
  380.     ipl = interrupts_disable();
  381.     mutex_lock(&as->lock);
  382.  
  383.     area = find_area_and_lock(as, address);
  384.     if (!area) {
  385.         mutex_unlock(&as->lock);
  386.         interrupts_restore(ipl);
  387.         return ENOENT;
  388.     }
  389.  
  390.     base = area->base;
  391.  
  392.     /*
  393.      * Start TLB shootdown sequence.
  394.      */
  395.     tlb_shootdown_start(TLB_INVL_PAGES, AS->asid, area->base, area->pages);
  396.  
  397.     /*
  398.      * Visit only the pages mapped by used_space B+tree.
  399.      * Note that we must be very careful when walking the tree
  400.      * leaf list and removing used space as the leaf list changes
  401.      * unpredictibly after each remove. The solution is to actually
  402.      * not walk the tree at all, but to remove items from the head
  403.      * of the leaf list until there are some keys left.
  404.      */
  405.     for (cond = true; cond;) {
  406.         btree_node_t *node;
  407.        
  408.         ASSERT(!list_empty(&area->used_space.leaf_head));
  409.         node = list_get_instance(area->used_space.leaf_head.next, btree_node_t, leaf_link);
  410.         if ((cond = (bool) node->keys)) {
  411.             __address b = node->key[0];
  412.             count_t i;
  413.             pte_t *pte;
  414.            
  415.             for (i = 0; i < (count_t) node->value[0]; i++) {
  416.                 page_table_lock(as, false);
  417.                 pte = page_mapping_find(as, b + i*PAGE_SIZE);
  418.                 ASSERT(pte && PTE_VALID(pte) && PTE_PRESENT(pte));
  419.                 if (area->backend && area->backend->frame_free) {
  420.                     area->backend->frame_free(area,
  421.                         b + i*PAGE_SIZE, PTE_GET_FRAME(pte));
  422.                 }
  423.                 page_mapping_remove(as, b + i*PAGE_SIZE);
  424.                 page_table_unlock(as, false);
  425.             }
  426.             if (!used_space_remove(area, b, i))
  427.                 panic("Could not remove used space.\n");
  428.         }
  429.     }
  430.  
  431.     /*
  432.      * Finish TLB shootdown sequence.
  433.      */
  434.     tlb_invalidate_pages(AS->asid, area->base, area->pages);
  435.     tlb_shootdown_finalize();
  436.    
  437.     btree_destroy(&area->used_space);
  438.  
  439.     area->attributes |= AS_AREA_ATTR_PARTIAL;
  440.    
  441.     if (area->sh_info)
  442.         sh_info_remove_reference(area->sh_info);
  443.        
  444.     mutex_unlock(&area->lock);
  445.  
  446.     /*
  447.      * Remove the empty area from address space.
  448.      */
  449.     btree_remove(&AS->as_area_btree, base, NULL);
  450.    
  451.     free(area);
  452.    
  453.     mutex_unlock(&AS->lock);
  454.     interrupts_restore(ipl);
  455.     return 0;
  456. }
  457.  
  458. /** Share address space area with another or the same address space.
  459.  *
  460.  * Address space area mapping is shared with a new address space area.
  461.  * If the source address space area has not been shared so far,
  462.  * a new sh_info is created. The new address space area simply gets the
  463.  * sh_info of the source area. The process of duplicating the
  464.  * mapping is done through the backend share function.
  465.  *
  466.  * @param src_as Pointer to source address space.
  467.  * @param src_base Base address of the source address space area.
  468.  * @param acc_size Expected size of the source area.
  469.  * @param dst_as Pointer to destination address space.
  470.  * @param dst_base Target base address.
  471.  * @param dst_flags_mask Destination address space area flags mask.
  472.  *
  473.  * @return Zero on success or ENOENT if there is no such task or
  474.  *     if there is no such address space area,
  475.  *     EPERM if there was a problem in accepting the area or
  476.  *     ENOMEM if there was a problem in allocating destination
  477.  *     address space area. ENOTSUP is returned if an attempt
  478.  *     to share non-anonymous address space area is detected.
  479.  */
  480. int as_area_share(as_t *src_as, __address src_base, size_t acc_size,
  481.           as_t *dst_as, __address dst_base, int dst_flags_mask)
  482. {
  483.     ipl_t ipl;
  484.     int src_flags;
  485.     size_t src_size;
  486.     as_area_t *src_area, *dst_area;
  487.     share_info_t *sh_info;
  488.     mem_backend_t *src_backend;
  489.     mem_backend_data_t src_backend_data;
  490.    
  491.     ipl = interrupts_disable();
  492.     mutex_lock(&src_as->lock);
  493.     src_area = find_area_and_lock(src_as, src_base);
  494.     if (!src_area) {
  495.         /*
  496.          * Could not find the source address space area.
  497.          */
  498.         mutex_unlock(&src_as->lock);
  499.         interrupts_restore(ipl);
  500.         return ENOENT;
  501.     }
  502.    
  503.     if (!src_area->backend || !src_area->backend->share) {
  504.         /*
  505.          * There is now backend or the backend does not
  506.          * know how to share the area.
  507.          */
  508.         mutex_unlock(&src_area->lock);
  509.         mutex_unlock(&src_as->lock);
  510.         interrupts_restore(ipl);
  511.         return ENOTSUP;
  512.     }
  513.    
  514.     src_size = src_area->pages * PAGE_SIZE;
  515.     src_flags = src_area->flags;
  516.     src_backend = src_area->backend;
  517.     src_backend_data = src_area->backend_data;
  518.    
  519.     if (src_size != acc_size) {
  520.         mutex_unlock(&src_area->lock);
  521.         mutex_unlock(&src_as->lock);
  522.         interrupts_restore(ipl);
  523.         return EPERM;
  524.     }
  525.  
  526.     /*
  527.      * Now we are committed to sharing the area.
  528.      * First prepare the area for sharing.
  529.      * Then it will be safe to unlock it.
  530.      */
  531.     sh_info = src_area->sh_info;
  532.     if (!sh_info) {
  533.         sh_info = (share_info_t *) malloc(sizeof(share_info_t), 0);
  534.         mutex_initialize(&sh_info->lock);
  535.         sh_info->refcount = 2;
  536.         btree_create(&sh_info->pagemap);
  537.         src_area->sh_info = sh_info;
  538.     } else {
  539.         mutex_lock(&sh_info->lock);
  540.         sh_info->refcount++;
  541.         mutex_unlock(&sh_info->lock);
  542.     }
  543.  
  544.     src_area->backend->share(src_area);
  545.  
  546.     mutex_unlock(&src_area->lock);
  547.     mutex_unlock(&src_as->lock);
  548.  
  549.     /*
  550.      * Create copy of the source address space area.
  551.      * The destination area is created with AS_AREA_ATTR_PARTIAL
  552.      * attribute set which prevents race condition with
  553.      * preliminary as_page_fault() calls.
  554.      * The flags of the source area are masked against dst_flags_mask
  555.      * to support sharing in less privileged mode.
  556.      */
  557.     dst_area = as_area_create(dst_as, src_flags & dst_flags_mask, src_size, dst_base,
  558.                   AS_AREA_ATTR_PARTIAL, src_backend, &src_backend_data);
  559.     if (!dst_area) {
  560.         /*
  561.          * Destination address space area could not be created.
  562.          */
  563.         sh_info_remove_reference(sh_info);
  564.        
  565.         interrupts_restore(ipl);
  566.         return ENOMEM;
  567.     }
  568.    
  569.     /*
  570.      * Now the destination address space area has been
  571.      * fully initialized. Clear the AS_AREA_ATTR_PARTIAL
  572.      * attribute and set the sh_info.
  573.      */
  574.     mutex_lock(&dst_area->lock);
  575.     dst_area->attributes &= ~AS_AREA_ATTR_PARTIAL;
  576.     dst_area->sh_info = sh_info;
  577.     mutex_unlock(&dst_area->lock);
  578.    
  579.     interrupts_restore(ipl);
  580.    
  581.     return 0;
  582. }
  583.  
  584. /** Check access mode for address space area.
  585.  *
  586.  * The address space area must be locked prior to this call.
  587.  *
  588.  * @param area Address space area.
  589.  * @param access Access mode.
  590.  *
  591.  * @return False if access violates area's permissions, true otherwise.
  592.  */
  593. bool as_area_check_access(as_area_t *area, pf_access_t access)
  594. {
  595.     int flagmap[] = {
  596.         [PF_ACCESS_READ] = AS_AREA_READ,
  597.         [PF_ACCESS_WRITE] = AS_AREA_WRITE,
  598.         [PF_ACCESS_EXEC] = AS_AREA_EXEC
  599.     };
  600.  
  601.     if (!(area->flags & flagmap[access]))
  602.         return false;
  603.    
  604.     return true;
  605. }
  606.  
  607. /** Handle page fault within the current address space.
  608.  *
  609.  * This is the high-level page fault handler. It decides
  610.  * whether the page fault can be resolved by any backend
  611.  * and if so, it invokes the backend to resolve the page
  612.  * fault.
  613.  *
  614.  * Interrupts are assumed disabled.
  615.  *
  616.  * @param page Faulting page.
  617.  * @param access Access mode that caused the fault (i.e. read/write/exec).
  618.  * @param istate Pointer to interrupted state.
  619.  *
  620.  * @return AS_PF_FAULT on page fault, AS_PF_OK on success or AS_PF_DEFER if the
  621.  *     fault was caused by copy_to_uspace() or copy_from_uspace().
  622.  */
  623. int as_page_fault(__address page, pf_access_t access, istate_t *istate)
  624. {
  625.     pte_t *pte;
  626.     as_area_t *area;
  627.    
  628.     if (!THREAD)
  629.         return AS_PF_FAULT;
  630.        
  631.     ASSERT(AS);
  632.  
  633.     mutex_lock(&AS->lock);
  634.     area = find_area_and_lock(AS, page);   
  635.     if (!area) {
  636.         /*
  637.          * No area contained mapping for 'page'.
  638.          * Signal page fault to low-level handler.
  639.          */
  640.         mutex_unlock(&AS->lock);
  641.         goto page_fault;
  642.     }
  643.  
  644.     if (area->attributes & AS_AREA_ATTR_PARTIAL) {
  645.         /*
  646.          * The address space area is not fully initialized.
  647.          * Avoid possible race by returning error.
  648.          */
  649.         mutex_unlock(&area->lock);
  650.         mutex_unlock(&AS->lock);
  651.         goto page_fault;       
  652.     }
  653.  
  654.     if (!area->backend || !area->backend->page_fault) {
  655.         /*
  656.          * The address space area is not backed by any backend
  657.          * or the backend cannot handle page faults.
  658.          */
  659.         mutex_unlock(&area->lock);
  660.         mutex_unlock(&AS->lock);
  661.         goto page_fault;       
  662.     }
  663.  
  664.     page_table_lock(AS, false);
  665.    
  666.     /*
  667.      * To avoid race condition between two page faults
  668.      * on the same address, we need to make sure
  669.      * the mapping has not been already inserted.
  670.      */
  671.     if ((pte = page_mapping_find(AS, page))) {
  672.         if (PTE_PRESENT(pte)) {
  673.             if (((access == PF_ACCESS_READ) && PTE_READABLE(pte)) ||
  674.                 (access == PF_ACCESS_WRITE && PTE_WRITABLE(pte)) ||
  675.                 (access == PF_ACCESS_EXEC && PTE_EXECUTABLE(pte))) {
  676.                 page_table_unlock(AS, false);
  677.                 mutex_unlock(&area->lock);
  678.                 mutex_unlock(&AS->lock);
  679.                 return AS_PF_OK;
  680.             }
  681.         }
  682.     }
  683.    
  684.     /*
  685.      * Resort to the backend page fault handler.
  686.      */
  687.     if (area->backend->page_fault(area, page, access) != AS_PF_OK) {
  688.         page_table_unlock(AS, false);
  689.         mutex_unlock(&area->lock);
  690.         mutex_unlock(&AS->lock);
  691.         goto page_fault;
  692.     }
  693.    
  694.     page_table_unlock(AS, false);
  695.     mutex_unlock(&area->lock);
  696.     mutex_unlock(&AS->lock);
  697.     return AS_PF_OK;
  698.  
  699. page_fault:
  700.     if (THREAD->in_copy_from_uspace) {
  701.         THREAD->in_copy_from_uspace = false;
  702.         istate_set_retaddr(istate, (__address) &memcpy_from_uspace_failover_address);
  703.     } else if (THREAD->in_copy_to_uspace) {
  704.         THREAD->in_copy_to_uspace = false;
  705.         istate_set_retaddr(istate, (__address) &memcpy_to_uspace_failover_address);
  706.     } else {
  707.         return AS_PF_FAULT;
  708.     }
  709.  
  710.     return AS_PF_DEFER;
  711. }
  712.  
  713. /** Switch address spaces.
  714.  *
  715.  * Note that this function cannot sleep as it is essentially a part of
  716.  * scheduling. Sleeping here would lead to deadlock on wakeup.
  717.  *
  718.  * @param old Old address space or NULL.
  719.  * @param new New address space.
  720.  */
  721. void as_switch(as_t *old, as_t *new)
  722. {
  723.     ipl_t ipl;
  724.     bool needs_asid = false;
  725.    
  726.     ipl = interrupts_disable();
  727.     spinlock_lock(&inactive_as_with_asid_lock);
  728.  
  729.     /*
  730.      * First, take care of the old address space.
  731.      */
  732.     if (old) {
  733.         mutex_lock_active(&old->lock);
  734.         ASSERT(old->cpu_refcount);
  735.         if((--old->cpu_refcount == 0) && (old != AS_KERNEL)) {
  736.             /*
  737.              * The old address space is no longer active on
  738.              * any processor. It can be appended to the
  739.              * list of inactive address spaces with assigned
  740.              * ASID.
  741.              */
  742.              ASSERT(old->asid != ASID_INVALID);
  743.              list_append(&old->inactive_as_with_asid_link, &inactive_as_with_asid_head);
  744.         }
  745.         mutex_unlock(&old->lock);
  746.     }
  747.  
  748.     /*
  749.      * Second, prepare the new address space.
  750.      */
  751.     mutex_lock_active(&new->lock);
  752.     if ((new->cpu_refcount++ == 0) && (new != AS_KERNEL)) {
  753.         if (new->asid != ASID_INVALID)
  754.             list_remove(&new->inactive_as_with_asid_link);
  755.         else
  756.             needs_asid = true;  /* defer call to asid_get() until new->lock is released */
  757.     }
  758.     SET_PTL0_ADDRESS(new->page_table);
  759.     mutex_unlock(&new->lock);
  760.  
  761.     if (needs_asid) {
  762.         /*
  763.          * Allocation of new ASID was deferred
  764.          * until now in order to avoid deadlock.
  765.          */
  766.         asid_t asid;
  767.        
  768.         asid = asid_get();
  769.         mutex_lock_active(&new->lock);
  770.         new->asid = asid;
  771.         mutex_unlock(&new->lock);
  772.     }
  773.     spinlock_unlock(&inactive_as_with_asid_lock);
  774.     interrupts_restore(ipl);
  775.    
  776.     /*
  777.      * Perform architecture-specific steps.
  778.      * (e.g. write ASID to hardware register etc.)
  779.      */
  780.     as_install_arch(new);
  781.    
  782.     AS = new;
  783. }
  784.  
  785. /** Convert address space area flags to page flags.
  786.  *
  787.  * @param aflags Flags of some address space area.
  788.  *
  789.  * @return Flags to be passed to page_mapping_insert().
  790.  */
  791. int area_flags_to_page_flags(int aflags)
  792. {
  793.     int flags;
  794.  
  795.     flags = PAGE_USER | PAGE_PRESENT;
  796.    
  797.     if (aflags & AS_AREA_READ)
  798.         flags |= PAGE_READ;
  799.        
  800.     if (aflags & AS_AREA_WRITE)
  801.         flags |= PAGE_WRITE;
  802.    
  803.     if (aflags & AS_AREA_EXEC)
  804.         flags |= PAGE_EXEC;
  805.    
  806.     if (aflags & AS_AREA_CACHEABLE)
  807.         flags |= PAGE_CACHEABLE;
  808.        
  809.     return flags;
  810. }
  811.  
  812. /** Compute flags for virtual address translation subsytem.
  813.  *
  814.  * The address space area must be locked.
  815.  * Interrupts must be disabled.
  816.  *
  817.  * @param a Address space area.
  818.  *
  819.  * @return Flags to be used in page_mapping_insert().
  820.  */
  821. int as_area_get_flags(as_area_t *a)
  822. {
  823.     return area_flags_to_page_flags(a->flags);
  824. }
  825.  
  826. /** Create page table.
  827.  *
  828.  * Depending on architecture, create either address space
  829.  * private or global page table.
  830.  *
  831.  * @param flags Flags saying whether the page table is for kernel address space.
  832.  *
  833.  * @return First entry of the page table.
  834.  */
  835. pte_t *page_table_create(int flags)
  836. {
  837.         ASSERT(as_operations);
  838.         ASSERT(as_operations->page_table_create);
  839.  
  840.         return as_operations->page_table_create(flags);
  841. }
  842.  
  843. /** Lock page table.
  844.  *
  845.  * This function should be called before any page_mapping_insert(),
  846.  * page_mapping_remove() and page_mapping_find().
  847.  *
  848.  * Locking order is such that address space areas must be locked
  849.  * prior to this call. Address space can be locked prior to this
  850.  * call in which case the lock argument is false.
  851.  *
  852.  * @param as Address space.
  853.  * @param lock If false, do not attempt to lock as->lock.
  854.  */
  855. void page_table_lock(as_t *as, bool lock)
  856. {
  857.     ASSERT(as_operations);
  858.     ASSERT(as_operations->page_table_lock);
  859.  
  860.     as_operations->page_table_lock(as, lock);
  861. }
  862.  
  863. /** Unlock page table.
  864.  *
  865.  * @param as Address space.
  866.  * @param unlock If false, do not attempt to unlock as->lock.
  867.  */
  868. void page_table_unlock(as_t *as, bool unlock)
  869. {
  870.     ASSERT(as_operations);
  871.     ASSERT(as_operations->page_table_unlock);
  872.  
  873.     as_operations->page_table_unlock(as, unlock);
  874. }
  875.  
  876.  
  877. /** Find address space area and lock it.
  878.  *
  879.  * The address space must be locked and interrupts must be disabled.
  880.  *
  881.  * @param as Address space.
  882.  * @param va Virtual address.
  883.  *
  884.  * @return Locked address space area containing va on success or NULL on failure.
  885.  */
  886. as_area_t *find_area_and_lock(as_t *as, __address va)
  887. {
  888.     as_area_t *a;
  889.     btree_node_t *leaf, *lnode;
  890.     int i;
  891.    
  892.     a = (as_area_t *) btree_search(&as->as_area_btree, va, &leaf);
  893.     if (a) {
  894.         /* va is the base address of an address space area */
  895.         mutex_lock(&a->lock);
  896.         return a;
  897.     }
  898.    
  899.     /*
  900.      * Search the leaf node and the righmost record of its left neighbour
  901.      * to find out whether this is a miss or va belongs to an address
  902.      * space area found there.
  903.      */
  904.    
  905.     /* First, search the leaf node itself. */
  906.     for (i = 0; i < leaf->keys; i++) {
  907.         a = (as_area_t *) leaf->value[i];
  908.         mutex_lock(&a->lock);
  909.         if ((a->base <= va) && (va < a->base + a->pages * PAGE_SIZE)) {
  910.             return a;
  911.         }
  912.         mutex_unlock(&a->lock);
  913.     }
  914.  
  915.     /*
  916.      * Second, locate the left neighbour and test its last record.
  917.      * Because of its position in the B+tree, it must have base < va.
  918.      */
  919.     if ((lnode = btree_leaf_node_left_neighbour(&as->as_area_btree, leaf))) {
  920.         a = (as_area_t *) lnode->value[lnode->keys - 1];
  921.         mutex_lock(&a->lock);
  922.         if (va < a->base + a->pages * PAGE_SIZE) {
  923.             return a;
  924.         }
  925.         mutex_unlock(&a->lock);
  926.     }
  927.  
  928.     return NULL;
  929. }
  930.  
  931. /** Check area conflicts with other areas.
  932.  *
  933.  * The address space must be locked and interrupts must be disabled.
  934.  *
  935.  * @param as Address space.
  936.  * @param va Starting virtual address of the area being tested.
  937.  * @param size Size of the area being tested.
  938.  * @param avoid_area Do not touch this area.
  939.  *
  940.  * @return True if there is no conflict, false otherwise.
  941.  */
  942. bool check_area_conflicts(as_t *as, __address va, size_t size, as_area_t *avoid_area)
  943. {
  944.     as_area_t *a;
  945.     btree_node_t *leaf, *node;
  946.     int i;
  947.    
  948.     /*
  949.      * We don't want any area to have conflicts with NULL page.
  950.      */
  951.     if (overlaps(va, size, NULL, PAGE_SIZE))
  952.         return false;
  953.    
  954.     /*
  955.      * The leaf node is found in O(log n), where n is proportional to
  956.      * the number of address space areas belonging to as.
  957.      * The check for conflicts is then attempted on the rightmost
  958.      * record in the left neighbour, the leftmost record in the right
  959.      * neighbour and all records in the leaf node itself.
  960.      */
  961.    
  962.     if ((a = (as_area_t *) btree_search(&as->as_area_btree, va, &leaf))) {
  963.         if (a != avoid_area)
  964.             return false;
  965.     }
  966.    
  967.     /* First, check the two border cases. */
  968.     if ((node = btree_leaf_node_left_neighbour(&as->as_area_btree, leaf))) {
  969.         a = (as_area_t *) node->value[node->keys - 1];
  970.         mutex_lock(&a->lock);
  971.         if (overlaps(va, size, a->base, a->pages * PAGE_SIZE)) {
  972.             mutex_unlock(&a->lock);
  973.             return false;
  974.         }
  975.         mutex_unlock(&a->lock);
  976.     }
  977.     if ((node = btree_leaf_node_right_neighbour(&as->as_area_btree, leaf))) {
  978.         a = (as_area_t *) node->value[0];
  979.         mutex_lock(&a->lock);
  980.         if (overlaps(va, size, a->base, a->pages * PAGE_SIZE)) {
  981.             mutex_unlock(&a->lock);
  982.             return false;
  983.         }
  984.         mutex_unlock(&a->lock);
  985.     }
  986.    
  987.     /* Second, check the leaf node. */
  988.     for (i = 0; i < leaf->keys; i++) {
  989.         a = (as_area_t *) leaf->value[i];
  990.    
  991.         if (a == avoid_area)
  992.             continue;
  993.    
  994.         mutex_lock(&a->lock);
  995.         if (overlaps(va, size, a->base, a->pages * PAGE_SIZE)) {
  996.             mutex_unlock(&a->lock);
  997.             return false;
  998.         }
  999.         mutex_unlock(&a->lock);
  1000.     }
  1001.  
  1002.     /*
  1003.      * So far, the area does not conflict with other areas.
  1004.      * Check if it doesn't conflict with kernel address space.
  1005.      */  
  1006.     if (!KERNEL_ADDRESS_SPACE_SHADOWED) {
  1007.         return !overlaps(va, size,
  1008.             KERNEL_ADDRESS_SPACE_START, KERNEL_ADDRESS_SPACE_END-KERNEL_ADDRESS_SPACE_START);
  1009.     }
  1010.  
  1011.     return true;
  1012. }
  1013.  
  1014. /** Return size of the address space area with given base.  */
  1015. size_t as_get_size(__address base)
  1016. {
  1017.     ipl_t ipl;
  1018.     as_area_t *src_area;
  1019.     size_t size;
  1020.  
  1021.     ipl = interrupts_disable();
  1022.     src_area = find_area_and_lock(AS, base);
  1023.     if (src_area){
  1024.         size = src_area->pages * PAGE_SIZE;
  1025.         mutex_unlock(&src_area->lock);
  1026.     } else {
  1027.         size = 0;
  1028.     }
  1029.     interrupts_restore(ipl);
  1030.     return size;
  1031. }
  1032.  
  1033. /** Mark portion of address space area as used.
  1034.  *
  1035.  * The address space area must be already locked.
  1036.  *
  1037.  * @param a Address space area.
  1038.  * @param page First page to be marked.
  1039.  * @param count Number of page to be marked.
  1040.  *
  1041.  * @return 0 on failure and 1 on success.
  1042.  */
  1043. int used_space_insert(as_area_t *a, __address page, count_t count)
  1044. {
  1045.     btree_node_t *leaf, *node;
  1046.     count_t pages;
  1047.     int i;
  1048.  
  1049.     ASSERT(page == ALIGN_DOWN(page, PAGE_SIZE));
  1050.     ASSERT(count);
  1051.  
  1052.     pages = (count_t) btree_search(&a->used_space, page, &leaf);
  1053.     if (pages) {
  1054.         /*
  1055.          * We hit the beginning of some used space.
  1056.          */
  1057.         return 0;
  1058.     }
  1059.  
  1060.     if (!leaf->keys) {
  1061.         btree_insert(&a->used_space, page, (void *) count, leaf);
  1062.         return 1;
  1063.     }
  1064.  
  1065.     node = btree_leaf_node_left_neighbour(&a->used_space, leaf);
  1066.     if (node) {
  1067.         __address left_pg = node->key[node->keys - 1], right_pg = leaf->key[0];
  1068.         count_t left_cnt = (count_t) node->value[node->keys - 1], right_cnt = (count_t) leaf->value[0];
  1069.        
  1070.         /*
  1071.          * Examine the possibility that the interval fits
  1072.          * somewhere between the rightmost interval of
  1073.          * the left neigbour and the first interval of the leaf.
  1074.          */
  1075.          
  1076.         if (page >= right_pg) {
  1077.             /* Do nothing. */
  1078.         } else if (overlaps(page, count*PAGE_SIZE, left_pg, left_cnt*PAGE_SIZE)) {
  1079.             /* The interval intersects with the left interval. */
  1080.             return 0;
  1081.         } else if (overlaps(page, count*PAGE_SIZE, right_pg, right_cnt*PAGE_SIZE)) {
  1082.             /* The interval intersects with the right interval. */
  1083.             return 0;          
  1084.         } else if ((page == left_pg + left_cnt*PAGE_SIZE) && (page + count*PAGE_SIZE == right_pg)) {
  1085.             /* The interval can be added by merging the two already present intervals. */
  1086.             node->value[node->keys - 1] += count + right_cnt;
  1087.             btree_remove(&a->used_space, right_pg, leaf);
  1088.             return 1;
  1089.         } else if (page == left_pg + left_cnt*PAGE_SIZE) {
  1090.             /* The interval can be added by simply growing the left interval. */
  1091.             node->value[node->keys - 1] += count;
  1092.             return 1;
  1093.         } else if (page + count*PAGE_SIZE == right_pg) {
  1094.             /*
  1095.              * The interval can be addded by simply moving base of the right
  1096.              * interval down and increasing its size accordingly.
  1097.              */
  1098.             leaf->value[0] += count;
  1099.             leaf->key[0] = page;
  1100.             return 1;
  1101.         } else {
  1102.             /*
  1103.              * The interval is between both neigbouring intervals,
  1104.              * but cannot be merged with any of them.
  1105.              */
  1106.             btree_insert(&a->used_space, page, (void *) count, leaf);
  1107.             return 1;
  1108.         }
  1109.     } else if (page < leaf->key[0]) {
  1110.         __address right_pg = leaf->key[0];
  1111.         count_t right_cnt = (count_t) leaf->value[0];
  1112.    
  1113.         /*
  1114.          * Investigate the border case in which the left neighbour does not
  1115.          * exist but the interval fits from the left.
  1116.          */
  1117.          
  1118.         if (overlaps(page, count*PAGE_SIZE, right_pg, right_cnt*PAGE_SIZE)) {
  1119.             /* The interval intersects with the right interval. */
  1120.             return 0;
  1121.         } else if (page + count*PAGE_SIZE == right_pg) {
  1122.             /*
  1123.              * The interval can be added by moving the base of the right interval down
  1124.              * and increasing its size accordingly.
  1125.              */
  1126.             leaf->key[0] = page;
  1127.             leaf->value[0] += count;
  1128.             return 1;
  1129.         } else {
  1130.             /*
  1131.              * The interval doesn't adjoin with the right interval.
  1132.              * It must be added individually.
  1133.              */
  1134.             btree_insert(&a->used_space, page, (void *) count, leaf);
  1135.             return 1;
  1136.         }
  1137.     }
  1138.  
  1139.     node = btree_leaf_node_right_neighbour(&a->used_space, leaf);
  1140.     if (node) {
  1141.         __address left_pg = leaf->key[leaf->keys - 1], right_pg = node->key[0];
  1142.         count_t left_cnt = (count_t) leaf->value[leaf->keys - 1], right_cnt = (count_t) node->value[0];
  1143.        
  1144.         /*
  1145.          * Examine the possibility that the interval fits
  1146.          * somewhere between the leftmost interval of
  1147.          * the right neigbour and the last interval of the leaf.
  1148.          */
  1149.  
  1150.         if (page < left_pg) {
  1151.             /* Do nothing. */
  1152.         } else if (overlaps(page, count*PAGE_SIZE, left_pg, left_cnt*PAGE_SIZE)) {
  1153.             /* The interval intersects with the left interval. */
  1154.             return 0;
  1155.         } else if (overlaps(page, count*PAGE_SIZE, right_pg, right_cnt*PAGE_SIZE)) {
  1156.             /* The interval intersects with the right interval. */
  1157.             return 0;          
  1158.         } else if ((page == left_pg + left_cnt*PAGE_SIZE) && (page + count*PAGE_SIZE == right_pg)) {
  1159.             /* The interval can be added by merging the two already present intervals. */
  1160.             leaf->value[leaf->keys - 1] += count + right_cnt;
  1161.             btree_remove(&a->used_space, right_pg, node);
  1162.             return 1;
  1163.         } else if (page == left_pg + left_cnt*PAGE_SIZE) {
  1164.             /* The interval can be added by simply growing the left interval. */
  1165.             leaf->value[leaf->keys - 1] +=  count;
  1166.             return 1;
  1167.         } else if (page + count*PAGE_SIZE == right_pg) {
  1168.             /*
  1169.              * The interval can be addded by simply moving base of the right
  1170.              * interval down and increasing its size accordingly.
  1171.              */
  1172.             node->value[0] += count;
  1173.             node->key[0] = page;
  1174.             return 1;
  1175.         } else {
  1176.             /*
  1177.              * The interval is between both neigbouring intervals,
  1178.              * but cannot be merged with any of them.
  1179.              */
  1180.             btree_insert(&a->used_space, page, (void *) count, leaf);
  1181.             return 1;
  1182.         }
  1183.     } else if (page >= leaf->key[leaf->keys - 1]) {
  1184.         __address left_pg = leaf->key[leaf->keys - 1];
  1185.         count_t left_cnt = (count_t) leaf->value[leaf->keys - 1];
  1186.    
  1187.         /*
  1188.          * Investigate the border case in which the right neighbour does not
  1189.          * exist but the interval fits from the right.
  1190.          */
  1191.          
  1192.         if (overlaps(page, count*PAGE_SIZE, left_pg, left_cnt*PAGE_SIZE)) {
  1193.             /* The interval intersects with the left interval. */
  1194.             return 0;
  1195.         } else if (left_pg + left_cnt*PAGE_SIZE == page) {
  1196.             /* The interval can be added by growing the left interval. */
  1197.             leaf->value[leaf->keys - 1] += count;
  1198.             return 1;
  1199.         } else {
  1200.             /*
  1201.              * The interval doesn't adjoin with the left interval.
  1202.              * It must be added individually.
  1203.              */
  1204.             btree_insert(&a->used_space, page, (void *) count, leaf);
  1205.             return 1;
  1206.         }
  1207.     }
  1208.    
  1209.     /*
  1210.      * Note that if the algorithm made it thus far, the interval can fit only
  1211.      * between two other intervals of the leaf. The two border cases were already
  1212.      * resolved.
  1213.      */
  1214.     for (i = 1; i < leaf->keys; i++) {
  1215.         if (page < leaf->key[i]) {
  1216.             __address left_pg = leaf->key[i - 1], right_pg = leaf->key[i];
  1217.             count_t left_cnt = (count_t) leaf->value[i - 1], right_cnt = (count_t) leaf->value[i];
  1218.  
  1219.             /*
  1220.              * The interval fits between left_pg and right_pg.
  1221.              */
  1222.  
  1223.             if (overlaps(page, count*PAGE_SIZE, left_pg, left_cnt*PAGE_SIZE)) {
  1224.                 /* The interval intersects with the left interval. */
  1225.                 return 0;
  1226.             } else if (overlaps(page, count*PAGE_SIZE, right_pg, right_cnt*PAGE_SIZE)) {
  1227.                 /* The interval intersects with the right interval. */
  1228.                 return 0;          
  1229.             } else if ((page == left_pg + left_cnt*PAGE_SIZE) && (page + count*PAGE_SIZE == right_pg)) {
  1230.                 /* The interval can be added by merging the two already present intervals. */
  1231.                 leaf->value[i - 1] += count + right_cnt;
  1232.                 btree_remove(&a->used_space, right_pg, leaf);
  1233.                 return 1;
  1234.             } else if (page == left_pg + left_cnt*PAGE_SIZE) {
  1235.                 /* The interval can be added by simply growing the left interval. */
  1236.                 leaf->value[i - 1] += count;
  1237.                 return 1;
  1238.             } else if (page + count*PAGE_SIZE == right_pg) {
  1239.                 /*
  1240.                      * The interval can be addded by simply moving base of the right
  1241.                  * interval down and increasing its size accordingly.
  1242.                  */
  1243.                 leaf->value[i] += count;
  1244.                 leaf->key[i] = page;
  1245.                 return 1;
  1246.             } else {
  1247.                 /*
  1248.                  * The interval is between both neigbouring intervals,
  1249.                  * but cannot be merged with any of them.
  1250.                  */
  1251.                 btree_insert(&a->used_space, page, (void *) count, leaf);
  1252.                 return 1;
  1253.             }
  1254.         }
  1255.     }
  1256.  
  1257.     panic("Inconsistency detected while adding %d pages of used space at %P.\n", count, page);
  1258. }
  1259.  
  1260. /** Mark portion of address space area as unused.
  1261.  *
  1262.  * The address space area must be already locked.
  1263.  *
  1264.  * @param a Address space area.
  1265.  * @param page First page to be marked.
  1266.  * @param count Number of page to be marked.
  1267.  *
  1268.  * @return 0 on failure and 1 on success.
  1269.  */
  1270. int used_space_remove(as_area_t *a, __address page, count_t count)
  1271. {
  1272.     btree_node_t *leaf, *node;
  1273.     count_t pages;
  1274.     int i;
  1275.  
  1276.     ASSERT(page == ALIGN_DOWN(page, PAGE_SIZE));
  1277.     ASSERT(count);
  1278.  
  1279.     pages = (count_t) btree_search(&a->used_space, page, &leaf);
  1280.     if (pages) {
  1281.         /*
  1282.          * We are lucky, page is the beginning of some interval.
  1283.          */
  1284.         if (count > pages) {
  1285.             return 0;
  1286.         } else if (count == pages) {
  1287.             btree_remove(&a->used_space, page, leaf);
  1288.             return 1;
  1289.         } else {
  1290.             /*
  1291.              * Find the respective interval.
  1292.              * Decrease its size and relocate its start address.
  1293.              */
  1294.             for (i = 0; i < leaf->keys; i++) {
  1295.                 if (leaf->key[i] == page) {
  1296.                     leaf->key[i] += count*PAGE_SIZE;
  1297.                     leaf->value[i] -= count;
  1298.                     return 1;
  1299.                 }
  1300.             }
  1301.             goto error;
  1302.         }
  1303.     }
  1304.  
  1305.     node = btree_leaf_node_left_neighbour(&a->used_space, leaf);
  1306.     if (node && page < leaf->key[0]) {
  1307.         __address left_pg = node->key[node->keys - 1];
  1308.         count_t left_cnt = (count_t) node->value[node->keys - 1];
  1309.  
  1310.         if (overlaps(left_pg, left_cnt*PAGE_SIZE, page, count*PAGE_SIZE)) {
  1311.             if (page + count*PAGE_SIZE == left_pg + left_cnt*PAGE_SIZE) {
  1312.                 /*
  1313.                  * The interval is contained in the rightmost interval
  1314.                  * of the left neighbour and can be removed by
  1315.                  * updating the size of the bigger interval.
  1316.                  */
  1317.                 node->value[node->keys - 1] -= count;
  1318.                 return 1;
  1319.             } else if (page + count*PAGE_SIZE < left_pg + left_cnt*PAGE_SIZE) {
  1320.                 count_t new_cnt;
  1321.                
  1322.                 /*
  1323.                  * The interval is contained in the rightmost interval
  1324.                  * of the left neighbour but its removal requires
  1325.                  * both updating the size of the original interval and
  1326.                  * also inserting a new interval.
  1327.                  */
  1328.                 new_cnt = ((left_pg + left_cnt*PAGE_SIZE) - (page + count*PAGE_SIZE)) >> PAGE_WIDTH;
  1329.                 node->value[node->keys - 1] -= count + new_cnt;
  1330.                 btree_insert(&a->used_space, page + count*PAGE_SIZE, (void *) new_cnt, leaf);
  1331.                 return 1;
  1332.             }
  1333.         }
  1334.         return 0;
  1335.     } else if (page < leaf->key[0]) {
  1336.         return 0;
  1337.     }
  1338.    
  1339.     if (page > leaf->key[leaf->keys - 1]) {
  1340.         __address left_pg = leaf->key[leaf->keys - 1];
  1341.         count_t left_cnt = (count_t) leaf->value[leaf->keys - 1];
  1342.  
  1343.         if (overlaps(left_pg, left_cnt*PAGE_SIZE, page, count*PAGE_SIZE)) {
  1344.             if (page + count*PAGE_SIZE == left_pg + left_cnt*PAGE_SIZE) {
  1345.                 /*
  1346.                  * The interval is contained in the rightmost interval
  1347.                  * of the leaf and can be removed by updating the size
  1348.                  * of the bigger interval.
  1349.                  */
  1350.                 leaf->value[leaf->keys - 1] -= count;
  1351.                 return 1;
  1352.             } else if (page + count*PAGE_SIZE < left_pg + left_cnt*PAGE_SIZE) {
  1353.                 count_t new_cnt;
  1354.                
  1355.                 /*
  1356.                  * The interval is contained in the rightmost interval
  1357.                  * of the leaf but its removal requires both updating
  1358.                  * the size of the original interval and
  1359.                  * also inserting a new interval.
  1360.                  */
  1361.                 new_cnt = ((left_pg + left_cnt*PAGE_SIZE) - (page + count*PAGE_SIZE)) >> PAGE_WIDTH;
  1362.                 leaf->value[leaf->keys - 1] -= count + new_cnt;
  1363.                 btree_insert(&a->used_space, page + count*PAGE_SIZE, (void *) new_cnt, leaf);
  1364.                 return 1;
  1365.             }
  1366.         }
  1367.         return 0;
  1368.     }  
  1369.    
  1370.     /*
  1371.      * The border cases have been already resolved.
  1372.      * Now the interval can be only between intervals of the leaf.
  1373.      */
  1374.     for (i = 1; i < leaf->keys - 1; i++) {
  1375.         if (page < leaf->key[i]) {
  1376.             __address left_pg = leaf->key[i - 1];
  1377.             count_t left_cnt = (count_t) leaf->value[i - 1];
  1378.  
  1379.             /*
  1380.              * Now the interval is between intervals corresponding to (i - 1) and i.
  1381.              */
  1382.             if (overlaps(left_pg, left_cnt*PAGE_SIZE, page, count*PAGE_SIZE)) {
  1383.                 if (page + count*PAGE_SIZE == left_pg + left_cnt*PAGE_SIZE) {
  1384.                     /*
  1385.                     * The interval is contained in the interval (i - 1)
  1386.                      * of the leaf and can be removed by updating the size
  1387.                      * of the bigger interval.
  1388.                      */
  1389.                     leaf->value[i - 1] -= count;
  1390.                     return 1;
  1391.                 } else if (page + count*PAGE_SIZE < left_pg + left_cnt*PAGE_SIZE) {
  1392.                     count_t new_cnt;
  1393.                
  1394.                     /*
  1395.                      * The interval is contained in the interval (i - 1)
  1396.                      * of the leaf but its removal requires both updating
  1397.                      * the size of the original interval and
  1398.                      * also inserting a new interval.
  1399.                      */
  1400.                     new_cnt = ((left_pg + left_cnt*PAGE_SIZE) - (page + count*PAGE_SIZE)) >> PAGE_WIDTH;
  1401.                     leaf->value[i - 1] -= count + new_cnt;
  1402.                     btree_insert(&a->used_space, page + count*PAGE_SIZE, (void *) new_cnt, leaf);
  1403.                     return 1;
  1404.                 }
  1405.             }
  1406.             return 0;
  1407.         }
  1408.     }
  1409.  
  1410. error:
  1411.     panic("Inconsistency detected while removing %d pages of used space from %P.\n", count, page);
  1412. }
  1413.  
  1414. /** Remove reference to address space area share info.
  1415.  *
  1416.  * If the reference count drops to 0, the sh_info is deallocated.
  1417.  *
  1418.  * @param sh_info Pointer to address space area share info.
  1419.  */
  1420. void sh_info_remove_reference(share_info_t *sh_info)
  1421. {
  1422.     bool dealloc = false;
  1423.  
  1424.     mutex_lock(&sh_info->lock);
  1425.     ASSERT(sh_info->refcount);
  1426.     if (--sh_info->refcount == 0) {
  1427.         dealloc = true;
  1428.         bool cond;
  1429.        
  1430.         /*
  1431.          * Now walk carefully the pagemap B+tree and free/remove
  1432.          * reference from all frames found there.
  1433.          */
  1434.         for (cond = true; cond;) {
  1435.             btree_node_t *node;
  1436.            
  1437.             ASSERT(!list_empty(&sh_info->pagemap.leaf_head));
  1438.             node = list_get_instance(sh_info->pagemap.leaf_head.next, btree_node_t, leaf_link);
  1439.             if ((cond = node->keys)) {
  1440.                 frame_free(ADDR2PFN((__address) node->value[0]));
  1441.                 btree_remove(&sh_info->pagemap, node->key[0], node);
  1442.             }
  1443.         }
  1444.        
  1445.     }
  1446.     mutex_unlock(&sh_info->lock);
  1447.    
  1448.     if (dealloc) {
  1449.         btree_destroy(&sh_info->pagemap);
  1450.         free(sh_info);
  1451.     }
  1452. }
  1453.  
  1454. /*
  1455.  * Address space related syscalls.
  1456.  */
  1457.  
  1458. /** Wrapper for as_area_create(). */
  1459. __native sys_as_area_create(__address address, size_t size, int flags)
  1460. {
  1461.     if (as_area_create(AS, flags | AS_AREA_CACHEABLE, size, address, AS_AREA_ATTR_NONE, &anon_backend, NULL))
  1462.         return (__native) address;
  1463.     else
  1464.         return (__native) -1;
  1465. }
  1466.  
  1467. /** Wrapper for as_area_resize. */
  1468. __native sys_as_area_resize(__address address, size_t size, int flags)
  1469. {
  1470.     return (__native) as_area_resize(AS, address, size, 0);
  1471. }
  1472.  
  1473. /** Wrapper for as_area_destroy. */
  1474. __native sys_as_area_destroy(__address address)
  1475. {
  1476.     return (__native) as_area_destroy(AS, address);
  1477. }
  1478.