e3240a6e5ee4e8499bd75fb21222c44fd7277e89
[AGL/meta-agl.git] / scripts / mkefi-agl.sh
1 #!/bin/sh
2 #
3 # Copyright (c) 2012, Intel Corporation.
4 # All rights reserved.
5 #
6 # This program is free software;  you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY;  without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See
14 # the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program;  if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 #
20 # Modification from mkefidisk.sh provided by the Yocto project by Dominig
21 # to install Automotive Grade Linux (AGL) on Minnowboard and any PC with UEFI boot
22 #
23 # changes
24 #         - simpler use model
25 #         - keep initrd if present
26 #         - create a grub config with PARTUID to ease boot from various devices automaticaly
27 #         - add a UEFI startup.nsh script for autoboot
28 #         - does not allocate swap
29 #         - accept .hddimg, wic and wic.xz as sources
30
31 LANG=C
32
33 # Set to 1 to enable additional output
34 DEBUG=0
35 exec 3>/dev/null
36
37 #
38 # Defaults
39 #
40 # 100 Mb for the boot partition
41 BOOT_SIZE=100
42 # min available space on TMP_DIR for uncompressing xz image in kB e.g. 5G (5000000)
43 TMP_SIZE_MIN=5000000
44 # TMP_DIR directory use for holding image file for uncompression (e.g. /tmp or $HOME)
45 TMP_DIR=/tmp
46
47 # Cleanup after die()
48 cleanup() {
49         debug "Syncing and unmounting devices"
50         # Unmount anything we mounted
51         unmount $ROOTFS_MNT || error "Failed to unmount $ROOTFS_MNT"
52         unmount $BOOTFS_MNT || error "Failed to unmount $BOOTFS_MNT"
53         unmount $HDDIMG_ROOTFS_MNT || error "Failed to unmount $HDDIMG_ROOTFS_MNT"
54     unmount $HDDIMG_MNT || error "Failed to unmount $HDDIMG_MNT"
55         if [ "$IMG_TYPE" = "DISK" ]; then
56         debug "de-attaching loop devices"
57         for LOOP_DEVICE in `losetup --list |grep $HDDIMG | cut -d" " -f1` ; do
58            losetup -d $LOOP_DEVICE  1>&3 2>&1 || error "Detaching $LOOP_DEVICE from $HDDIMG failled"
59         done   
60      fi
61
62         # Remove the TMPDIR
63         debug "Removing temporary files"
64         if [ -d "$TMPDIR" ]; then
65                 rm -rf "$TMPDIR" || error "Failed to remove $TMPDIR"
66         fi
67         [ -f "$TMP_DIR/TMP-AGL-wic-image.wic" ] || rm -f $TMP_DIR/TMP-AGL-wic-image.wic
68 }
69
70 trap 'die "Signal Received, Aborting..."' HUP INT TERM
71
72 # Logging routines
73 WARNINGS=0
74 ERRORS=0
75 CLEAR="$(tput sgr0)"
76 INFO="$(tput bold)"
77 RED="$(tput setaf 1)$(tput bold)"
78 GREEN="$(tput setaf 2)$(tput bold)"
79 YELLOW="$(tput setaf 3)$(tput bold)"
80 info() {
81         echo "${INFO}$1${CLEAR}"
82 }
83 error() {
84         ERRORS=$((ERRORS+1))
85         echo "${RED}$1${CLEAR}"
86 }
87 warn() {
88         WARNINGS=$((WARNINGS+1))
89         echo "${YELLOW}$1${CLEAR}"
90 }
91 success() {
92         echo "${GREEN}$1${CLEAR}"
93 }
94 die() {
95         error "$1"
96         cleanup
97         exit 1
98 }
99 debug() {
100         if [ $DEBUG -eq 1 ]; then
101                 echo "$1"
102         fi
103 }
104
105 usage() {
106         echo "Install AGL on a removable device to boot on IA UEFI based computer"
107         echo "In particular is can create USB or SD bootable support for Minnowboard"
108         echo ""
109         echo "Usage: $(basename $0) [-v] IDSK_IMAGE REMOVABLE_DEVICE"
110         echo "       -v: Verbose debug"
111         echo "       HDDIMG: The DISK_IMAGE file generated by Yocto the efi disk from"
112         echo "               Supported formats are .hddimg, .wic .wic.xz"
113         echo "       REMOVABLE_DEVICE: The block device to write the image to, e.g. /dev/sdh"
114         echo "ex:"
115         echo "   mkefi-agl.sh   agl-demo-platform-intel-corei7-64.hddimg /dev/sdd"
116         echo "   mkefi-agl.sh   agl-demo-platform-intel-corei7-64.wic.xz /dev/sdd"
117         exit 1
118 }
119
120 image_details() {
121         IMG=$1
122         info "Image details"
123         echo "    image: $(stat --printf '%N\n' $IMG)"
124         echo "     size: $(stat -L --printf '%s bytes\n' $IMG)"
125         echo " modified: $(stat -L --printf '%y\n' $IMG)"
126         echo "     type: $(file -L -b $IMG)"
127         echo ""
128 }
129
130 device_details() {
131         DEV=$1
132         BLOCK_SIZE=512
133
134         info "Device details"
135         echo "  device: $DEVICE"
136         if [ -f "/sys/class/block/$DEV/device/vendor" ]; then
137                 echo "  vendor: $(cat /sys/class/block/$DEV/device/vendor)"
138         else
139                 echo "  vendor: UNKOWN"
140         fi
141         if [ -f "/sys/class/block/$DEV/device/model" ]; then
142                 echo "   model: $(cat /sys/class/block/$DEV/device/model)"
143         else
144                 echo "   model: UNKNOWN"
145         fi
146         if [ -f "/sys/class/block/$DEV/size" ]; then
147                 echo "    size: $(($(cat /sys/class/block/$DEV/size) * $BLOCK_SIZE)) bytes"
148         else
149                 echo "    size: UNKNOWN"
150         fi
151         echo ""
152 }
153
154 unmount_device() {
155         grep -q $DEVICE /proc/mounts
156         if [ $? -eq 0 ]; then
157                 warn "$DEVICE listed in /proc/mounts, attempting to unmount"
158                 umount $DEVICE* 2>/dev/null
159                 ! grep -q $DEVICE /proc/mounts && info "Unmounted successfully"
160                 return $?
161         fi
162         return 0
163 }
164
165 unmount() {
166         if [ "$1" = "" ] ; then
167                 return 0
168         fi
169         grep -q $1 /proc/mounts
170         if [ $? -eq 0 ]; then
171                 debug "Unmounting $1"
172                 umount $1
173                 ! grep -q $1 /proc/mounts # check if unmounted successfully
174                 return $?
175         fi
176         return 0
177 }
178
179 #
180 # Parse and validate arguments
181 #
182 if [ "$1" != "-v" ] && [ $# -ne 2 ]; then
183         usage
184 fi
185 if [ "$1" = "-v" ] && [ $# -ne 3 ]; then
186         usage
187 fi
188
189 if [ "$1" = "-v" ] ; then
190         DEBUG=1
191         exec 3>&1
192         shift
193 fi
194
195 HDDIMG=$1
196 DEVICE=$2
197
198 LINK=$(readlink $DEVICE)
199 if [ $? -eq 0 ]; then
200         DEVICE="$LINK"
201 fi
202
203 if [ ! -w "$DEVICE" ]; then
204         if [ ! -e "${DEVICE}" ] ; then
205                 die "Device $DEVICE cannot be found"
206         else
207                 die "Device $DEVICE is not writable (need to run under sudo?)"
208         fi
209 fi
210
211 if [ ! -e "$HDDIMG" ]; then
212         die "HDDIMG $HDDIMG does not exist"
213 fi
214 HDDIMG_EXT=${HDDIMG##*.}
215 case $HDDIMG_EXT in
216   hddimg)
217      IMG_TYPE="MOUNT"
218      IMG_COMPRESS="NO"
219      debug "Detected: uncompressed image type .hddimg"
220      ;;
221   wic)
222      IMG_TYPE="DISK"
223      IMG_COMPRESS="NO"
224      debug "Detected: uncompressed image type .wic"
225      ;;
226   xz)
227      IMG_TYPE="DISK"
228      IMG_COMPRESS="YES"
229      debug "Detected: xz compressed image type .wic"
230      command -v xz >/dev/null 2>&1 || { die "xz command is not available, pleaes install xz package"; }
231      TMP_SIZE=`df -k $TMP_DIR | awk '/[0-9]%/{print $(NF-2)}'`
232      if [ "$TMP_SIZE" -lt "$TMP_SIZE_MIN" ]; then
233        die "Available space on $TMP_DIR must be at least $TMP_SIZE_MIN kB" 
234      fi
235      printf "Starting decompression of the image. It may take some time ..."
236      xz --decompress --keep --format=auto --force --threads=0 --stdout > $TMP_DIR/TMP-AGL-wic-image.wic  $HDDIMG|| \
237          die "xz command failled: xz --decompress --keep --format=auto --force --threads=0 --stdout > $TMP_DIR/TMP-AGL-wic-image.wic"
238      HDDIMG="$TMP_DIR/TMP-AGL-wic-image.wic"
239      echo "Image uncompressed, starting doing real work ..."
240      ;;
241   *)
242      die "Unsupported image format: $HDDIMG_EXT Supported format are .hddimg .wic wic.xz"
243      ;;
244 esac
245
246 #
247 # Ensure the hddimg is not mounted
248 #
249 debug "will now try to umount /detach previous images"
250 case $IMG_TYPE in
251   MOUNT)
252       unmount "$HDDIMG" || die "Failed to unmount $HDDIMG"
253       ;;
254   DISK)
255       [ `losetup --list |grep $HDDIMG | wc -l ` -gt 1 ] && die "Image mounted more than once, manual cleaning required see: losetup --list"
256       debug "ready to attach the wic image to aloop device"
257       LOOP_DEVICE=`losetup --find --show $HDDIMG`  && ( losetup -d $LOOP_DEVICE  1>&3 2>&1 || die "Detaching $LOOP_DEVICE from $HDDIMG failled")
258       ;;
259   *)
260       die "unknown image format $IMG_TYPE"
261       ;;
262 esac
263
264 #
265 # Check if any $DEVICE partitions are mounted
266 #
267 unmount_device || die "Failed to unmount $DEVICE"
268
269 #
270 # Confirm device with user
271 #
272 image_details $HDDIMG
273 device_details $(basename $DEVICE)
274 echo -n "${INFO}Prepare EFI image on $DEVICE [y/N]?${CLEAR} "
275 read RESPONSE
276 if [ "$RESPONSE" != "y" ]; then
277         die "Image creation aborted"
278 fi
279
280
281 #
282 # Prepare the temporary working space
283 #
284 TMPDIR=$(mktemp -d mkefidisk-XXX) || die "Failed to create temporary mounting directory."
285 HDDIMG_MNT=$TMPDIR/hddimg
286 HDDIMG_ROOTFS_MNT=$TMPDIR/hddimg_rootfs
287 ROOTFS_MNT=$TMPDIR/rootfs
288 BOOTFS_MNT=$TMPDIR/bootfs
289 mkdir $HDDIMG_MNT || die "Failed to create $HDDIMG_MNT"
290 mkdir $HDDIMG_ROOTFS_MNT || die "Failed to create $HDDIMG_ROOTFS_MNT"
291 mkdir $ROOTFS_MNT || die "Failed to create $ROOTFS_MNT"
292 mkdir $BOOTFS_MNT || die "Failed to create $BOOTFS_MNT"
293
294
295 #
296 # Partition $DEVICE
297 #
298 DEVICE_SIZE=$(parted -s $DEVICE unit mb print | grep ^Disk | cut -d" " -f 3 | sed -e "s/MB//")
299 # If the device size is not reported there may not be a valid label
300 if [ "$DEVICE_SIZE" = "" ] ; then
301         parted -s $DEVICE mklabel msdos || die "Failed to create MSDOS partition table"
302         DEVICE_SIZE=$(parted -s $DEVICE unit mb print | grep ^Disk | cut -d" " -f 3 | sed -e "s/MB//")
303 fi
304 ROOTFS_SIZE=$((DEVICE_SIZE-BOOT_SIZE))
305 ROOTFS_START=$((BOOT_SIZE))
306 ROOTFS_END=$((ROOTFS_START+ROOTFS_SIZE))
307
308 # MMC devices use a partition prefix character 'p'
309 PART_PREFIX=""
310 if [ ! "${DEVICE#/dev/mmcblk}" = "${DEVICE}" ] || [ ! "${DEVICE#/dev/loop}" = "${DEVICE}" ]; then
311         PART_PREFIX="p"
312 fi
313 BOOTFS=$DEVICE${PART_PREFIX}1
314 ROOTFS=$DEVICE${PART_PREFIX}2
315
316 TARGET_PART_PREFIX=""
317 if [ ! "${TARGET_DEVICE#/dev/mmcblk}" = "${TARGET_DEVICE}" ]; then
318         TARGET_PART_PREFIX="p"
319 fi
320 TARGET_ROOTFS=$TARGET_DEVICE${TARGET_PART_PREFIX}2
321
322 echo ""
323 info "Boot partition size:   $BOOT_SIZE MB ($BOOTFS)"
324 info "ROOTFS partition size: $ROOTFS_SIZE MB ($ROOTFS)"
325 echo ""
326
327 # Use MSDOS by default as GPT cannot be reliably distributed in disk image form
328 # as it requires the backup table to be on the last block of the device, which
329 # of course varies from device to device.
330
331 info "Partitioning installation media ($DEVICE)"
332
333 debug "Deleting partition table on $DEVICE"
334 dd if=/dev/zero of=$DEVICE bs=512 count=2 1>&3 2>&1 || die "Failed to zero beginning of $DEVICE"
335
336 debug "Creating new partition table (MSDOS) on $DEVICE"
337 parted -s $DEVICE mklabel msdos 1>&3 2>&1 || die "Failed to create MSDOS partition table"
338
339 debug "Creating boot partition on $BOOTFS"
340 parted -s $DEVICE mkpart primary 0% $BOOT_SIZE 1>&3 2>&1 || die "Failed to create BOOT partition"
341
342 debug "Enabling boot flag on $BOOTFS"
343 parted -s $DEVICE set 1 boot on 1>&3 2>&1 || die "Failed to enable boot flag"
344
345 debug "Creating ROOTFS partition on $ROOTFS"
346 parted -s $DEVICE mkpart primary $ROOTFS_START $ROOTFS_END 1>&3 2>&1 || die "Failed to create ROOTFS partition"
347
348 # as blkid does not provide PARTUUID on Ubuntu LTS 14.04 we myst hack via fdisk
349 #ROOTFS_PARTUUID=$(blkid |grep -e "$ROOTFS" |sed -n 's/^.*PARTUUID=/PARTUUID=/p')
350 export LC_ALL=C
351 ROOTFS_DISKID=$(fdisk -l "$DEVICE" | grep -e "Disk identifier" | sed -n 's/^.*Disk identifier: 0x/PARTUUID=/p')
352 if [ $ROOTFS_DISKID = "" ]; then
353     die "Failed to read DISKID"
354 fi
355 ROOTFS_PARTUUID="$ROOTFS_DISKID-02"
356 debug "PARTUUID for ROOTFS is $ROOTFS_PARTUUID"
357
358 if [ $DEBUG -eq 1 ]; then
359         parted -s $DEVICE print
360 fi
361
362
363 #
364 # Check if any $DEVICE partitions are mounted after partitioning
365 #
366 unmount_device || die "Failed to unmount $DEVICE partitions"
367
368
369 #
370 # Format $DEVICE partitions
371 #
372 info "Formatting partitions"
373 debug "Formatting $BOOTFS as vfat"
374 if [ ! "${DEVICE#/dev/loop}" = "${DEVICE}" ]; then
375         mkfs.vfat -I $BOOTFS -n "EFI" 1>&3 2>&1 || die "Failed to format $BOOTFS"
376 else
377         mkfs.vfat $BOOTFS -n "EFI" 1>&3 2>&1 || die "Failed to format $BOOTFS"
378 fi
379
380 debug "Formatting $ROOTFS as ext4"
381 mkfs.ext4 -F $ROOTFS -L "ROOT" 1>&3 2>&1 || die "Failed to format $ROOTFS"
382
383
384 #
385 # Mounting image file system on loop devices
386 #
387 case $IMG_TYPE in
388
389   MOUNT) 
390      debug "Mounting images and device in preparation for installation"
391      mount -o loop $HDDIMG $HDDIMG_MNT 1>&3 2>&1 || die "Failed to mount $HDDIMG"
392      mount -o loop $HDDIMG_MNT/rootfs.img $HDDIMG_ROOTFS_MNT 1>&3 2>&1 || die "Failed to mount rootfs.img"
393      ;;
394   DISK)
395      debug "Attaching image and mounting partitions then device in preparation for installation"
396      LOOP_DEVICE=`losetup --find` || die "Failled to find an available loop device see: losetup --find"
397      losetup -P $LOOP_DEVICE $HDDIMG  1>&3 2>&1 || die "Attaching $LOOP_DEVICE from $HDDIMG failled"
398      mount "$LOOP_DEVICE"p2  $HDDIMG_ROOTFS_MNT 1>&3 2>&1 || die "Failed to mount $LOOP_DEVICEp1 on $HDDIMG_ROOTFS_MNT"
399      mount "$LOOP_DEVICE"p1  $HDDIMG_MNT       1>&3 2>&1 || die "Failed to mount $LOOP_DEVICEp2 on $HDDIMG_MNT"
400      ;;
401   *)
402       die "unknown image format $IMG_TYPE"
403       ;;
404 esac
405 # Mount removable device
406      mount $ROOTFS $ROOTFS_MNT 1>&3 2>&1 || die "Failed to mount $ROOTFS on $ROOTFS_MNT"
407      mount $BOOTFS $BOOTFS_MNT 1>&3 2>&1 || die "Failed to mount $BOOTFS on $BOOTFS_MNT"
408
409
410 info "Preparing boot partition"
411 EFIDIR="$BOOTFS_MNT/EFI/BOOT"
412 if [ -f $HDDIMG_MNT/vmlinuz ]; then
413    cp $HDDIMG_MNT/vmlinuz $BOOTFS_MNT 1>&3 2>&1 || die "Failed to copy vmlinuz"
414    KERNEL_TYPE="VMLINUZ"
415    debug "kernel is vmlinuz"
416 fi
417 if [ -f $HDDIMG_MNT/bzimage ]; then
418    cp $HDDIMG_MNT/bzimage $BOOTFS_MNT 1>&3 2>&1 || die "Failed to copy vmlinuz"
419    KERNEL_TYPE="BZIMAGE"
420    debug "kernel is bzimage"
421 fi
422 [ -z $KERNEL_TYPE ] && die "Linux kernel type in $HDDIMG is unsupported"
423
424 if [ -f $HDDIMG_MNT/initrd ]
425   then
426     echo "initrd detected"
427     cp $HDDIMG_MNT/initrd $BOOTFS_MNT 1>&3 2>&1 || die "Failed to copy initrd"
428   else
429     warn "initrd missing"
430 fi
431 echo "bootx64.efi" > $BOOTFS_MNT/startup.nsh || die "Failed to create startup.nsh"
432 # Copy the efi loader and configs (booti*.efi and grub.cfg if it exists)
433 cp -r $HDDIMG_MNT/EFI $BOOTFS_MNT 1>&3 2>&1 || die "Failed to copy EFI dir"
434 # Silently ignore a missing systemd-boot or gummiboot loader dir (we might just be a GRUB image)
435 cp -r $HDDIMG_MNT/loader $BOOTFS_MNT 1>&3 2>&1
436
437 # Update the boot loaders configurations for an installed image
438 # Remove any existing root= kernel parameters and:
439 # o Add a root= parameter with the target rootfs
440 # o Specify ro so fsck can be run during boot
441 # o Specify rootwait in case the target media is an asyncronous block device
442 #   such as MMC or USB disks
443 # o Specify "quiet" to minimize boot time when using slow serial consoles
444
445 # Look for a GRUB installation
446 GRUB_CFG="$EFIDIR/grub.cfg"
447 if [ -e "$GRUB_CFG" ]; then
448         info "Configuring GRUB"
449         # Delete the install entry
450         sed -i "/menuentry 'install'/,/^}/d" $GRUB_CFG
451         # Delete any LABEL= strings
452         sed -i "s/ LABEL=[^ ]*/ /" $GRUB_CFG
453
454         sed -i "s@ root=[^ ]*@ @" $GRUB_CFG
455         sed -i "s@vmlinuz @vmlinuz root=$ROOTFS_PARTUUID @" $GRUB_CFG
456 fi
457
458 # look for a systemd-boot loader.conf file and create a default boot entry
459 SYSTEMDBOOT_CFG="$BOOTFS_MNT/loader/loader.conf"
460 if [ -e "$SYSTEMDBOOT_CFG" ]; then
461         info "Configuring SYSTEMD-BOOT"
462     SYSTEMDBOOT_BOOT="$BOOTFS_MNT/loader/entries/boot.conf"
463     SYSTEMDBOOT_DEBUG="$BOOTFS_MNT/loader/entries/debug.conf"
464     # Delete the install entry
465         sed -i "/menuentry 'install'/,/^}/d" $SYSTEMDBOOT_CFG
466         rm -rf "$BOOTFS_MNT/loader/entries/install.conf" 1>&3 2>&1
467         # Add PARTUUID to the boot entry file
468         if [ ! -e "$SYSTEMDBOOT_BOOT" ]; then
469         die "no boot.conf entry found in systemd-boot directories"
470     fi
471         # Delete any LABEL= strings
472         sed -i "s/ LABEL=[^ ]*/ /" $SYSTEMDBOOT_BOOT
473
474         sed -i "s@ root=[^ ]*@ @" $SYSTEMDBOOT_BOOT
475         sed -i "s@options @options root=$ROOTFS_PARTUUID @" $SYSTEMDBOOT_BOOT
476 fi
477
478
479 # Ensure we have at least one EFI bootloader configured
480 if [ ! -e $GRUB_CFG ]  && [ ! -e $SYSTEMDBOOT_CFG ] ; then
481         die "No EFI bootloader configuration found"
482 fi
483
484 printf "Copying ROOTFS files ... "
485 command -v rsync >/dev/null 2>&1 # check if rsync exists
486 if [ $DEBUG -eq 1 ] && [ $? -eq 0 ]; then
487         rsync --info=progress2 -h -aHAXW --no-compress  $HDDIMG_ROOTFS_MNT/* $ROOTFS_MNT 1>&3 2>&1 || die "Root FS copy failed"
488 else
489         cp -a $HDDIMG_ROOTFS_MNT/* $ROOTFS_MNT 1>&3 2>&1 || die "Root FS copy failed"
490 fi
491
492 printf "flushing data on removable device. May take a while ... "
493 sync --file-system $ROOTFS_MNT
494 echo done
495
496 # We dont want udev to mount our root device while we're booting...
497 if [ -d $ROOTFS_MNT/etc/udev/ ] ; then
498         echo "$TARGET_DEVICE" >> $ROOTFS_MNT/etc/udev/mount.blacklist
499 fi
500
501
502 # Call cleanup to unmount devices and images and remove the TMPDIR
503 cleanup
504
505 echo ""
506 if [ $WARNINGS -ne 0 ] && [ $ERRORS -eq 0 ]; then
507         echo "${YELLOW}Installation completed with warnings${CLEAR}"
508         echo "${YELLOW}Warnings: $WARNINGS${CLEAR}"
509 elif [ $ERRORS -ne 0 ]; then
510         echo "${RED}Installation encountered errors${CLEAR}"
511         echo "${RED}Errors: $ERRORS${CLEAR}"
512         echo "${YELLOW}Warnings: $WARNINGS${CLEAR}"
513 else
514         success "Installation completed successfully"
515 fi
516 echo ""