1// Copyright 2016 The Fuchsia Authors
2// Copyright (c) 2008-2014 Travis Geiselbrecht
3//
4// Use of this source code is governed by a MIT-style
5// license that can be found in the LICENSE file or at
6// https://opensource.org/licenses/MIT
7
8#include <rand.h>
9
10#include <kernel/atomic.h>
11#include <sys/types.h>
12
13static uint64_t randseed;
14
15void srand(unsigned int seed) {
16    atomic_store_u64_relaxed(&randseed, seed - 1);
17}
18
19int rand(void) {
20    for (;;) {
21        uint64_t old_seed = atomic_load_u64_relaxed(&randseed);
22        uint64_t new_seed = 6364136223846793005ULL * old_seed + 1;
23        if (atomic_cmpxchg_u64_relaxed(&randseed, &old_seed, new_seed)) {
24            return new_seed >> 33;
25        }
26    }
27}
28