summaryrefslogtreecommitdiffstats
path: root/scripts/mkabl-agl.sh
blob: 611c08fbc957ecf87446f792e87816646311114f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
#!/bin/sh
#
# Copyright (c) 2012, Intel Corporation.
# All rights reserved.
#
# This program is free software;  you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY;  without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See
# the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program;  if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
#
# Modification from mkefidisk.sh provided by the Yocto project by Dominig
# to install Automotive Grade Linux (AGL) on 
# Intel platforms equipped with the Automotive Linux Boot (ABL)
#
# Dependencies:
# Relies on the Intel iasImage tool to pakage the Kernel and the initrd in ABL format
#
# changes
#         - simpler use model
#         - keep initrd if present
#         - does not allocate swap
#         - accept .hddimg, wic and wic.xz as sources
#

LANG=C

# Set to 1 to enable additional output
DEBUG=0
exec 3>/dev/null

#
# Defaults
#
# 100 Mb for the boot partition
BOOT_SIZE=100
# min available space on TMP_DIR for uncompressing xz image in kB e.g. 5G (5000000)
TMP_SIZE_MIN=5000000
# TMP_DIR directory use for holding image file for uncompression (e.g. /tmp or $HOME)
TMP_DIR=/tmp
#
MRB_DEBUG_TTY="ttyS2,115200n8"
MRB_HDMI="HDMI-A-1:e"
#
IAS_PATH=""
IAS_EXE="ias_image_app"
IAS_CMD_LINE=/tmp/iasCommandLine.cmd

# Cleanup after die()
cleanup() {
	debug "Syncing and unmounting devices"
	# Unmount anything we mounted
	unmount $ROOTFS_MNT || error "Failed to unmount $ROOTFS_MNT"
	unmount $BOOTFS_MNT || error "Failed to unmount $BOOTFS_MNT"
	unmount $HDDIMG_ROOTFS_MNT || error "Failed to unmount $HDDIMG_ROOTFS_MNT"
	unmount $HDDIMG_MNT || error "Failed to unmount $HDDIMG_MNT"
	if [ "$IMG_TYPE" = "DISK" ]; then
        debug "de-attaching loop devices"
        for LOOP_DEVICE in `losetup --list |grep $HDDIMG | cut -d" " -f1` ; do
           losetup -d $LOOP_DEVICE  1>&3 2>&1 || error "Detaching $LOOP_DEVICE from $HDDIMG failled"
        done   
     fi
	# Remove the TMPDIR
	debug "Removing temporary files"
	if [ -d "$TMPDIR" ]; then
		rm -rf $TMPDIR || error "Failed to remove $TMPDIR"
	fi
    [ -f "$TMP_DIR/TMP-AGL-wic-image.wic" ] || rm -f $TMP_DIR/TMP-AGL-wic-image.wic
}

trap 'die "Signal Received, Aborting..."' HUP INT TERM

# Logging routines
WARNINGS=0
ERRORS=0
CLEAR="$(tput sgr0)"
INFO="$(tput bold)"
RED="$(tput setaf 1)$(tput bold)"
GREEN="$(tput setaf 2)$(tput bold)"
YELLOW="$(tput setaf 3)$(tput bold)"
info() {
	echo "${INFO}$1${CLEAR}"
}
error() {
	ERRORS=$((ERRORS+1))
	echo "${RED}$1${CLEAR}"
}
warn() {
	WARNINGS=$((WARNINGS+1))
	echo "${YELLOW}$1${CLEAR}"
}
success() {
	echo "${GREEN}$1${CLEAR}"
}
die() {
	error "$1"
	cleanup
	exit 1
}
debug() {
	if [ $DEBUG -eq 1 ]; then
		echo "$1"
	fi
}

usage() {
	echo "Install AGL on a removable device to boot ABL based computer"
        echo "ABL on the target must accept non signed development Linux kernel"
	echo "In particular is can create USB or SD bootable support for Intel MRB"
	echo ""
	echo "Usage: $(basename $0) [-v] [-p path_to_iasImage_tool] HDDIMG REMOVABLE_DEVICE"
	echo "       -v: Verbose debug"
        echo "       path_to_iasImage_tool: path the iasImage tool provided by Intel."
	echo "       HDDIMG: The hddimg file to generate the efi disk from"
    echo "               Supported formats are .hddimg, .wic .wic.xz"
	echo "       REMOVABLE_DEVICE: The block device to write the image to, e.g. /dev/sdh"
	echo "ex:"
	echo "   mkabl-agl.sh   agl-demo-platform-intel-corei7-64.wic.xz /dev/sdd"
    echo "   mkabl-agl.sh   agl-demo-platform-intel-corei7-64.hddimg /dev/sdd"

        echo "                  assuming that iasImage is accessible via your default path"
	exit 1
}

