1 /* 2 * Capability allocation and management. 3 * 4 * Copyright (C) 2019, 2021, 2022 Paul Boddie <paul@boddie.org.uk> 5 * 6 * This program is free software; you can redistribute it and/or 7 * modify it under the terms of the GNU General Public License as 8 * published by the Free Software Foundation; either version 2 of 9 * the License, or (at your option) any later version. 10 * 11 * This program is distributed in the hope that it will be useful, 12 * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 * GNU General Public License for more details. 15 * 16 * You should have received a copy of the GNU General Public License 17 * along with this program; if not, write to the Free Software 18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, 19 * Boston, MA 02110-1301, USA 20 */ 21 22 #include <l4/re/c/util/cap_alloc.h> 23 #include <l4/sys/err.h> 24 25 #include "cap_alloc.h" 26 #include "semaphore.h" 27 28 29 30 /* Semaphore used if threading has been initialised by ipc_cap_alloc_init. */ 31 32 l4_cap_idx_t ipc_cap_alloc_semaphore = L4_INVALID_CAP; 33 34 35 36 /* Reserve and return a capability index. */ 37 38 l4_cap_idx_t ipc_cap_alloc() 39 { 40 l4_cap_idx_t cap; 41 long err; 42 43 /* Allocate a capability in the critical section, then return. */ 44 45 err = ipc_semaphore_down(ipc_cap_alloc_semaphore); 46 if (err) 47 return L4_INVALID_CAP; 48 49 cap = l4re_util_cap_alloc(); 50 51 ipc_semaphore_up(ipc_cap_alloc_semaphore); 52 53 return cap; 54 } 55 56 /* Reserve and return many capability indexes. */ 57 58 long ipc_cap_alloc_many(l4_cap_idx_t caps[], int count) 59 { 60 int i; 61 long err; 62 63 /* Allocate a capability in the critical section, then return. */ 64 65 err = ipc_semaphore_down(ipc_cap_alloc_semaphore); 66 if (err) 67 return err; 68 69 for (i = 0; i < count; i++) 70 { 71 caps[i] = l4re_util_cap_alloc(); 72 73 if (l4_is_invalid_cap(caps[i])) 74 { 75 err = -L4_ENOMEM; 76 break; 77 } 78 } 79 80 /* Free allocated capabilities if not all could be allocated. */ 81 82 if (err) 83 for (; i >= 0; i--) 84 l4re_util_cap_free(caps[i]); 85 86 ipc_semaphore_up(ipc_cap_alloc_semaphore); 87 88 return err; 89 } 90 91 /* Release a capability. */ 92 93 int ipc_cap_free(l4_cap_idx_t cap) 94 { 95 long err; 96 97 err = ipc_semaphore_down(ipc_cap_alloc_semaphore); 98 if (err) 99 return 0; 100 101 l4re_util_cap_free(cap); 102 103 ipc_semaphore_up(ipc_cap_alloc_semaphore); 104 105 return 1; 106 } 107 108 /* Free the indicated capability and unmap it. */ 109 110 int ipc_cap_free_um(l4_cap_idx_t cap) 111 { 112 long err; 113 114 err = ipc_semaphore_down(ipc_cap_alloc_semaphore); 115 if (err) 116 return 0; 117 118 l4re_util_cap_free_um(cap); 119 120 ipc_semaphore_up(ipc_cap_alloc_semaphore); 121 122 return 1; 123 } 124 125 // vim: tabstop=2 expandtab shiftwidth=2