c6b43051798dc507b5992c14880f3414003012b2
[dragonfly.git] / initrd / mkinitrd.sh
1 #!/bin/sh
2 #
3 # Copyright (c) 2010, 2018
4 #       The DragonFly Project.  All rights reserved.
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions
8 # are met:
9 #
10 # 1. Redistributions of source code must retain the above copyright
11 #    notice, this list of conditions and the following disclaimer.
12 # 2. Redistributions in binary form must reproduce the above copyright
13 #    notice, this list of conditions and the following disclaimer in
14 #    the documentation and/or other materials provided with the
15 #    distribution.
16 # 3. Neither the name of The DragonFly Project nor the names of its
17 #    contributors may be used to endorse or promote products derived
18 #    from this software without specific, prior written permission.
19 #
20 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 # ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23 # FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
24 # COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25 # INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
26 # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28 # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29 # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
30 # OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 # SUCH DAMAGE.
32 #
33
34 #
35 # Description
36 #
37 # This tool packs the (statically linked) rescue tools (at /rescue by
38 # default) and contents specified by "-c <content_dirs>", such as the
39 # necessary etc files, into an UFS-formatted VN image.  This image is
40 # installed at /boot/kernel/initrd.img.gz and used as the initial ramdisk
41 # to help mount the real root filesystem when it is encrypted or on LVM.
42 #
43
44
45 #
46 # Default configurations
47 #
48
49 # Directory hierarchy on the initrad
50 #
51 # * 'new_root' will always be created
52 # * 'sbin' will be symlinked to 'bin'
53 # * 'tmp' will be symlinked to 'var/tmp'
54 #
55 INITRD_DIRS="bin dev etc mnt var"
56
57 # Directory of the statically linked rescue tools which will be copied
58 # onto the initrd.
59 RESCUE_DIR="/rescue"
60
61 # Specify the location that the initrd will be installed to, i.e.,
62 # <BOOT_DIR>/kernel/initrd.img.gz
63 BOOT_DIR="/boot"
64
65 # Maximum size (number of MB) allowed for the initrd image
66 INITRD_SIZE_MAX="15"  # MB
67
68 # When run from the buildworld environment do not require that
69 # things like uniq, kldload, mount, newfs, etc be in the cross-tools.
70 # These must run natively for the current system version.
71 #
72 PATH=${PATH}:/sbin:/usr/sbin:/bin:/usr/bin
73
74 #
75 # Helper functions
76 #
77
78 log() {
79         echo "$@" >&2
80 }
81
82 error() {
83         local rc=$1
84         shift
85         log "$@"
86         exit ${rc}
87 }
88
89 check_dirs() {
90         for _dir; do
91                 [ -d "${_dir}" ] ||
92                     error 1 "Directory '${_dir}' does not exist"
93         done
94         return 0
95 }
96
97 # Calculate the total size of the given directory, taking care of the
98 # hard links.
99 #
100 # NOTE: Do not use 'du' since it gives the disk usage of the files,
101 #       which varies between different filesystems.
102 #
103 calc_size() {
104         find "$1" -ls | \
105             awk '{ print $7,$1 }' | \
106             sort -n -k 2 | \
107             uniq -f 1 | \
108             awk '{ sum+=$1 } END { print sum }'  # byte
109 }
110
111
112 #
113 # Functions
114 #
115
116 calc_initrd_size() {
117         log "Calculating required initrd size ..."
118         isize=0
119         for _dir; do
120                 csize=$(calc_size ${_dir})
121                 log "* ${_dir}: ${csize} bytes"
122                 isize=$((${isize} + ${csize}))
123         done
124         # Round initrd size up by MB
125         isize_mb=$(echo ${isize} | awk '
126             function ceil(x) {
127                 y = int(x);
128                 return (x>y ? y+1 : y);
129             }
130             {
131                 mb = $1/1024/1024;
132                 print ceil(mb);
133             }')
134         # Add additional 1 MB
135         echo $((${isize_mb} + 1))
136 }
137
138 create_vn() {
139         kldload -n vn
140         VN_DEV=$(vnconfig -c -S ${INITRD_SIZE}m -Z -T vn ${INITRD_FILE}) &&
141             echo "Configured ${VN_DEV}" ||
142             error 1 "Failed to configure VN device"
143
144         newfs -i 131072 -m 0 /dev/${VN_DEV}s0 &&
145             echo "Formatted initrd image with UFS" ||
146             error 1 "Failed to format the initrd image"
147         mount_ufs /dev/${VN_DEV}s0 ${BUILD_DIR} &&
148             echo "Mounted initrd image on ${BUILD_DIR}" ||
149             error 1 "Failed to mount initrd image on ${BUILD_DIR}"
150 }
151
152 destroy_vn() {
153         umount /dev/${VN_DEV}s0 &&
154             echo "Unmounted initrd image" ||
155             error 1 "Failed to umount initrd image"
156         vnconfig -u ${VN_DEV} &&
157             echo "Unconfigured ${VN_DEV}" ||
158             error 1 "Failed to unconfigure ${VN_DEV}"
159 }
160
161 make_hier() {
162         mkdir -p ${BUILD_DIR}/new_root ||
163             error 1 "Failed to mkdir ${BUILD_DIR}/new_root"
164         # Symlink 'sbin' to 'bin'
165         ln -sf bin ${BUILD_DIR}/sbin
166         # Symlink 'tmp' to 'var/tmp', as '/var' will be mounted with
167         # tmpfs, saving a second tmpfs been mounted on '/tmp'.
168         ln -sf var/tmp ${BUILD_DIR}/tmp
169         for _dir in ${INITRD_DIRS}; do
170                 [ ! -d "${BUILD_DIR}/${_dir}" ] &&
171                     mkdir -p ${BUILD_DIR}/${_dir}
172         done
173         echo "Created directory structure"
174 }
175
176 copy_rescue() {
177         cpdup -o -u ${RESCUE_DIR}/ ${BUILD_DIR}/bin/ &&
178             echo "Copied ${RESCUE_DIR} to ${BUILD_DIR}/bin" ||
179             error 1 "Failed to copy ${RESCUE_DIR} to ${BUILD_DIR}/bin"
180 }
181
182 copy_content() {
183         for _dir in ${CONTENT_DIRS}; do
184                 cpdup -o -u ${_dir}/ ${BUILD_DIR}/ &&
185                     echo "Copied ${_dir} to ${BUILD_DIR}" ||
186                     error 1 "Failed to copy ${dir} to ${BUILD_DIR}"
187         done
188 }
189
190 print_info() {
191         lt ${BUILD_DIR}
192         df -h ${BUILD_DIR}
193 }
194
195 # Check the validity of the created initrd image before moving over.
196 # This prevents creating an empty and broken initrd image by running
197 # this tool but without ${CONTENT_DIRS} prepared.
198 #
199 # NOTE: Need more improvements.
200 #
201 check_initrd()
202 {
203         [ -x "${BUILD_DIR}/sbin/oinit" ] &&
204         [ -x "${BUILD_DIR}/bin/sh" ] &&
205         [ -x "${BUILD_DIR}/etc/rc" ] || {
206                 destroy_vn
207                 error 1 "Ivalid initrd image!"
208         }
209 }
210
211 usage() {
212         error 2 \
213             "usage: ${0##*/} [-b boot_dir] [-r rescue_dir]" \
214             "[-s size] [-S max_size] -c <content_dirs>"
215 }
216
217
218 #
219 # Main
220 #
221
222 while getopts :b:c:hr:s:S: opt; do
223         case ${opt} in
224         b)
225                 BOOT_DIR="${OPTARG}"
226                 ;;
227         c)
228                 CONTENT_DIRS="${OPTARG}"
229                 ;;
230         h)
231                 usage
232                 ;;
233         r)
234                 RESCUE_DIR="${OPTARG}"
235                 ;;
236         s)
237                 INITRD_SIZE="${OPTARG}"
238                 ;;
239         S)
240                 INITRD_SIZE_MAX="${OPTARG}"
241                 ;;
242         \?)
243                 log "Invalid option -${OPTARG}"
244                 usage
245                 ;;
246         :)
247                 log "Option -${OPTARG} requires an argument"
248                 usage
249                 ;;
250         esac
251 done
252
253 shift $((OPTIND - 1))
254 [ $# -ne 0 ] && usage
255 [ -z "${BOOT_DIR}" -o -z "${RESCUE_DIR}" -o -z "${CONTENT_DIRS}" ] && usage
256 check_dirs ${BOOT_DIR} ${RESCUE_DIR} ${CONTENT_DIRS}
257
258 VN_DEV=""
259 INITRD_SIZE=${INITRD_SIZE%[mM]}  # MB
260 INITRD_SIZE_MAX=${INITRD_SIZE_MAX%[mM]}  # MB
261
262 BUILD_DIR=$(mktemp -d -t initrd) || error $? "Cannot create build directory"
263 echo "Initrd build directory: ${BUILD_DIR}"
264 INITRD_FILE="${BUILD_DIR}.img"
265 INITRD_DEST="${BOOT_DIR}/kernel/initrd.img.gz"
266
267 CSIZE=$(calc_initrd_size ${RESCUE_DIR} ${CONTENT_DIRS})
268 echo "Required initrd image size: ${CSIZE} MB"
269 if [ -n "${INITRD_SIZE}" -a "${INITRD_SIZE}" != "0" ]; then
270         if [ ${CSIZE} -gt ${INITRD_SIZE} ]; then
271                 error 1 "Given initrd size (${INITRD_SIZE} MB) too small"
272         fi
273 else
274         INITRD_SIZE=${CSIZE}
275 fi
276 echo "Initrd size: ${INITRD_SIZE} MB"
277
278 if [ -n "${INITRD_SIZE_MAX}" -a "${INITRD_SIZE_MAX}" != "0" ] && \
279    [ ${INITRD_SIZE} -gt ${INITRD_SIZE_MAX} ]; then
280         error 1 "Exceeded the maximum size (${INITRD_SIZE_MAX} MB)"
281 fi
282
283 create_vn
284 make_hier
285 copy_rescue
286 copy_content
287 print_info
288 destroy_vn
289 rm -rf ${BUILD_DIR}
290
291 echo -n "Compressing ${INITRD_FILE} ..."
292 gzip -9 ${INITRD_FILE}
293 echo " OK"
294
295 if [ -f "${INITRD_DEST}" ]; then
296         echo -n "Backing up ${INITRD_DEST} ..."
297         mv ${INITRD_DEST} ${INITRD_DEST}.old
298         echo " OK (${INITRD_DEST}.old)"
299 fi
300
301 echo -n "Copying ${INITRD_FILE}.gz to ${INITRD_DEST} ..."
302 install -o root -g wheel -m 444 ${INITRD_FILE}.gz ${INITRD_DEST}
303 echo " OK"
304 rm -f ${INITRD_FILE}.gz