image_details() {
	IMG=$1
	info "Image details"
	echo "    image: $(stat --printf '%N\n' $IMG)"
	echo "     size: $(stat -L --printf '%s bytes\n' $IMG)"
	echo " modified: $(stat -L --printf '%y\n' $IMG)"
	echo "     type: $(file -L -b $IMG)"
	echo ""
}

device_details() {
	DEV=$1
	BLOCK_SIZE=512

	info "Device details"
	echo "  device: $DEVICE"
	if [ -f "/sys/class/block/$DEV/device/vendor" ]; then
		echo "  vendor: $(cat /sys/class/block/$DEV/device/vendor)"
	else
		echo "  vendor: UNKOWN"
	fi
	if [ -f "/sys/class/block/$DEV/device/model" ]; then
		echo "   model: $(cat /sys/class/block/$DEV/device/model)"
	else
		echo "   model: UNKNOWN"
	fi
	if [ -f "/sys/class/block/$DEV/size" ]; then
		echo "    size: $(($(cat /sys/class/block/$DEV/size) * $BLOCK_SIZE)) bytes"
	else
		echo "    size: UNKNOWN"
	fi
	echo ""
}

unmount_device() {
	grep -q $DEVICE /proc/mounts
	if [ $? -eq 0 ]; then
		warn "$DEVICE listed in /proc/mounts, attempting to unmount"
		umount $DEVICE* 2>/dev/null
		! grep -q $DEVICE /proc/mounts && info "Unmounted successfully"
		return $?
	fi
	return 0
}

unmount() {
	if [ "$1" = "" ] ; then
		return 0
	fi
	grep -q $1 /proc/mounts
	if [ $? -eq 0 ]; then
		debug "Unmounting $1"
		umount $1
		! grep -q $1 /proc/mounts # check if unmounted successfully
		return $?
	fi
	return 0
}

#
# Parse and validate arguments
#

if [ "$1" = "-v" ] ; then
	DEBUG=1
	exec 3>&1
	shift
fi

if [ "$1" = "-p" ] ; then
        IAS_PATH="$2""/"
        shift 2
fi

if  [ $# -ne 2 ]; then
        usage
fi

IAS_IMAGE_TOOL="$IAS_PATH$IAS_EXE"
debug "iasImage tool is: $IAS_IMAGE_TOOL"
which $IAS_IMAGE_TOOL > IAS_IMAGE_TOOL_PATH
if  [ ! -x "$(command -v $IAS_IMAGE_TOOL)" ]; then
   die "$IAS_IMAGE_TOOL not found pointed by the path via 'sudo; use -p option'"
fi

HDDIMG=$1
DEVICE=$2

LINK=$(readlink $DEVICE)
if [ $? -eq 0 ]; then
	DEVICE="$LINK"
fi

if [ ! -w "$DEVICE" ]; then
	if [ ! -e "${DEVICE}" ] ; then
		die "Device $DEVICE cannot be found"
	else
		die "Device $DEVICE is not writable (need to run under sudo?)"
	fi
fi

if [ ! -e "$HDDIMG" ]; then
	die "HDDIMG $HDDIMG does not exist"
fi
HDDIMG_EXT=${HDDIMG##*.}
case $HDDIMG_EXT in
  hddimg)
     IMG_TYPE="MOUNT"
     IMG_COMPRESS="NO"
     debug "Detected: uncompressed image type .hddimg"
     ;;
  wic)
     IMG_TYPE="DISK"
     IMG_COMPRESS="NO"
     debug "Detected: uncompressed image type .wic"
     ;;
  xz)
     IMG_TYPE="DISK"
     IMG_COMPRESS="YES"
     debug "Detected: xz compressed image type .wic"
     command -v xz >/dev/null 2>&1 || { die "xz command is not available, pleaes install xz package"; }
     TMP_SIZE=`df -k $TMP_DIR | awk '/[0-9]%/{print $(NF-2)}'`
     if [ "$TMP_SIZE" -lt "$TMP_SIZE_MIN" ]; then
       die "Available space on $TMP_DIR must be at least $TMP_SIZE_MIN kB" 
     fi
     printf "Starting decompression of the image. It may take some time ..."
     xz --decompress --keep --format=auto --force --threads=0 --stdout > $TMP_DIR/TMP-AGL-wic-image.wic  $HDDIMG|| \
         die "xz command failled: xz --decompress --keep --format=auto --force --threads=0 --stdout > $TMP_DIR/TMP-AGL-wic-image.wic"
     HDDIMG="$TMP_DIR/TMP-AGL-wic-image.wic"
     echo "Image uncompressed, starting doing real work ..."
     ;;
  *)
     die "Unsupported image format: $HDDIMG_EXT Supported format are .hddimg .wic wic.xz"
     ;;
