+static void free_shm(void)
+{
+ struct shmid_ds sbuf;
+
+ if (threads) {
+ void *tp = threads;
+
+ threads = NULL;
+ file_hash_exit();
+ flow_exit();
+ fio_debug_jobp = NULL;
+ shmdt(tp);
+ shmctl(shm_id, IPC_RMID, &sbuf);
+ }
+
+ scleanup();
+}
+
+/*
+ * The thread area is shared between the main process and the job
+ * threads/processes. So setup a shared memory segment that will hold
+ * all the job info. We use the end of the region for keeping track of
+ * open files across jobs, for file sharing.
+ */
+static int setup_thread_area(void)
+{
+ void *hash;
+
+ if (threads)
+ return 0;
+
+ /*
+ * 1024 is too much on some machines, scale max_jobs if
+ * we get a failure that looks like too large a shm segment
+ */
+ do {
+ size_t size = max_jobs * sizeof(struct thread_data);
+
+ size += file_hash_size;
+ size += sizeof(unsigned int);
+
+ shm_id = shmget(0, size, IPC_CREAT | 0600);
+ if (shm_id != -1)
+ break;
+ if (errno != EINVAL && errno != ENOMEM && errno != ENOSPC) {
+ perror("shmget");
+ break;
+ }
+
+ max_jobs >>= 1;
+ } while (max_jobs);
+
+ if (shm_id == -1)
+ return 1;
+
+ threads = shmat(shm_id, NULL, 0);
+ if (threads == (void *) -1) {
+ perror("shmat");
+ return 1;
+ }
+
+ memset(threads, 0, max_jobs * sizeof(struct thread_data));
+ hash = (void *) threads + max_jobs * sizeof(struct thread_data);
+ fio_debug_jobp = (void *) hash + file_hash_size;
+ *fio_debug_jobp = -1;
+ file_hash_init(hash);
+
+ flow_init();
+
+ return 0;
+}
+