| /* |
| * Copyright © 2022 Google, LLC |
| * |
| * Permission is hereby granted, free of charge, to any person obtaining a |
| * copy of this software and associated documentation files (the "Software"), |
| * to deal in the Software without restriction, including without limitation |
| * the rights to use, copy, modify, merge, publish, distribute, sublicense, |
| * and/or sell copies of the Software, and to permit persons to whom the |
| * Software is furnished to do so, subject to the following conditions: |
| * |
| * The above copyright notice and this permission notice (including the next |
| * paragraph) shall be included in all copies or substantial portions of the |
| * Software. |
| * |
| * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL |
| * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING |
| * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS |
| * IN THE SOFTWARE. |
| */ |
| |
| #include "u_magma.h" |
| |
| #include "u_magma_map.h" |
| |
| #include <assert.h> |
| #include <pthread.h> |
| |
| #if defined(__linux__) |
| #include <fcntl.h> |
| #include <sys/stat.h> |
| #include <sys/types.h> |
| #endif |
| |
| #if defined(__Fuchsia__) |
| #include "os/fuchsia.h" |
| #endif |
| |
| static struct u_magma_map s_device_map; |
| static pthread_once_t s_once; |
| |
| static void s_map_release(void) |
| { |
| u_magma_map_release(&s_device_map); |
| } |
| |
| static void s_map_init(void) |
| { |
| u_magma_map_init(&s_device_map); |
| atexit(s_map_release); |
| } |
| |
| int u_magma_open(const char* path) |
| { |
| pthread_once(&s_once, s_map_init); |
| |
| magma_device_t device; |
| #if defined(__Fuchsia__) |
| { |
| zx_handle_t client_handle; |
| if (!fuchsia_open(path, &client_handle)) { |
| return -1; |
| } |
| |
| if (magma_device_import(client_handle, &device) != MAGMA_STATUS_OK) { |
| return -1; |
| } |
| } |
| #else |
| { |
| int fd = open(path, O_RDWR | O_CLOEXEC); |
| if (fd < 0) |
| return -1; |
| |
| if (magma_device_import(fd, &device) != MAGMA_STATUS_OK) { |
| return -1; |
| } |
| } |
| #endif |
| |
| return u_magma_map_get(&s_device_map, device); |
| } |
| |
| void u_magma_close(int fd) { |
| assert(fd >= 0); |
| |
| uint64_t object; |
| if (!u_magma_map_query(&s_device_map, fd, &object)) |
| return; |
| |
| magma_device_release((magma_device_t)object); |
| |
| u_magma_map_put(&s_device_map, fd); |
| } |
| |
| magma_device_t u_magma_device_from_fd(int fd) { |
| assert(fd >= 0); |
| |
| uint64_t object; |
| if (!u_magma_map_query(&s_device_map, fd, &object)) |
| return 0; |
| |
| return (magma_device_t) object; |
| } |