esac
#
# Ensure the hddimg is not mounted
#
debug "will now try to umount /detach previous images"
case $IMG_TYPE in
  MOUNT)
      unmount "$HDDIMG" || die "Failed to unmount $HDDIMG"
      ;;
  DISK)
      [ `losetup --list |grep $HDDIMG | wc -l ` -gt 1 ] && die "Image mounted more than once, manual cleaning required see: losetup --list"
      debug "ready to attach the wic image to aloop device"
      LOOP_DEVICE=`losetup --find --show $HDDIMG`  && ( losetup -d $LOOP_DEVICE  1>&3 2>&1 || die "Detaching $LOOP_DEVICE from $HDDIMG failled")
      ;;
  *)
      die "unknown image format $IMG_TYPE"
      ;;
esac
#
# Check if any $DEVICE partitions are mounted
#
unmount_device || die "Failed to unmount $DEVICE"

#
# Confirm device with user
#
image_details $HDDIMG
device_details $(basename $DEVICE)
echo -n "${INFO}Prepare ABL image on $DEVICE [y/N]?${CLEAR} "
read RESPONSE
if [ "$RESPONSE" != "y" ]; then
	echo "Image creation aborted"
	exit 0
fi


#
# Prepare the temporary working space
#
TMPDIR=$(mktemp -d mkabldisk-XXX) || die "Failed to create temporary mounting directory."
HDDIMG_MNT=$TMPDIR/hddimg
debug "TEMPDIR is: $TMPDIR"
HDDIMG_ROOTFS_MNT=$TMPDIR/hddimg_rootfs
ROOTFS_MNT=$TMPDIR/rootfs
BOOTFS_MNT=$TMPDIR/bootfs
mkdir $HDDIMG_MNT || die "Failed to create $HDDIMG_MNT"
mkdir $HDDIMG_ROOTFS_MNT || die "Failed to create $HDDIMG_ROOTFS_MNT"
mkdir $ROOTFS_MNT || die "Failed to create $ROOTFS_MNT"
mkdir $BOOTFS_MNT || die "Failed to create $BOOTFS_MNT"


#
# Partition $DEVICE
#
DEVICE_SIZE=$(parted -s $DEVICE unit mb print | grep ^Disk | cut -d" " -f 3 | sed -e "s/MB//")
# If the device size is not reported there may not be a valid label
if [ "$DEVICE_SIZE" = "" ] ; then
	parted -s $DEVICE mklabel msdos || die "Failed to create MSDOS partition table"
	DEVICE_SIZE=$(parted -s $DEVICE unit mb print | grep ^Disk | cut -d" " -f 3 | sed -e "s/MB//")
fi
ROOTFS_SIZE=$((DEVICE_SIZE-BOOT_SIZE))
ROOTFS_START=$((BOOT_SIZE))
ROOTFS_END=$((ROOTFS_START+ROOTFS_SIZE))

# MMC devices use a partition prefix character 'p'
PART_PREFIX=""
if [ ! "${DEVICE#/dev/mmcblk}" = "${DEVICE}" ] || [ ! "${DEVICE#/dev/loop}" = "${DEVICE}" ]; then
	PART_PREFIX="p"
fi
BOOTFS=$DEVICE${PART_PREFIX}1
ROOTFS=$DEVICE${PART_PREFIX}2

TARGET_PART_PREFIX=""
if [ ! "${TARGET_DEVICE#/dev/mmcblk}" = "${TARGET_DEVICE}" ]; then
	TARGET_PART_PREFIX="p"
fi
TARGET_ROOTFS=$TARGET_DEVICE${TARGET_PART_PREFIX}2

echo ""
info "Boot partition size:   $BOOT_SIZE MB ($BOOTFS)"
info "ROOTFS partition size: $ROOTFS_SIZE MB ($ROOTFS)"
echo ""

# Use MSDOS by default as GPT cannot be reliably distributed in disk image form
# as it requires the backup table to be on the last block of the device, which
# of course varies from device to device.

info "Partitioning installation media ($DEVICE)"

debug "Deleting partition table on $DEVICE"
dd if=/dev/zero of=$DEVICE bs=512 count=2 1>&3 2>&1 || die "Failed to zero beginning of $DEVICE"

debug "Creating new partition table (MSDOS) on $DEVICE"
parted -s $DEVICE mklabel msdos 1>&3 2>&1 || die "Failed to create MSDOS partition table"

debug "Creating boot partition on $BOOTFS"
parted -s $DEVICE mkpart primary 0% $BOOT_SIZE 1>&3 2>&1 || die "Failed to create BOOT partition"

debug "Enabling boot flag on $BOOTFS"
parted -s $DEVICE set 1 boot on 1>&3 2>&1 || die "Failed to enable boot flag"

debug "Creating ROOTFS partition on $ROOTFS"
parted -s $DEVICE mkpart primary $ROOTFS_START $ROOTFS_END 1>&3 2>&1 || die "Failed to create ROOTFS partition"

# as blkid does not provide PARTUUID on Ubuntu LTS 14.04 we myst hack via fdisk
#ROOTFS_PARTUUID=$(blkid |grep -e "$ROOTFS" |sed -n 's/^.*PARTUUID=/PARTUUID=/p')
export LC_ALL=C
ROOTFS_DISKID=$(fdisk -l "$DEVICE" | grep -e "Disk identifier" | sed -n 's/^.*Disk identifier: 0x/PARTUUID=/p')
if [ $ROOTFS_DISKID = "" ]; then
    die "Failed to read DISKID"
