xref: /netbsd-src/sys/external/bsd/drm2/dist/drm/lib/drm_random.c (revision 41ec02673d281bbb3d38e6c78504ce6e30c228c1)
1*41ec0267Sriastradh /*	$NetBSD: drm_random.c,v 1.2 2021/12/18 23:45:31 riastradh Exp $	*/
24e390cabSriastradh 
34e390cabSriastradh // SPDX-License-Identifier: GPL-2.0
44e390cabSriastradh #include <sys/cdefs.h>
5*41ec0267Sriastradh __KERNEL_RCSID(0, "$NetBSD: drm_random.c,v 1.2 2021/12/18 23:45:31 riastradh Exp $");
64e390cabSriastradh 
74e390cabSriastradh #include <linux/bitops.h>
84e390cabSriastradh #include <linux/kernel.h>
94e390cabSriastradh #include <linux/random.h>
104e390cabSriastradh #include <linux/slab.h>
114e390cabSriastradh #include <linux/types.h>
124e390cabSriastradh 
134e390cabSriastradh #include "drm_random.h"
144e390cabSriastradh 
drm_prandom_u32_max_state(u32 ep_ro,struct rnd_state * state)154e390cabSriastradh static inline u32 drm_prandom_u32_max_state(u32 ep_ro, struct rnd_state *state)
164e390cabSriastradh {
174e390cabSriastradh 	return upper_32_bits((u64)prandom_u32_state(state) * ep_ro);
184e390cabSriastradh }
194e390cabSriastradh 
drm_random_reorder(unsigned int * order,unsigned int count,struct rnd_state * state)204e390cabSriastradh void drm_random_reorder(unsigned int *order, unsigned int count,
214e390cabSriastradh 			struct rnd_state *state)
224e390cabSriastradh {
234e390cabSriastradh 	unsigned int i, j;
244e390cabSriastradh 
254e390cabSriastradh 	for (i = 0; i < count; ++i) {
264e390cabSriastradh 		BUILD_BUG_ON(sizeof(unsigned int) > sizeof(u32));
274e390cabSriastradh 		j = drm_prandom_u32_max_state(count, state);
284e390cabSriastradh 		swap(order[i], order[j]);
294e390cabSriastradh 	}
304e390cabSriastradh }
314e390cabSriastradh EXPORT_SYMBOL(drm_random_reorder);
324e390cabSriastradh 
drm_random_order(unsigned int count,struct rnd_state * state)334e390cabSriastradh unsigned int *drm_random_order(unsigned int count, struct rnd_state *state)
344e390cabSriastradh {
354e390cabSriastradh 	unsigned int *order, i;
364e390cabSriastradh 
374e390cabSriastradh 	order = kmalloc_array(count, sizeof(*order), GFP_KERNEL);
384e390cabSriastradh 	if (!order)
394e390cabSriastradh 		return order;
404e390cabSriastradh 
414e390cabSriastradh 	for (i = 0; i < count; i++)
424e390cabSriastradh 		order[i] = i;
434e390cabSriastradh 
444e390cabSriastradh 	drm_random_reorder(order, count, state);
454e390cabSriastradh 	return order;
464e390cabSriastradh }
474e390cabSriastradh EXPORT_SYMBOL(drm_random_order);
48