xref: /freebsd/tools/tools/nanobsd/defaults.sh (revision 7d536dc855c85c15bf45f033d108a61b1f3cecc3)
1#!/bin/sh
2#
3# Copyright (c) 2005 Poul-Henning Kamp.
4# 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# 1. Redistributions of source code must retain the above copyright
10#    notice, this list of conditions and the following disclaimer.
11# 2. Redistributions in binary form must reproduce the above copyright
12#    notice, this list of conditions and the following disclaimer in the
13#    documentation and/or other materials provided with the distribution.
14#
15# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25# SUCH DAMAGE.
26#
27# $FreeBSD$
28#
29
30set -e
31
32#######################################################################
33#
34# Setup default values for all controlling variables.
35# These values can be overridden from the config file(s)
36#
37#######################################################################
38
39# Name of this NanoBSD build.  (Used to construct workdir names)
40NANO_NAME=full
41
42# Source tree directory
43NANO_SRC=/usr/src
44
45# Where nanobsd additional files live under the source tree
46NANO_TOOLS=tools/tools/nanobsd
47
48# Where cust_pkgng() finds packages to install
49NANO_PACKAGE_DIR=${NANO_SRC}/${NANO_TOOLS}/Pkg
50NANO_PACKAGE_LIST="*"
51
52# where package metadata gets placed
53NANO_PKG_META_BASE=/var/db
54
55# Object tree directory
56# default is subdir of /usr/obj
57#NANO_OBJ=""
58
59# The directory to put the final images
60# default is ${NANO_OBJ}
61#NANO_DISKIMGDIR=""
62
63# Make & parallel Make
64NANO_MAKE="make"
65NANO_PMAKE="make -j 3"
66
67# The default name for any image we create.
68NANO_IMGNAME="_.disk.full"
69
70# Options to put in make.conf during buildworld only
71CONF_BUILD=' '
72
73# Options to put in make.conf during installworld only
74CONF_INSTALL=' '
75
76# Options to put in make.conf during both build- & installworld.
77CONF_WORLD=' '
78
79# Kernel config file to use
80NANO_KERNEL=GENERIC
81
82# Kernel modules to install. If empty, no modules are installed.
83# Use "default" to install all built modules.
84NANO_MODULES=
85
86# Customize commands.
87NANO_CUSTOMIZE=""
88
89# Late customize commands.
90NANO_LATE_CUSTOMIZE=""
91
92# Newfs paramters to use
93NANO_NEWFS="-b 4096 -f 512 -i 8192 -U"
94
95# The drive name of the media at runtime
96NANO_DRIVE=ada0
97
98# Target media size in 512 bytes sectors
99NANO_MEDIASIZE=2000000
100
101# Number of code images on media (1 or 2)
102NANO_IMAGES=2
103
104# 0 -> Leave second image all zeroes so it compresses better.
105# 1 -> Initialize second image with a copy of the first
106NANO_INIT_IMG2=1
107
108# Size of code file system in 512 bytes sectors
109# If zero, size will be as large as possible.
110NANO_CODESIZE=0
111
112# Size of configuration file system in 512 bytes sectors
113# Cannot be zero.
114NANO_CONFSIZE=2048
115
116# Size of data file system in 512 bytes sectors
117# If zero: no partition configured.
118# If negative: max size possible
119NANO_DATASIZE=0
120
121# Size of the /etc ramdisk in 512 bytes sectors
122NANO_RAM_ETCSIZE=10240
123
124# Size of the /tmp+/var ramdisk in 512 bytes sectors
125NANO_RAM_TMPVARSIZE=10240
126
127# Media geometry, only relevant if bios doesn't understand LBA.
128NANO_SECTS=63
129NANO_HEADS=16
130
131# boot0 flags/options and configuration
132NANO_BOOT0CFG="-o packet -s 1 -m 3"
133NANO_BOOTLOADER="boot/boot0sio"
134
135# boot2 flags/options
136# default force serial console
137NANO_BOOT2CFG="-h -S115200"
138
139# Backing type of md(4) device
140# Can be "file" or "swap"
141NANO_MD_BACKING="file"
142
143# for swap type md(4) backing, write out the mbr only
144NANO_IMAGE_MBRONLY=true
145
146# Progress Print level
147PPLEVEL=3
148
149# Set NANO_LABEL to non-blank to form the basis for using /dev/ufs/label
150# in preference to /dev/${NANO_DRIVE}
151# Root partition will be ${NANO_LABEL}s{1,2}
152# /cfg partition will be ${NANO_LABEL}s3
153# /data partition will be ${NANO_LABEL}s4
154NANO_LABEL=""
155NANO_SLICE_ROOT=s1
156NANO_SLICE_ALTROOT=s2
157NANO_SLICE_CFG=s3
158NANO_SLICE_DATA=s4
159NANO_ROOT=s1a
160NANO_ALTROOT=s2a
161
162# Default ownwership for nopriv build
163NANO_DEF_UNAME=root
164NANO_DEF_GNAME=wheel
165
166#######################################################################
167# Architecture to build.  Corresponds to TARGET_ARCH in a buildworld.
168# Unfortunately, there's no way to set TARGET at this time, and it
169# conflates the two, so architectures where TARGET != TARGET_ARCH and
170# TARGET can't be guessed from TARGET_ARCH do not work.  This defaults
171# to the arch of the current machine.
172NANO_ARCH=`uname -p`
173
174# CPUTYPE defaults to "" which is the default when CPUTYPE isn't
175# defined.
176NANO_CPUTYPE=""
177
178# Directory to populate /cfg from
179NANO_CFGDIR=""
180
181# Directory to populate /data from
182NANO_DATADIR=""
183
184# We don't need SRCCONF or SRC_ENV_CONF. NanoBSD puts everything we
185# need for the build in files included with __MAKE_CONF. Override in your
186# config file if you really must. We set them unconditionally here, though
187# in case they are stray in the build environment
188SRCCONF=/dev/null
189SRC_ENV_CONF=/dev/null
190
191#######################################################################
192#
193# The functions which do the real work.
194# Can be overridden from the config file(s)
195#
196#######################################################################
197
198# Export values into the shell. Must use { } instead of ( ) like
199# other functions to avoid a subshell.
200# We set __MAKE_CONF as a global since it is easier to get quoting
201# right for paths with spaces in them.
202make_export ( ) {
203	# Similar to export_var, except puts the data out to stdout
204	var=$1
205	eval val=\$$var
206	echo "Setting variable: $var=\"$val\""
207	export $1
208}
209
210nano_make_build_env ( ) {
211	__MAKE_CONF="${NANO_MAKE_CONF_BUILD}"
212	make_export __MAKE_CONF
213}
214
215nano_make_install_env ( ) {
216	__MAKE_CONF="${NANO_MAKE_CONF_INSTALL}"
217	make_export __MAKE_CONF
218}
219
220# Extra environment variables for kernel builds
221nano_make_kernel_env ( ) {
222	if [ -f ${NANO_KERNEL} ] ; then
223		KERNCONFDIR="$(realpath $(dirname ${NANO_KERNEL}))"
224		KERNCONF="$(basename ${NANO_KERNEL})"
225		make_export KERNCONFDIR
226		make_export KERNCONF
227	else
228		export KERNCONF="${NANO_KERNEL}"
229		make_export KERNCONF
230	fi
231}
232
233nano_global_make_env ( ) (
234	# global settings for the make.conf file, if set
235	[ -z "${NANO_ARCH}" ] || echo TARGET_ARCH="${NANO_ARCH}"
236	[ -z "${NANO_CPUTYPE}" ] || echo TARGET_CPUTYPE="${NANO_CPUTYPE}"
237)
238
239# rm doesn't know -x prior to FreeBSD 10, so cope with a variety of build
240# hosts for now. This will go away when support in the base goes away.
241rm ( ) {
242    echo "NANO RM $*"
243	case $(uname -r) in
244	7*|8*|9*) command rm $* ;;
245	*) command rm -x $* ;;
246	esac
247}
248
249#
250# Create empty files in the target tree, and record the fact.  All paths
251# are relative to NANO_WORLDDIR.
252#
253tgt_touch ( ) (
254
255	cd "${NANO_WORLDDIR}"
256	for i; do
257		touch $i
258		echo "./${i} type=file" >> ${NANO_METALOG}
259	done
260)
261
262#
263# Convert a directory into a symlink. Takes two arguments, the
264# current directory and what it should become a symlink to. The
265# directory is removed and a symlink is created. If we're doing
266# a nopriv build, then append this fact to the metalog
267#
268tgt_dir2symlink () (
269	dir=$1
270	symlink=$2
271
272	cd "${NANO_WORLDDIR}"
273	rm -rf "$dir"
274	ln -s "$symlink" "$dir"
275	if [ -n "$NANO_METALOG" ]; then
276		echo "./${dir} type=link mode=0777 link=${symlink}" >> ${NANO_METALOG}
277	fi
278)
279
280# run in the world chroot, errors fatal
281CR ( ) {
282	chroot "${NANO_WORLDDIR}" /bin/sh -exc "$*"
283}
284
285# run in the world chroot, errors not fatal
286CR0 ( ) {
287	chroot "${NANO_WORLDDIR}" /bin/sh -c "$*" || true
288}
289
290nano_cleanup ( ) (
291	[ $? -eq 0 ] || echo "Error encountered.  Check for errors in last log file." 1>&2
292	exit $?
293)
294
295clean_build ( ) (
296	pprint 2 "Clean and create object directory (${MAKEOBJDIRPREFIX})"
297
298	if ! rm -rf ${MAKEOBJDIRPREFIX}/ > /dev/null 2>&1 ; then
299		chflags -R noschg ${MAKEOBJDIRPREFIX}/
300		rm -r ${MAKEOBJDIRPREFIX}/
301	fi
302)
303
304make_conf_build ( ) (
305	pprint 2 "Construct build make.conf ($NANO_MAKE_CONF_BUILD)"
306
307	mkdir -p ${MAKEOBJDIRPREFIX}
308	printenv > ${MAKEOBJDIRPREFIX}/_.env
309
310	# Make sure we get all the global settings that NanoBSD wants
311	# in addition to the user's global settings
312	(
313	nano_global_make_env
314	echo "${CONF_WORLD}"
315	echo "${CONF_BUILD}"
316	) > ${NANO_MAKE_CONF_BUILD}
317)
318
319build_world ( ) (
320	pprint 2 "run buildworld"
321	pprint 3 "log: ${MAKEOBJDIRPREFIX}/_.bw"
322
323	(
324	nano_make_build_env
325	set -o xtrace
326	cd "${NANO_SRC}"
327	${NANO_PMAKE} buildworld
328	) > ${MAKEOBJDIRPREFIX}/_.bw 2>&1
329)
330
331build_kernel ( ) (
332	local extra
333
334	pprint 2 "build kernel ($NANO_KERNEL)"
335	pprint 3 "log: ${MAKEOBJDIRPREFIX}/_.bk"
336
337	(
338	nano_make_build_env
339	nano_make_kernel_env
340
341	# Note: We intentionally build all modules, not only the ones in
342	# NANO_MODULES so the built world can be reused by multiple images.
343	# Although MODULES_OVERRIDE can be defined in the kenrel config
344	# file to override this behavior. Just set NANO_MODULES=default.
345	set -o xtrace
346	cd "${NANO_SRC}"
347	${NANO_PMAKE} buildkernel
348	) > ${MAKEOBJDIRPREFIX}/_.bk 2>&1
349)
350
351clean_world ( ) (
352	if [ "${NANO_OBJ}" != "${MAKEOBJDIRPREFIX}" ]; then
353		pprint 2 "Clean and create object directory (${NANO_OBJ})"
354		if ! rm -rf ${NANO_OBJ}/ > /dev/null 2>&1 ; then
355			chflags -R noschg ${NANO_OBJ}
356			rm -r ${NANO_OBJ}/
357		fi
358		mkdir -p "${NANO_OBJ}" "${NANO_WORLDDIR}"
359		printenv > ${NANO_LOG}/_.env
360	else
361		pprint 2 "Clean and create world directory (${NANO_WORLDDIR})"
362		if ! rm -rf "${NANO_WORLDDIR}/" > /dev/null 2>&1 ; then
363			chflags -R noschg "${NANO_WORLDDIR}"
364			rm -rf "${NANO_WORLDDIR}/"
365		fi
366		mkdir -p "${NANO_WORLDDIR}"
367	fi
368)
369
370make_conf_install ( ) (
371	pprint 2 "Construct install make.conf ($NANO_MAKE_CONF_INSTALL)"
372
373	# Make sure we get all the global settings that NanoBSD wants
374	# in addition to the user's global settings
375	(
376	nano_global_make_env
377	echo "${CONF_WORLD}"
378	echo "${CONF_INSTALL}"
379	if [ -n "${NANO_NOPRIV_BUILD}" ]; then
380	    echo NO_ROOT=t
381	    echo METALOG=${NANO_METALOG}
382	fi
383	) >  ${NANO_MAKE_CONF_INSTALL}
384)
385
386install_world ( ) (
387	pprint 2 "installworld"
388	pprint 3 "log: ${NANO_LOG}/_.iw"
389
390	(
391	nano_make_install_env
392	set -o xtrace
393	cd "${NANO_SRC}"
394	${NANO_MAKE} installworld DESTDIR="${NANO_WORLDDIR}"
395	chflags -R noschg "${NANO_WORLDDIR}"
396	) > ${NANO_LOG}/_.iw 2>&1
397)
398
399install_etc ( ) (
400
401	pprint 2 "install /etc"
402	pprint 3 "log: ${NANO_LOG}/_.etc"
403
404	(
405	nano_make_install_env
406	set -o xtrace
407	cd "${NANO_SRC}"
408	${NANO_MAKE} distribution DESTDIR="${NANO_WORLDDIR}"
409	# make.conf doesn't get created by default, but some ports need it
410	# so they can spam it.
411	cp /dev/null "${NANO_WORLDDIR}"/etc/make.conf
412	) > ${NANO_LOG}/_.etc 2>&1
413)
414
415install_kernel ( ) (
416	local extra
417
418	pprint 2 "install kernel ($NANO_KERNEL)"
419	pprint 3 "log: ${NANO_LOG}/_.ik"
420
421	(
422
423	nano_make_install_env
424	nano_make_kernel_env
425
426	if [ "${NANO_MODULES}" != "default" ]; then
427		MODULES_OVERRIDE="${NANO_MODULES}"
428		make_export MODULES_OVERRIDE
429	fi
430
431	set -o xtrace
432	cd "${NANO_SRC}"
433	${NANO_MAKE} installkernel DESTDIR="${NANO_WORLDDIR}"
434
435	) > ${NANO_LOG}/_.ik 2>&1
436)
437
438native_xtools ( ) (
439	print 2 "Installing the optimized native build tools for cross env"
440	pprint 3 "log: ${NANO_LOG}/_.native_xtools"
441
442	(
443
444	nano_make_install_env
445	set -o xtrace
446	cd "${NANO_SRC}"
447	${NANO_MAKE} native-xtools DESTDIR="${NANO_WORLDDIR}"
448
449	) > ${NANO_LOG}/_.native_xtools 2>&1
450)
451
452#
453# Run the requested set of customization scripts, run after we've
454# done an installworld, installed the etc files, installed the kernel
455# and tweaked them in the standard way.
456#
457run_customize ( ) (
458
459	pprint 2 "run customize scripts"
460	for c in $NANO_CUSTOMIZE
461	do
462		pprint 2 "customize \"$c\""
463		pprint 3 "log: ${NANO_LOG}/_.cust.$c"
464		pprint 4 "`type $c`"
465		( set -x ; $c ) > ${NANO_LOG}/_.cust.$c 2>&1
466	done
467)
468
469#
470# Run any last-minute customization commands after we've had a chance to
471# setup nanobsd, prune empty dirs from /usr, etc
472#
473run_late_customize ( ) (
474
475	pprint 2 "run late customize scripts"
476	for c in $NANO_LATE_CUSTOMIZE
477	do
478		pprint 2 "late customize \"$c\""
479		pprint 3 "log: ${NANO_LOG}/_.late_cust.$c"
480		pprint 4 "`type $c`"
481		( set -x ; $c ) > ${NANO_LOG}/_.late_cust.$c 2>&1
482	done
483)
484
485#
486# Hook called after we run all the late customize commands, but
487# before we invoke the disk imager. The nopriv build uses it to
488# read in the meta log, apply the changes other parts of nanobsd
489# have been recording their actions. It's not anticipated that
490# a user's cfg file would override this.
491#
492fixup_before_diskimage ( ) (
493
494	# Run the deduplication script that takes the matalog journal and
495	# combines multiple entries for the same file (see source for
496	# details). We take the extra step of removing the size keywords. This
497	# script, and many of the user scripts, copies, appeneds and otherwise
498	# modifies files in the build, changing their sizes.  These actions are
499	# impossible to trap, so go ahead remove the size= keyword. For this
500	# narrow use, it doesn't buy us any protection and just gets in the way.
501	# The dedup tool's output must be sorted due to limitations in awk.
502	if [ -n "${NANO_METALOG}" ]; then
503		pprint 2 "Fixing metalog"
504		cp ${NANO_METALOG} ${NANO_METALOG}.pre
505		echo "/set uname=${NANO_DEF_UNAME} gname=${NANO_DEF_GNAME}" > ${NANO_METALOG}
506		cat ${NANO_METALOG}.pre | ${NANO_TOOLS}/mtree-dedup.awk | \
507		    sed -e 's/ size=[0-9][0-9]*//' | sort >> ${NANO_METALOG}
508	fi
509)
510
511setup_nanobsd ( ) (
512	pprint 2 "configure nanobsd setup"
513	pprint 3 "log: ${NANO_LOG}/_.dl"
514
515	(
516	cd "${NANO_WORLDDIR}"
517
518	# Move /usr/local/etc to /etc/local so that the /cfg stuff
519	# can stomp on it.  Otherwise packages like ipsec-tools which
520	# have hardcoded paths under ${prefix}/etc are not tweakable.
521	if [ -d usr/local/etc ] ; then
522		(
523		mkdir -p etc/local
524		cd usr/local/etc
525		find . -print | cpio -dumpl ../../../etc/local
526		cd ..
527		rm -rf etc
528		ln -s ../../etc/local etc
529		)
530	fi
531
532	for d in var etc
533	do
534		# link /$d under /conf
535		# we use hard links so we have them both places.
536		# the files in /$d will be hidden by the mount.
537		mkdir -p conf/base/$d conf/default/$d
538		find $d -print | cpio -dumpl conf/base/
539	done
540
541	echo "$NANO_RAM_ETCSIZE" > conf/base/etc/md_size
542	echo "$NANO_RAM_TMPVARSIZE" > conf/base/var/md_size
543
544	# pick up config files from the special partition
545	echo "mount -o ro /dev/${NANO_DRIVE}${NANO_SLICE_CFG}" > conf/default/etc/remount
546
547	# Put /tmp on the /var ramdisk (could be symlink already)
548	tgt_dir2symlink tmp var/tmp
549
550	) > ${NANO_LOG}/_.dl 2>&1
551)
552
553setup_nanobsd_etc ( ) (
554	pprint 2 "configure nanobsd /etc"
555
556	(
557	cd "${NANO_WORLDDIR}"
558
559	# create diskless marker file
560	touch etc/diskless
561
562	[ -n "${NANO_NOPRIV_BUILD}" ] && chmod 666 etc/defaults/rc.conf
563
564	# Make root filesystem R/O by default
565	echo "root_rw_mount=NO" >> etc/defaults/rc.conf
566	# Disable entropy file, since / is read-only /var/db/entropy should be enough?
567	echo "entropy_file=NO" >> etc/defaults/rc.conf
568
569	[ -n "${NANO_NOPRIV_BUILD}" ] && chmod 444 etc/defaults/rc.conf
570
571	# save config file for scripts
572	echo "NANO_DRIVE=${NANO_DRIVE}" > etc/nanobsd.conf
573
574	echo "/dev/${NANO_DRIVE}${NANO_ROOT} / ufs ro 1 1" > etc/fstab
575	echo "/dev/${NANO_DRIVE}${NANO_SLICE_CFG} /cfg ufs rw,noauto 2 2" >> etc/fstab
576	mkdir -p cfg
577	)
578)
579
580prune_usr ( ) (
581
582	# Remove all empty directories in /usr
583	find "${NANO_WORLDDIR}"/usr -type d -depth -print |
584		while read d
585		do
586			rmdir $d > /dev/null 2>&1 || true
587		done
588)
589
590newfs_part ( ) (
591	local dev mnt lbl
592	dev=$1
593	mnt=$2
594	lbl=$3
595	echo newfs ${NANO_NEWFS} ${NANO_LABEL:+-L${NANO_LABEL}${lbl}} ${dev}
596	newfs ${NANO_NEWFS} ${NANO_LABEL:+-L${NANO_LABEL}${lbl}} ${dev}
597	mount -o async ${dev} ${mnt}
598)
599
600# Convenient spot to work around any umount issues that your build environment
601# hits by overriding this method.
602nano_umount ( ) (
603	umount ${1}
604)
605
606populate_slice ( ) (
607	local dev dir mnt lbl
608	dev=$1
609	dir=$2
610	mnt=$3
611	lbl=$4
612	echo "Creating ${dev} (mounting on ${mnt})"
613	newfs_part ${dev} ${mnt} ${lbl}
614	if [ -n "${dir}" -a -d "${dir}" ]; then
615		echo "Populating ${lbl} from ${dir}"
616		cd "${dir}"
617		find . -print | grep -Ev '/(CVS|\.svn|\.hg|\.git)' | cpio -dumpv ${mnt}
618	fi
619	df -i ${mnt}
620	nano_umount ${mnt}
621)
622
623populate_cfg_slice ( ) (
624	populate_slice "$1" "$2" "$3" "$4"
625)
626
627populate_data_slice ( ) (
628	populate_slice "$1" "$2" "$3" "$4"
629)
630
631create_diskimage ( ) (
632	pprint 2 "build diskimage"
633	pprint 3 "log: ${NANO_LOG}/_.di"
634
635	(
636	echo $NANO_MEDIASIZE $NANO_IMAGES \
637		$NANO_SECTS $NANO_HEADS \
638		$NANO_CODESIZE $NANO_CONFSIZE $NANO_DATASIZE |
639	awk '
640	{
641		printf "# %s\n", $0
642
643		# size of cylinder in sectors
644		cs = $3 * $4
645
646		# number of full cylinders on media
647		cyl = int ($1 / cs)
648
649		# output fdisk geometry spec, truncate cyls to 1023
650		if (cyl <= 1023)
651			print "g c" cyl " h" $4 " s" $3
652		else
653			print "g c" 1023 " h" $4 " s" $3
654
655		if ($7 > 0) {
656			# size of data partition in full cylinders
657			dsl = int (($7 + cs - 1) / cs)
658		} else {
659			dsl = 0;
660		}
661
662		# size of config partition in full cylinders
663		csl = int (($6 + cs - 1) / cs)
664
665		if ($5 == 0) {
666			# size of image partition(s) in full cylinders
667			isl = int ((cyl - dsl - csl) / $2)
668		} else {
669			isl = int (($5 + cs - 1) / cs)
670		}
671
672		# First image partition start at second track
673		print "p 1 165 " $3, isl * cs - $3
674		c = isl * cs;
675
676		# Second image partition (if any) also starts offset one
677		# track to keep them identical.
678		if ($2 > 1) {
679			print "p 2 165 " $3 + c, isl * cs - $3
680			c += isl * cs;
681		}
682
683		# Config partition starts at cylinder boundary.
684		print "p 3 165 " c, csl * cs
685		c += csl * cs
686
687		# Data partition (if any) starts at cylinder boundary.
688		if ($7 > 0) {
689			print "p 4 165 " c, dsl * cs
690		} else if ($7 < 0 && $1 > c) {
691			print "p 4 165 " c, $1 - c
692		} else if ($1 < c) {
693			print "Disk space overcommitted by", \
694			    c - $1, "sectors" > "/dev/stderr"
695			exit 2
696		}
697
698		# Force slice 1 to be marked active. This is necessary
699		# for booting the image from a USB device to work.
700		print "a 1"
701	}
702	' > ${NANO_LOG}/_.fdisk
703
704	IMG=${NANO_DISKIMGDIR}/${NANO_IMGNAME}
705	MNT=${NANO_OBJ}/_.mnt
706	mkdir -p ${MNT}
707
708	if [ "${NANO_MD_BACKING}" = "swap" ] ; then
709		MD=`mdconfig -a -t swap -s ${NANO_MEDIASIZE} -x ${NANO_SECTS} \
710			-y ${NANO_HEADS}`
711	else
712		echo "Creating md backing file..."
713		rm -f ${IMG}
714		dd if=/dev/zero of=${IMG} seek=${NANO_MEDIASIZE} count=0
715		MD=`mdconfig -a -t vnode -f ${IMG} -x ${NANO_SECTS} \
716			-y ${NANO_HEADS}`
717	fi
718
719	trap "echo 'Running exit trap code' ; df -i ${MNT} ; nano_umount ${MNT} || true ; mdconfig -d -u $MD" 1 2 15 EXIT
720
721	fdisk -i -f ${NANO_LOG}/_.fdisk ${MD}
722	fdisk ${MD}
723	# XXX: params
724	# XXX: pick up cached boot* files, they may not be in image anymore.
725	if [ -f ${NANO_WORLDDIR}/${NANO_BOOTLOADER} ]; then
726		boot0cfg -B -b ${NANO_WORLDDIR}/${NANO_BOOTLOADER} ${NANO_BOOT0CFG} ${MD}
727	fi
728	if [ -f ${NANO_WORLDDIR}/boot/boot ]; then
729		bsdlabel -w -B -b ${NANO_WORLDDIR}/boot/boot ${MD}${NANO_SLICE_ROOT}
730	else
731		bsdlabel -w ${MD}${NANO_SLICE_ROOT}
732	fi
733	bsdlabel ${MD}${NANO_SLICE_ROOT}
734
735	# Create first image
736	populate_slice /dev/${MD}${NANO_ROOT} ${NANO_WORLDDIR} ${MNT} "${NANO_ROOT}"
737	mount /dev/${MD}${NANO_ROOT} ${MNT}
738	echo "Generating mtree..."
739	( cd "${MNT}" && mtree -c ) > ${NANO_LOG}/_.mtree
740	( cd "${MNT}" && du -k ) > ${NANO_LOG}/_.du
741	nano_umount "${MNT}"
742
743	if [ $NANO_IMAGES -gt 1 -a $NANO_INIT_IMG2 -gt 0 ] ; then
744		# Duplicate to second image (if present)
745		echo "Duplicating to second image..."
746		dd conv=sparse if=/dev/${MD}${NANO_SLICE_ROOT} of=/dev/${MD}${NANO_SLICE_ALTROOT} bs=64k
747		mount /dev/${MD}${NANO_ALTROOT} ${MNT}
748		for f in ${MNT}/etc/fstab ${MNT}/conf/base/etc/fstab
749		do
750			sed -i "" "s=${NANO_DRIVE}${NANO_SLICE_ROOT}=${NANO_DRIVE}${NANO_SLICE_ALTROOT}=g" $f
751		done
752		nano_umount ${MNT}
753		# Override the label from the first partition so we
754		# don't confuse glabel with duplicates.
755		if [ -n "${NANO_LABEL}" ]; then
756			tunefs -L ${NANO_LABEL}"${NANO_ALTROOT}" /dev/${MD}${NANO_ALTROOT}
757		fi
758	fi
759
760	# Create Config slice
761	populate_cfg_slice /dev/${MD}${NANO_SLICE_CFG} "${NANO_CFGDIR}" ${MNT} "${NANO_SLICE_CFG}"
762
763	# Create Data slice, if any.
764	if [ -n "$NANO_SLICE_DATA" -a "$NANO_SLICE_CFG" = "$NANO_SLICE_DATA" -a \
765	   "$NANO_DATASIZE" -ne 0 ]; then
766		pprint 2 "NANO_SLICE_DATA is the same as NANO_SLICE_CFG, fix."
767		exit 2
768	fi
769	if [ $NANO_DATASIZE -ne 0 -a -n "$NANO_SLICE_DATA" ] ; then
770		populate_data_slice /dev/${MD}${NANO_SLICE_DATA} "${NANO_DATADIR}" ${MNT} "${NANO_SLICE_DATA}"
771	fi
772
773	if [ "${NANO_MD_BACKING}" = "swap" ] ; then
774		if [ ${NANO_IMAGE_MBRONLY} ]; then
775			echo "Writing out _.disk.mbr..."
776			dd if=/dev/${MD} of=${NANO_DISKIMGDIR}/_.disk.mbr bs=512 count=1
777		else
778			echo "Writing out ${NANO_IMGNAME}..."
779			dd if=/dev/${MD} of=${IMG} bs=64k
780		fi
781
782		echo "Writing out ${NANO_IMGNAME}..."
783		dd conv=sparse if=/dev/${MD} of=${IMG} bs=64k
784	fi
785
786	if ${do_copyout_partition} ; then
787		echo "Writing out _.disk.image..."
788		dd conv=sparse if=/dev/${MD}${NANO_SLICE_ROOT} of=${NANO_DISKIMGDIR}/_.disk.image bs=64k
789	fi
790	mdconfig -d -u $MD
791
792	trap - 1 2 15
793	trap nano_cleanup EXIT
794
795	) > ${NANO_LOG}/_.di 2>&1
796)
797
798last_orders ( ) (
799	# Redefine this function with any last orders you may have
800	# after the build completed, for instance to copy the finished
801	# image to a more convenient place:
802	# cp ${NANO_DISKIMGDIR}/_.disk.image /home/ftp/pub/nanobsd.disk
803	true
804)
805
806#######################################################################
807#
808# Optional convenience functions.
809#
810#######################################################################
811
812#######################################################################
813# Common Flash device geometries
814#
815
816FlashDevice ( ) {
817	if [ -d ${NANO_TOOLS} ] ; then
818		. ${NANO_TOOLS}/FlashDevice.sub
819	else
820		. ${NANO_SRC}/${NANO_TOOLS}/FlashDevice.sub
821	fi
822	sub_FlashDevice $1 $2
823}
824
825#######################################################################
826# USB device geometries
827#
828# Usage:
829#	UsbDevice Generic 1000	# a generic flash key sold as having 1GB
830#
831# This function will set NANO_MEDIASIZE, NANO_HEADS and NANO_SECTS for you.
832#
833# Note that the capacity of a flash key is usually advertised in MB or
834# GB, *not* MiB/GiB. As such, the precise number of cylinders available
835# for C/H/S geometry may vary depending on the actual flash geometry.
836#
837# The following generic device layouts are understood:
838#  generic           An alias for generic-hdd.
839#  generic-hdd       255H 63S/T xxxxC with no MBR restrictions.
840#  generic-fdd       64H 32S/T xxxxC with no MBR restrictions.
841#
842# The generic-hdd device is preferred for flash devices larger than 1GB.
843#
844
845UsbDevice ( ) {
846	a1=`echo $1 | tr '[:upper:]' '[:lower:]'`
847	case $a1 in
848	generic-fdd)
849		NANO_HEADS=64
850		NANO_SECTS=32
851		NANO_MEDIASIZE=$(( $2 * 1000 * 1000 / 512 ))
852		;;
853	generic|generic-hdd)
854		NANO_HEADS=255
855		NANO_SECTS=63
856		NANO_MEDIASIZE=$(( $2 * 1000 * 1000 / 512 ))
857		;;
858	*)
859		echo "Unknown USB flash device"
860		exit 2
861		;;
862	esac
863}
864
865#######################################################################
866# Setup serial console
867
868cust_comconsole ( ) (
869	# Enable getty on console
870	sed -i "" -e /tty[du]0/s/off/on/ ${NANO_WORLDDIR}/etc/ttys
871
872	# Disable getty on syscons devices
873	sed -i "" -e '/^ttyv[0-8]/s/	on/	off/' ${NANO_WORLDDIR}/etc/ttys
874
875	# Tell loader to use serial console early.
876	echo "${NANO_BOOT2CFG}" > ${NANO_WORLDDIR}/boot.config
877)
878
879#######################################################################
880# Allow root login via ssh
881
882cust_allow_ssh_root ( ) (
883	sed -i "" -e '/PermitRootLogin/s/.*/PermitRootLogin yes/' \
884	    ${NANO_WORLDDIR}/etc/ssh/sshd_config
885)
886
887#######################################################################
888# Install the stuff under ./Files
889
890cust_install_files ( ) (
891	cd "${NANO_TOOLS}/Files"
892	find . -print | grep -Ev '/(CVS|\.svn|\.hg|\.git)' | cpio -Ldumpv ${NANO_WORLDDIR}
893)
894
895#######################################################################
896# Install packages from ${NANO_PACKAGE_DIR}
897
898cust_pkgng ( ) (
899
900	# If the package directory doesn't exist, we're done.
901	if [ ! -d ${NANO_PACKAGE_DIR} ]; then
902		echo "DONE 0 packages"
903		return 0
904	fi
905
906	# Find a pkg-* package
907	for x in `find -s ${NANO_PACKAGE_DIR} -iname 'pkg-*'`; do
908		_NANO_PKG_PACKAGE=`basename "$x"`
909	done
910	if [ -z "${_NANO_PKG_PACKAGE}" -o ! -f "${NANO_PACKAGE_DIR}/${_NANO_PKG_PACKAGE}" ]; then
911		echo "FAILED: need a pkg/ package for bootstrapping"
912		exit 2
913	fi
914
915	# Copy packages into chroot
916	mkdir -p ${NANO_WORLDDIR}/Pkg
917	(
918		cd "${NANO_PACKAGE_DIR}"
919		find "${NANO_PACKAGE_LIST}" -print |
920		cpio -Ldumpv ${NANO_WORLDDIR}/Pkg
921	)
922
923	#Bootstrap pkg
924	CR env ASSUME_ALWAYS_YES=YES SIGNATURE_TYPE=none /usr/sbin/pkg add /Pkg/${_NANO_PKG_PACKAGE}
925	CR pkg -N >/dev/null 2>&1
926	if [ "$?" -ne "0" ]; then
927		echo "FAILED: pkg bootstrapping faied"
928		exit 2
929	fi
930	rm -f ${NANO_WORLDDIR}/Pkg/pkg-*
931
932	# Count & report how many we have to install
933	todo=`ls ${NANO_WORLDDIR}/Pkg | /usr/bin/wc -l`
934	todo=$(expr $todo + 1) # add one for pkg since it is installed already
935	echo "=== TODO: $todo"
936	ls ${NANO_WORLDDIR}/Pkg
937	echo "==="
938	while true
939	do
940		# Record how many we have now
941 		have=$(CR env ASSUME_ALWAYS_YES=YES /usr/sbin/pkg info | /usr/bin/wc -l)
942
943		# Attempt to install more packages
944		CR0 'ls 'Pkg/*txz' | xargs env ASSUME_ALWAYS_YES=YES /usr/sbin/pkg add'
945
946		# See what that got us
947 		now=$(CR env ASSUME_ALWAYS_YES=YES /usr/sbin/pkg info | /usr/bin/wc -l)
948		echo "=== NOW $now"
949		CR env ASSUME_ALWAYS_YES=YES /usr/sbin/pkg info
950		echo "==="
951		if [ $now -eq $todo ] ; then
952			echo "DONE $now packages"
953			break
954		elif [ $now -eq $have ] ; then
955			echo "FAILED: Nothing happened on this pass"
956			exit 2
957		fi
958	done
959	rm -rf ${NANO_WORLDDIR}/Pkg
960)
961
962#######################################################################
963# Convenience function:
964# 	Register all args as customize function.
965
966customize_cmd ( ) {
967	NANO_CUSTOMIZE="$NANO_CUSTOMIZE $*"
968}
969
970#######################################################################
971# Convenience function:
972# 	Register all args as late customize function to run just before
973#	image creation.
974
975late_customize_cmd ( ) {
976	NANO_LATE_CUSTOMIZE="$NANO_LATE_CUSTOMIZE $*"
977}
978
979#######################################################################
980#
981# All set up to go...
982#
983#######################################################################
984
985# Progress Print
986#	Print $2 at level $1.
987pprint ( ) (
988    if [ "$1" -le $PPLEVEL ]; then
989	runtime=$(( `date +%s` - $NANO_STARTTIME ))
990	printf "%s %.${1}s %s\n" "`date -u -r $runtime +%H:%M:%S`" "#####" "$2" 1>&3
991    fi
992)
993
994usage ( ) {
995	(
996	echo "Usage: $0 [-bfiKknqvw] [-c config_file]"
997	echo "	-b	suppress builds (both kernel and world)"
998	echo "	-c	specify config file"
999	echo "	-f	suppress code slice extraction"
1000	echo "	-i	suppress disk image build"
1001	echo "	-K	suppress installkernel"
1002	echo "	-k	suppress buildkernel"
1003	echo "	-n	add -DNO_CLEAN to buildworld, buildkernel, etc"
1004	echo "	-q	make output more quiet"
1005	echo "	-v	make output more verbose"
1006	echo "	-w	suppress buildworld"
1007	) 1>&2
1008	exit 2
1009}
1010
1011#######################################################################
1012# Setup and Export Internal variables
1013#
1014
1015export_var ( ) {		# Don't wawnt a subshell
1016	var=$1
1017	# Lookup value of the variable.
1018	eval val=\$$var
1019	pprint 3 "Setting variable: $var=\"$val\""
1020	export $1
1021}
1022
1023# Call this function to set defaults _after_ parsing options.
1024# dont want a subshell otherwise variable setting is thrown away.
1025set_defaults_and_export ( ) {
1026	: ${NANO_OBJ:=/usr/obj/nanobsd.${NANO_NAME}}
1027	: ${MAKEOBJDIRPREFIX:=${NANO_OBJ}}
1028	: ${NANO_DISKIMGDIR:=${NANO_OBJ}}
1029	: ${NANO_WORLDDIR:=${NANO_OBJ}/_.w}
1030	: ${NANO_LOG:=${NANO_OBJ}}
1031	NANO_MAKE_CONF_BUILD=${MAKEOBJDIRPREFIX}/make.conf.build
1032	NANO_MAKE_CONF_INSTALL=${NANO_OBJ}/make.conf.install
1033
1034	# Override user's NANO_DRIVE if they specified a NANO_LABEL
1035	[ -n "${NANO_LABEL}" ] && NANO_DRIVE="ufs/${NANO_LABEL}" || true
1036
1037	# Set a default NANO_TOOLS to NANO_SRC/NANO_TOOLS if it exists.
1038	[ ! -d "${NANO_TOOLS}" ] && [ -d "${NANO_SRC}/${NANO_TOOLS}" ] && \
1039		NANO_TOOLS="${NANO_SRC}/${NANO_TOOLS}" || true
1040
1041	[ -n "${NANO_NOPRIV_BUILD}" ] && [ -z "${NANO_METALOG}" ] && \
1042		NANO_METALOG=${NANO_OBJ}/_.metalog || true
1043
1044	NANO_STARTTIME=`date +%s`
1045	pprint 3 "Exporting NanoBSD variables"
1046	export_var MAKEOBJDIRPREFIX
1047	export_var NANO_ARCH
1048	export_var NANO_CODESIZE
1049	export_var NANO_CONFSIZE
1050	export_var NANO_CUSTOMIZE
1051	export_var NANO_DATASIZE
1052	export_var NANO_DRIVE
1053	export_var NANO_HEADS
1054	export_var NANO_IMAGES
1055	export_var NANO_IMGNAME
1056	export_var NANO_MAKE
1057	export_var NANO_MAKE_CONF_BUILD
1058	export_var NANO_MAKE_CONF_INSTALL
1059	export_var NANO_MEDIASIZE
1060	export_var NANO_NAME
1061	export_var NANO_NEWFS
1062	export_var NANO_OBJ
1063	export_var NANO_PMAKE
1064	export_var NANO_SECTS
1065	export_var NANO_SRC
1066	export_var NANO_TOOLS
1067	export_var NANO_WORLDDIR
1068	export_var NANO_BOOT0CFG
1069	export_var NANO_BOOTLOADER
1070	export_var NANO_LABEL
1071	export_var NANO_MODULES
1072	export_var NANO_NOPRIV_BUILD
1073	export_var NANO_METALOG
1074	export_var NANO_LOG
1075	export_var SRCCONF
1076	export_var SRC_ENV_CONF
1077}
1078