/* * Copyright 2010 Stefan Lankes, Chair for Operating Systems, * RWTH Aachen University * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is part of MetalSVM. */ #ifndef __MAILBOX_H__ #define __MAILBOX_H__ #include #include #include #include #ifdef __cplusplus extern "C" { #endif #define MAILBOX(name, type) \ inline static int mailbox_##name##_init(mailbox_##name##_t* m) { \ if (BUILTIN_EXPECT(!m, 0)) \ return -1; \ \ memset(m->buffer, 0x00, sizeof(type)*MAILBOX_SIZE); \ m->wpos = m->rpos = 0; \ sem_init(&m->mails, 0); \ sem_init(&m->boxes, MAILBOX_SIZE); \ spinlock_init(&m->rlock); \ spinlock_init(&m->wlock); \ \ return 0; \ }\ \ inline static int mailbox_##name##_destroy(mailbox_##name##_t* m) { \ if (BUILTIN_EXPECT(!m, 0)) \ return -1; \ \ sem_destroy(&m->mails); \ sem_destroy(&m->boxes); \ spinlock_destroy(&m->rlock); \ spinlock_destroy(&m->wlock); \ \ return 0; \ } \ \ inline static int mailbox_##name##_post(mailbox_##name##_t* m, type mail) { \ if (BUILTIN_EXPECT(!m, 0)) \ return -1; \ \ sem_wait(&m->boxes); \ spinlock_lock(&m->wlock); \ m->buffer[m->wpos] = mail; \ m->wpos = (m->wpos+1) % MAILBOX_SIZE; \ spinlock_unlock(&m->wlock); \ sem_post(&m->mails); \ \ return 0; \ } \ \ inline static int mailbox_##name##_fetch(mailbox_##name##_t* m, type* mail) { \ if (BUILTIN_EXPECT(!m || !mail, 0)) \ return -1; \ \ sem_wait(&m->mails); \ spinlock_lock(&m->rlock); \ *mail = m->buffer[m->rpos]; \ m->rpos = (m->rpos+1) % MAILBOX_SIZE; \ spinlock_unlock(&m->rlock); \ sem_post(&m->boxes); \ \ return 0; \ } \ \ inline static int mailbox_##name##_tryfetch(mailbox_##name##_t* m, type* mail) { \ if (BUILTIN_EXPECT(!m || !mail, 0)) \ return -1; \ \ if (sem_trywait(&m->mails) != 0) \ return -1; \ spinlock_lock(&m->rlock); \ *mail = m->buffer[m->rpos]; \ m->rpos = (m->rpos+1) % MAILBOX_SIZE; \ spinlock_unlock(&m->rlock); \ sem_post(&m->boxes); \ \ return 0; \ }\ MAILBOX(wait_msg, wait_msg_t) MAILBOX(int32, int32_t) MAILBOX(int16, int16_t) MAILBOX(int8, int8_t) MAILBOX(uint32, uint32_t) MAILBOX(uint16, uint16_t) MAILBOX(uint8, uint8_t) MAILBOX(ptr, void*) #ifdef __cplusplus } #endif #endif