fi
BOOTFS_PARTUUID="$ROOTFS_DISKID-01"
ROOTFS_PARTUUID="$ROOTFS_DISKID-02"
debug "PARTUUID for ROOTFS is $ROOTFS_PARTUUID"

if [ $DEBUG -eq 1 ]; then
	parted -s $DEVICE print
fi


#
# Check if any $DEVICE partitions are mounted after partitioning
#
unmount_device || die "Failed to unmount $DEVICE partitions"


#
# Format $DEVICE partitions
#
info "Formatting partitions"
debug "Formatting $BOOTFS as ext2"
mkfs.ext2 -F -F -L BOOT $BOOTFS  1>&3 2>&1 || die "Failed to format $BOOTFS"

debug "Formatting $ROOTFS as ext4"
mkfs.ext4 -F $ROOTFS -L "ROOT" 1>&3 2>&1 || die "Failed to format $ROOTFS"


# Mounting image file system on loop devices
#
case $IMG_TYPE in

  MOUNT) 
     debug "Mounting images and device in preparation for installation"
     mount -o loop $HDDIMG $HDDIMG_MNT 1>&3 2>&1 || die "Failed to mount $HDDIMG"
     mount -o loop $HDDIMG_MNT/rootfs.img $HDDIMG_ROOTFS_MNT 1>&3 2>&1 || die "Failed to mount rootfs.img"
     ;;
  DISK)
     debug "Attaching image and mounting partitions then device in preparation for installation"
     LOOP_DEVICE=`losetup --find` || die "Failled to find an available loop device see: losetup --find"
     losetup -P $LOOP_DEVICE $HDDIMG  1>&3 2>&1 || die "Attaching $LOOP_DEVICE from $HDDIMG failled"
     mount "$LOOP_DEVICE"p2  $HDDIMG_ROOTFS_MNT 1>&3 2>&1 || die "Failed to mount $LOOP_DEVICEp1 on $HDDIMG_ROOTFS_MNT"
     mount "$LOOP_DEVICE"p1  $HDDIMG_MNT       1>&3 2>&1 || die "Failed to mount $LOOP_DEVICEp2 on $HDDIMG_MNT"
     ;;
  *)
      die "unknown image format $IMG_TYPE"
      ;;
esac

mount $ROOTFS $ROOTFS_MNT 1>&3 2>&1 || die "Failed to mount $ROOTFS on $ROOTFS_MNT"
mount $BOOTFS $BOOTFS_MNT 1>&3 2>&1 || die "Failed to mount $BOOTFS on $BOOTFS_MNT"

info "Preparing boot partition"
# create the config file for iasImage
# Remove any existing root= kernel parameters and:
# o Add a root= parameter with the target rootfs
# o Specify ro so fsck can be run during boot
# o Specify rootwait in case the target media is an asyncronous block device
#   such as MMC or USB disks
# o Specify "quiet" to minimize boot time when using slow serial consoles

# iasImage command line file creation
echo "root=$ROOTFS_PARTUUID"   > $IAS_CMD_LINE
echo "console=$MRB_DEBUG_TTY" >> $IAS_CMD_LINE
echo "earlycon=uart8250,mmio32,0xfc000000,115200n8" >> $IAS_CMD_LINE
echo "rootwait" >> $IAS_CMD_LINE
echo "video=$MRB_HDMI" >> $IAS_CMD_LINE
echo "i915.enable_initial_modeset=1" >> $IAS_CMD_LINE
debug "temp config for iasImage is $IAS_CMD_LINE"

if [ -f $HDDIMG_MNT/vmlinuz ]; then
   KERNEL_TYPE="vmlinuz"
   debug "kernel is vmlinuz"
fi
if [ -f $HDDIMG_MNT/bzimage ]; then
   KERNEL_TYPE="bzimage"
   debug "kernel is bzimage -> vmlinuz"
fi
if [ -f $HDDIMG_MNT/microcode.cpio ]; then
     warn "initrd=microcode.cpio is not a supported configuration, microcode.cpio has been ignored"
fi
[ -z $KERNEL_TYPE ] && die "Linux kernel type in $HDDIMG is unsupported"

if [ -f $HDDIMG_MNT/initrd ]; 
  then
     info "creating ABL image with initramsfs"
     debug "$IAS_IMAGE_TOOL -o  $BOOTFS_MNT/iasImage -i 0x30000 $IAS_CMD_LINE $HDDIMG_MNT/$KERNEL_TYPE $HDDIMG_MNT/initrd"
     $IAS_IMAGE_TOOL -o  $BOOTFS_MNT/iasImage -i 0x30000 $IAS_CMD_LINE $HDDIMG_MNT/$KERNEL_TYPE $HDDIMG_MNT/initrd
  else
     info "creating ABL image without initramfs"
     debug "$IAS_IMAGE_TOOL -o  $BOOTFS_MNT/iasImage -i 0x30000 $IAS_CMD_LINE $HDDIMG_MNT/$KERNEL_TYPE"
     $IAS_IMAGE_TOOL -o  $BOOTFS_MNT/iasImage -i 0x30000 $IAS_CMD_LINE $HDDIMG_MNT/$KERNEL_TYPE
