2 * Copyright (C) 2006-2007 Andre Noll <maan@systemlinux.org>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file ipc.c interprocess communication and shared memory helpers */
16 /** abort if semget() failed that many times */
17 #define MAX_SEMOP_RETRIES 500
22 * \return the identifier for the new mutex on success, \a -E_SEM_GET
29 int ret = semget(IPC_PRIVATE, 1, IPC_CREAT | 0666);
30 return ret < 0? -E_SEM_GET : ret;
36 * \param id the identifier of the mutex to be destroyed
38 * \return Positive on success, \a -E_SEM_REMOVE on errors.
42 int mutex_destroy(int id)
44 int ret = semctl(id, 0, IPC_RMID);
45 return ret < 0? -E_SEM_REMOVE : 1;
48 static void para_semop(int id, struct sembuf *sops, unsigned num)
52 for (i = 0; i < MAX_SEMOP_RETRIES; i++)
53 if (semop(id, sops, num) >= 0)
55 PARA_EMERG_LOG("semop failed %d times, aborting\n", MAX_SEMOP_RETRIES);
60 * lock the given mutex
62 * \param id of the shared memory area to lock
64 * This function either succeeds or aborts.
66 * \sa semop(2), struct misc_meta_data
68 void mutex_lock(int id)
70 struct sembuf sops[2] = {
82 para_semop(id, sops, 2);
88 * \param id the identifier of the mutex
90 * This function either succeeds or aborts.
92 * \sa semop(2), struct misc_meta_data
94 void mutex_unlock(int id)
96 struct sembuf sops[1] = {
103 para_semop(id, sops, 1);
107 * create a new shared memory area of given size
109 * \param size the size of the shared memory area to create
111 * \return The id of the shared memory areay on success, \a -E_SHM_GET on errors.
115 int shm_new(size_t size)
117 int ret = shmget(IPC_PRIVATE, size, IPC_CREAT | IPC_EXCL | 0600);
118 return ret < 0 ? -E_SHM_GET : ret;
122 * destroy the given shared memory area
124 * \param id the shared memory id
126 * \return The return value of the underlying shmctl() call on success,
127 * \a -E_SHM_DESTROY on errors.
131 int shm_destroy(int id)
133 struct shmid_ds shm_desc;
134 int ret = shmctl(id, IPC_RMID, &shm_desc);
135 return ret < 0? -E_SHM_DESTROY : ret;
139 * attach a shared memory segment
141 * \param id the identifier of the shared memory segment to attach
142 * \param mode either ATTACH_RO (read only) or ATTACH_RW (read/write)
143 * \param result points to the attached area just attached
145 * \return positive on success, \a -E_SHM_ATTACH on errors.
149 int shm_attach(int id, enum shm_attach_mode mode, void **result)
151 if (mode == ATTACH_RW) {
152 *result = shmat(id, NULL, 0);
153 return *result? 1 : -E_SHM_ATTACH;
155 *result = shmat(id, NULL, SHM_RDONLY);
156 return *result? 1 : -E_SHM_ATTACH;
160 * detach a shared memory segment
162 * \param addr the address of the attached segment
164 * \return positive on success, \a -E_SHM_DETACH on errors.
168 int shm_detach(void *addr)
170 int ret = shmdt(addr);
171 return ret < 0? -E_SHM_DETACH : 1;