1#!/bin/bash
2# SPDX-License-Identifier: GPL-2.0+
3#
4# Create an initrd directory if one does not already exist.
5#
6# Copyright (C) IBM Corporation, 2013
7#
8# Author: Connor Shu <Connor.Shu@ibm.com>
9
10D=tools/testing/selftests/rcutorture
11
12# Prerequisite checks
13[ -z "$D" ] && echo >&2 "No argument supplied" && exit 1
14if [ ! -d "$D" ]; then
15    echo >&2 "$D does not exist: Malformed kernel source tree?"
16    exit 1
17fi
18if [ -s "$D/initrd/init" ]; then
19    echo "$D/initrd/init already exists, no need to create it"
20    exit 0
21fi
22
23# Create a C-language initrd/init infinite-loop program and statically
24# link it.  This results in a very small initrd.
25echo "Creating a statically linked C-language initrd"
26cd $D
27mkdir -p initrd
28cd initrd
29cat > init.c << '___EOF___'
30#ifndef NOLIBC
31#include <unistd.h>
32#include <sys/time.h>
33#endif
34
35volatile unsigned long delaycount;
36
37int main(int argc, int argv[])
38{
39	int i;
40	struct timeval tv;
41	struct timeval tvb;
42
43	for (;;) {
44		sleep(1);
45		/* Need some userspace time. */
46		if (gettimeofday(&tvb, NULL))
47			continue;
48		do {
49			for (i = 0; i < 1000 * 100; i++)
50				delaycount = i * i;
51			if (gettimeofday(&tv, NULL))
52				break;
53			tv.tv_sec -= tvb.tv_sec;
54			if (tv.tv_sec > 1)
55				break;
56			tv.tv_usec += tv.tv_sec * 1000 * 1000;
57			tv.tv_usec -= tvb.tv_usec;
58		} while (tv.tv_usec < 1000);
59	}
60	return 0;
61}
62___EOF___
63
64# build using nolibc on supported archs (smaller executable) and fall
65# back to regular glibc on other ones.
66if echo -e "#if __x86_64__||__i386__||__i486__||__i586__||__i686__" \
67           "||__ARM_EABI__||__aarch64__||__s390x__\nyes\n#endif" \
68   | ${CROSS_COMPILE}gcc -E -nostdlib -xc - \
69   | grep -q '^yes'; then
70	# architecture supported by nolibc
71        ${CROSS_COMPILE}gcc -fno-asynchronous-unwind-tables -fno-ident \
72		-nostdlib -include ../../../../include/nolibc/nolibc.h \
73		-s -static -Os -o init init.c -lgcc
74else
75	${CROSS_COMPILE}gcc -s -static -Os -o init init.c
76fi
77
78rm init.c
79echo "Done creating a statically linked C-language initrd"
80
81exit 0
82