fi     

printf "Copying ROOTFS files ... "
command -v rsync >/dev/null 2>&1 # check if rsync exists
if [ $DEBUG -eq 1 ] && [ $? -eq 0 ]; then
	rsync --info=progress2 -h -aHAXW --no-compress  $HDDIMG_ROOTFS_MNT/* $ROOTFS_MNT 1>&3 2>&1 || die "Root FS copy failed"
else
	cp -a $HDDIMG_ROOTFS_MNT/* $ROOTFS_MNT 1>&3 2>&1 || die "Root FS copy failed"
fi

debug "removing any swap entry in /etc/fstab"
sed --in-place '/swap/d' $ROOTFS_MNT/etc/fstab 
debug "fixing PARTUUID for /boot"
sed --in-place -e "s#PARTUUID=[0-9a-z-]\+\t/boot#${BOOTFS_PARTUUID}\t/boot#" $ROOTFS_MNT/etc/fstab

printf "flushing data on removable device. May take a while ... "
sync --file-system $ROOTFS_MNT
echo done

# We dont want udev to mount our root device while we're booting...
if [ -d $ROOTFS_MNT/etc/udev/ ] ; then
	echo "$TARGET_DEVICE" >> $ROOTFS_MNT/etc/udev/mount.blacklist
fi


# Call cleanup to unmount devices and images and remove the TMPDIR
cleanup

echo ""
if [ $WARNINGS -ne 0 ] && [ $ERRORS -eq 0 ]; then
	echo "${YELLOW}Installation completed with warnings${CLEAR}"
	echo "${YELLOW}Warnings: $WARNINGS${CLEAR}"
elif [ $ERRORS -ne 0 ]; then
	echo "${RED}Installation encountered errors${CLEAR}"
	echo "${RED}Errors: $ERRORS${CLEAR}"
	echo "${YELLOW}Warnings: $WARNINGS${CLEAR}"
else
	success "Installation completed successfully"
fi
echo ""
pan class="n">type, is_tx ? 1 : 0, sync_mfe); dim2_configure_adt(ch_addr); dim2_configure_cat(AHB_CAT, ch_addr, type, is_tx ? 0 : 1, sync_mfe); /* unmask interrupt for used channel, enable mlb_sys_int[0] interrupt */ dimcb_io_write(&g.dim2->ACMR0, dimcb_io_read(&g.dim2->ACMR0) | bit_mask(ch_addr)); } static void dim2_clear_channel(u8 ch_addr) { /* mask interrupt for used channel, disable mlb_sys_int[0] interrupt */ dimcb_io_write(&g.dim2->ACMR0, dimcb_io_read(&g.dim2->ACMR0) & ~bit_mask(ch_addr)); dim2_clear_cat(AHB_CAT, ch_addr); dim2_clear_adt(ch_addr); dim2_clear_cat(MLB_CAT, ch_addr); dim2_clear_cdt(ch_addr); /* clear channel status bit */ dimcb_io_write(&g.dim2->ACSR0, bit_mask(ch_addr)); } /* -------------------------------------------------------------------------- */ /* channel state helpers */ static void state_init(struct int_ch_state *state) { state->request_counter = 0; state->service_counter = 0; state->idx1 = 0; state->idx2 = 0; state->level = 0; } /* -------------------------------------------------------------------------- */ /* macro helper functions */ static inline bool check_channel_address(u32 ch_address) { return ch_address > 0 && (ch_address % 2) == 0 && (ch_address / 2) <= (u32)CAT_CL_MASK; } static inline bool check_packet_length(u32 packet_length) { u16 const max_size = ((u16)CDT3_BD_ISOC_MASK + 1u) / ISOC_DBR_FACTOR; if (packet_length <= 0) return false; /* too small */ if (packet_length > max_size) return false; /* too big */ if (packet_length - 1u > (u32)CDT1_BS_ISOC_MASK) return false; /* too big */ return true; } static inline bool check_bytes_per_frame(u32 bytes_per_frame) { u16 const bd_factor = g.fcnt + 2; u16 const max_size = ((u16)CDT3_BD_MASK + 1u) >> bd_factor; if (bytes_per_frame <= 0) return false; /* too small */ if (bytes_per_frame > max_size) return false; /* too big */ return true; } static inline u16 norm_ctrl_async_buffer_size(u16 buf_size) { u16 const max_size = (u16)ADT1_CTRL_ASYNC_BD_MASK + 1u; if (buf_size > max_size) return max_size; return buf_size; } static inline u16 norm_isoc_buffer_size(u16 buf_size, u16 packet_length) { u16 n; u16 const max_size = (u16)ADT1_ISOC_SYNC_BD_MASK + 1u; if (buf_size > max_size) buf_size = max_size; n = buf_size / packet_length; if (n < 2u) return 0; /* too small buffer for given packet_length */ return packet_length * n; } static inline u16 norm_sync_buffer_size(u16 buf_size, u16 bytes_per_frame) { u16 n; u16 const max_size = (u16)ADT1_ISOC_SYNC_BD_MASK + 1u; u32 const unit = bytes_per_frame << g.fcnt; if (buf_size > max_size) buf_size = max_size; n = buf_size / unit; if (n < 1u) return 0; /* too small buffer for given bytes_per_frame */ return unit * n; } static void dim2_cleanup(void) { /* disable MediaLB */ dimcb_io_write(&g.dim2->MLBC0, false << MLBC0_MLBEN_BIT); dim2_clear_ctram(); /* disable mlb_int interrupt */ dimcb_io_write(&g.dim2->MIEN, 0); /* clear status for all dma channels */ dimcb_io_write(&g.dim2->ACSR0, 0xFFFFFFFF); dimcb_io_write(&g.dim2->ACSR1, 0xFFFFFFFF); /* mask interrupts for all channels */ dimcb_io_write(&g.dim2->ACMR0, 0); dimcb_io_write(&g.dim2->ACMR1, 0); } static void dim2_initialize(bool enable_6pin, u8 mlb_clock) { dim2_cleanup(); /* configure and enable MediaLB */ dimcb_io_write(&g.dim2->MLBC0, enable_6pin << MLBC0_MLBPEN_BIT | mlb_clock << MLBC0_MLBCLK_SHIFT | g.fcnt << MLBC0_FCNT_SHIFT | true << MLBC0_MLBEN_BIT); /* activate all HBI channels */ dimcb_io_write(&g.dim2->HCMR0, 0xFFFFFFFF); dimcb_io_write(&g.dim2->HCMR1, 0xFFFFFFFF); /* enable HBI */ dimcb_io_write(&g.dim2->HCTL, bit_mask(HCTL_EN_BIT)); /* configure DMA */ dimcb_io_write(&g.dim2->ACTL, ACTL_DMA_MODE_VAL_DMA_MODE_1 << ACTL_DMA_MODE_BIT | true << ACTL_SCE_BIT); } static bool dim2_is_mlb_locked(void) { u32 const mask0 = bit_mask(MLBC0_MLBLK_BIT); u32 const mask1 = bit_mask(MLBC1_CLKMERR_BIT) | bit_mask(MLBC1_LOCKERR_BIT); u32 const c1 = dimcb_io_read(&g.dim2->MLBC1); u32 const nda_mask = (u32)MLBC1_NDA_MASK << MLBC1_NDA_SHIFT; dimcb_io_write(&g.dim2->MLBC1, c1 & nda_mask); return (dimcb_io_read(&g.dim2->MLBC1) & mask1) == 0 && (dimcb_io_read(&g.dim2->MLBC0) & mask0) != 0; } /* -------------------------------------------------------------------------- */ /* channel help routines */ static inline bool service_channel(u8 ch_addr, u8 idx) { u8 const shift = idx * 16; u32 const adt1 = dim2_read_ctr(ADT + ch_addr, 1); if (((adt1 >> (ADT1_DNE_BIT + shift)) & 1) == 0) return false; { u32 mask[4] = { 0, 0, 0, 0 }; u32 adt_w[4] = { 0, 0, 0, 0 }; mask[1] = bit_mask(ADT1_DNE_BIT + shift) | bit_mask(ADT1_ERR_BIT + shift) | bit_mask(ADT1_RDY_BIT + shift); dim2_write_ctr_mask(ADT + ch_addr, mask, adt_w); } /* clear channel status bit */ dimcb_io_write(&g.dim2->ACSR0, bit_mask(ch_addr)); return true; } /* -------------------------------------------------------------------------- */ /* channel init routines */ static void isoc_init(struct dim_channel *ch, u8 ch_addr, u16 packet_length) { state_init(&ch->state); ch->addr = ch_addr; ch->packet_length = packet_length; ch->bytes_per_frame = 0; ch->done_sw_buffers_number = 0; } static void sync_init(struct dim_channel *ch, u8 ch_addr, u16 bytes_per_frame) { state_init(&ch->state); ch->addr = ch_addr; ch->packet_length = 0; ch->bytes_per_frame = bytes_per_frame; ch->done_sw_buffers_number = 0; } static void channel_init(struct dim_channel *ch, u8 ch_addr) { state_init(&ch->state); ch->addr = ch_addr; ch->packet_length = 0; ch->bytes_per_frame = 0; ch->done_sw_buffers_number = 0; } /* returns true if channel interrupt state is cleared */ static bool channel_service_interrupt(struct dim_channel *ch) { struct int_ch_state *const state = &ch->state; if (!service_channel(ch->addr, state->idx2)) return false; state->idx2 ^= 1; state->request_counter++; return true; } static bool channel_start(struct dim_channel *ch, u32 buf_addr, u16 buf_size) { struct int_ch_state *const state = &ch->state; if (buf_size <= 0) return dim_on_error(DIM_ERR_BAD_BUFFER_SIZE, "Bad buffer size"); if (ch->packet_length == 0 && ch->bytes_per_frame == 0 && buf_size != norm_ctrl_async_buffer_size(buf_size)) return dim_on_error(DIM_ERR_BAD_BUFFER_SIZE, "Bad control/async buffer size"); if (ch->packet_length && buf_size != norm_isoc_buffer_size(buf_size, ch->packet_length)) return dim_on_error(DIM_ERR_BAD_BUFFER_SIZE, "Bad isochronous buffer size"); if (ch->bytes_per_frame && buf_size != norm_sync_buffer_size(buf_size, ch->bytes_per_frame)) return dim_on_error(DIM_ERR_BAD_BUFFER_SIZE, "Bad synchronous buffer size"); if (state->level >= 2u) return dim_on_error(DIM_ERR_OVERFLOW, "Channel overflow"); ++state->level; if (ch->packet_length || ch->bytes_per_frame) dim2_start_isoc_sync(ch->addr, state->idx1, buf_addr, buf_size); else dim2_start_ctrl_async(ch->addr, state->idx1, buf_addr, buf_size); state->idx1 ^= 1; return true; } static u8 channel_service(struct dim_channel *ch) { struct int_ch_state *const state = &ch->state; if (state->service_counter != state->request_counter) { state->service_counter++; if (state->level == 0) return DIM_ERR_UNDERFLOW; --state->level; ch->done_sw_buffers_number++; } return DIM_NO_ERROR; } static bool channel_detach_buffers(struct dim_channel *ch, u16 buffers_number) { if (buffers_number > ch->done_sw_buffers_number) return dim_on_error(DIM_ERR_UNDERFLOW, "Channel underflow"); ch->done_sw_buffers_number -= buffers_number; return true; } /* -------------------------------------------------------------------------- */ /* API */ u8 dim_startup(struct dim2_regs __iomem *dim_base_address, u32 mlb_clock, u32 fcnt) { g.dim_is_initialized = false; if (!dim_base_address) return DIM_INIT_ERR_DIM_ADDR; /* MediaLB clock: 0 - 256 fs, 1 - 512 fs, 2 - 1024 fs, 3 - 2048 fs */ /* MediaLB clock: 4 - 3072 fs, 5 - 4096 fs, 6 - 6144 fs, 7 - 8192 fs */ if (mlb_clock >= 8) return DIM_INIT_ERR_MLB_CLOCK; if (fcnt > MLBC0_FCNT_MAX_VAL) return DIM_INIT_ERR_MLB_CLOCK; g.dim2 = dim_base_address; g.fcnt = fcnt; g.dbr_map[0] = 0; g.dbr_map[1] = 0; dim2_initialize(mlb_clock >= 3, mlb_clock); g.dim_is_initialized = true; return DIM_NO_ERROR; } void dim_shutdown(void) { g.dim_is_initialized = false; dim2_cleanup(); } bool dim_get_lock_state(void) { return dim2_is_mlb_locked(); } static u8 init_ctrl_async(struct dim_channel *ch, u8 type, u8 is_tx, u16 ch_address, u16 hw_buffer_size) { if (!g.dim_is_initialized || !ch) return DIM_ERR_DRIVER_NOT_INITIALIZED; if (!check_channel_address(ch_address)) return DIM_INIT_ERR_CHANNEL_ADDRESS; ch->dbr_size = hw_buffer_size; ch->dbr_addr = alloc_dbr(ch->dbr_size); if (ch->dbr_addr >= DBR_SIZE) return DIM_INIT_ERR_OUT_OF_MEMORY; channel_init(ch, ch_address / 2); dim2_configure_channel(ch->addr, type, is_tx, ch->dbr_addr, ch->dbr_size, 0, false); return DIM_NO_ERROR; } u16 dim_norm_ctrl_async_buffer_size(u16 buf_size) { return norm_ctrl_async_buffer_size(buf_size); } /** * Retrieves maximal possible correct buffer size for isochronous data type * conform to given packet length and not bigger than given buffer size. * * Returns non-zero correct buffer size or zero by error. */ u16 dim_norm_isoc_buffer_size(u16 buf_size, u16 packet_length) { if (!check_packet_length(packet_length)) return 0; return norm_isoc_buffer_size(buf_size, packet_length); } /** * Retrieves maximal possible correct buffer size for synchronous data type * conform to given bytes per frame and not bigger than given buffer size. * * Returns non-zero correct buffer size or zero by error. */ u16 dim_norm_sync_buffer_size(u16 buf_size, u16 bytes_per_frame) { if (!check_bytes_per_frame(bytes_per_frame)) return 0; return norm_sync_buffer_size(buf_size, bytes_per_frame); } u8 dim_init_control(struct dim_channel *ch, u8 is_tx, u16 ch_address, u16 max_buffer_size) { return init_ctrl_async(ch, CAT_CT_VAL_CONTROL, is_tx, ch_address, max_buffer_size); } u8 dim_init_async(struct dim_channel *ch, u8 is_tx, u16 ch_address, u16 max_buffer_size) { return init_ctrl_async(ch, CAT_CT_VAL_ASYNC, is_tx, ch_address, max_buffer_size); } u8 dim_init_isoc(struct dim_channel *ch, u8 is_tx, u16 ch_address, u16 packet_length) { if (!g.dim_is_initialized || !ch) return DIM_ERR_DRIVER_NOT_INITIALIZED; if (!check_channel_address(ch_address)) return DIM_INIT_ERR_CHANNEL_ADDRESS; if (!check_packet_length(packet_length)) return DIM_ERR_BAD_CONFIG; ch->dbr_size = packet_length * ISOC_DBR_FACTOR; ch->dbr_addr = alloc_dbr(ch->dbr_size); if (ch->dbr_addr >= DBR_SIZE) return DIM_INIT_ERR_OUT_OF_MEMORY; isoc_init(ch, ch_address / 2, packet_length); dim2_configure_channel(ch->addr, CAT_CT_VAL_ISOC, is_tx, ch->dbr_addr, ch->dbr_size, packet_length, false); return DIM_NO_ERROR; } u8 dim_init_sync(struct dim_channel *ch, u8 is_tx, u16 ch_address, u16 bytes_per_frame) { u16 bd_factor = g.fcnt + 2; if (!g.dim_is_initialized || !ch) return DIM_ERR_DRIVER_NOT_INITIALIZED; if (!check_channel_address(ch_address)) return DIM_INIT_ERR_CHANNEL_ADDRESS; if (!check_bytes_per_frame(bytes_per_frame)) return DIM_ERR_BAD_CONFIG; ch->dbr_size = bytes_per_frame << bd_factor; ch->dbr_addr = alloc_dbr(ch->dbr_size); if (ch->dbr_addr >= DBR_SIZE) return DIM_INIT_ERR_OUT_OF_MEMORY; sync_init(ch, ch_address / 2, bytes_per_frame); dim2_configure_channel(ch->addr, CAT_CT_VAL_SYNC, is_tx, ch->dbr_addr, ch->dbr_size, 0, true); return DIM_NO_ERROR; } u8 dim_destroy_channel(struct dim_channel *ch) { if (!g.dim_is_initialized || !ch) return DIM_ERR_DRIVER_NOT_INITIALIZED; dim2_clear_channel(ch->addr); if (ch->dbr_addr < DBR_SIZE) free_dbr(ch->dbr_addr, ch->dbr_size); ch->dbr_addr = DBR_SIZE; return DIM_NO_ERROR; } void dim_service_irq(struct dim_channel *const *channels) { bool state_changed; if (!g.dim_is_initialized) { dim_on_error(DIM_ERR_DRIVER_NOT_INITIALIZED, "DIM is not initialized"); return; } if (!channels) { dim_on_error(DIM_ERR_DRIVER_NOT_INITIALIZED, "Bad channels"); return; } /* * Use while-loop and a flag to make sure the age is changed back at * least once, otherwise the interrupt may never come if CPU generates * interrupt on changing age. * This cycle runs not more than number of channels, because * channel_service_interrupt() routine doesn't start the channel again. */ do { struct dim_channel *const *ch = channels; state_changed = false; while (*ch) { state_changed |= channel_service_interrupt(*ch); ++ch; } } while (state_changed); /* clear pending Interrupts */ dimcb_io_write(&g.dim2->MS0, 0); dimcb_io_write(&g.dim2->MS1, 0); } u8 dim_service_channel(struct dim_channel *ch) { if (!g.dim_is_initialized || !ch) return DIM_ERR_DRIVER_NOT_INITIALIZED; return channel_service(ch); } struct dim_ch_state_t *dim_get_channel_state(struct dim_channel *ch, struct dim_ch_state_t *state_ptr) { if (!ch || !state_ptr) return NULL; state_ptr->ready = ch->state.level < 2; state_ptr->done_buffers = ch->done_sw_buffers_number; return state_ptr; } bool dim_enqueue_buffer(struct dim_channel *ch, u32 buffer_addr, u16 buffer_size) { if (!ch) return dim_on_error(DIM_ERR_DRIVER_NOT_INITIALIZED, "Bad channel"); return channel_start(ch, buffer_addr, buffer_size); } bool dim_detach_buffers(struct dim_channel *ch, u16 buffers_number) { if (!ch) return dim_on_error(DIM_ERR_DRIVER_NOT_INITIALIZED, "Bad channel"); return channel_detach_buffers(ch, buffers_number); }