blob: cbfa422ab6fe91d1c156d1001ccefa2a03acaba7 [file] [log] [blame]
Simon Glass89b86b82011-07-17 23:49:49 -07001# Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
Rhyland Kleinc2df3ca2014-01-06 15:15:34 -05005"""This module builds a firmware image.
Simon Glass89b86b82011-07-17 23:49:49 -07006
7This modules uses a few rudimentary other libraries for its activity.
8
9Here are the names we give to the various files we deal with. It is important
10to keep these consistent!
11
12 uboot u-boot.bin (with no device tree)
13 fdt the fdt blob
14 bct the BCT file
15 bootstub uboot + fdt
16 signed (uboot + fdt + bct) signed blob
17"""
18
Simon Glassceff3ff2012-04-04 11:23:45 -070019import glob
Gabe Blackcdbdfe12013-02-06 05:37:52 -080020import hashlib
Simon Glass89b86b82011-07-17 23:49:49 -070021import os
22import re
23
Simon Glass89b86b82011-07-17 23:49:49 -070024from fdt import Fdt
25from pack_firmware import PackFirmware
26import shutil
Simon Glass7c2d5572011-11-15 14:47:08 -080027import struct
Vadim Bendebury8c35e2e2014-05-06 12:55:50 -070028from flashmaps import default_flashmaps
Simon Glass439fe7a2012-03-09 16:19:34 -080029from tools import CmdError
Vadim Bendeburyb12e3352013-06-08 17:25:19 -070030from exynos import ExynosBl2
Simon Glass89b86b82011-07-17 23:49:49 -070031
32# This data is required by bmpblk_utility. Does it ever change?
33# It was stored with the chromeos-bootimage ebuild, but we want
34# this utility to work outside the chroot.
35yaml_data = '''
36bmpblock: 1.0
37
38images:
39 devmode: DeveloperBmp/DeveloperBmp.bmp
40 recovery: RecoveryBmp/RecoveryBmp.bmp
41 rec_yuck: RecoveryNoOSBmp/RecoveryNoOSBmp.bmp
42 rec_insert: RecoveryMissingOSBmp/RecoveryMissingOSBmp.bmp
43
44screens:
45 dev_en:
46 - [0, 0, devmode]
47 rec_en:
48 - [0, 0, recovery]
49 yuck_en:
50 - [0, 0, rec_yuck]
51 ins_en:
52 - [0, 0, rec_insert]
53
54localizations:
55 - [ dev_en, rec_en, yuck_en, ins_en ]
56'''
57
Simon Glass4a887b12012-10-23 16:29:03 -070058# Build GBB flags.
59# (src/platform/vboot_reference/firmware/include/gbb_header.h)
60gbb_flag_properties = {
61 'dev-screen-short-delay': 0x00000001,
62 'load-option-roms': 0x00000002,
63 'enable-alternate-os': 0x00000004,
64 'force-dev-switch-on': 0x00000008,
65 'force-dev-boot-usb': 0x00000010,
66 'disable-fw-rollback-check': 0x00000020,
67 'enter-triggers-tonorm': 0x00000040,
68 'force-dev-boot-legacy': 0x00000080,
Shawn Nematbakhsh07c19882014-08-19 10:21:59 -070069 'faft-key-overide': 0x00000100,
70 'disable-ec-software-sync': 0x00000200,
71 'default-dev-boot-legacy': 0x00000400,
72 'disable-pd-software-sync': 0x00000800,
Furquan Shaikhd4eac3b2015-05-15 18:05:09 -070073 'force-dev-boot-fastboot-full-cap': 0x00002000,
Mary Ruthvena759c322015-11-16 08:23:26 -080074 'enable-serial': 0x00004000,
Simon Glass4a887b12012-10-23 16:29:03 -070075}
76
Simon Glass49b026b2013-04-26 16:38:42 -070077# Maps board name to Exynos product number
78type_to_model = {
79 'peach' : '5420',
80 'daisy' : '5250'
81}
82
Simon Glass5076a7f2012-10-23 16:31:54 -070083def ListGoogleBinaryBlockFlags():
84 """Print out a list of GBB flags."""
85 print ' %-30s %s' % ('Available GBB flags:', 'Hex')
86 for name, value in gbb_flag_properties.iteritems():
87 print ' %-30s %02x' % (name, value)
88
Aaron Durbin41c85b62015-12-17 17:40:29 -060089class BlobDeferral(Exception):
90 """An error indicating deferal of blob generation."""
91 pass
92
Simon Glass89b86b82011-07-17 23:49:49 -070093class Bundle:
Simon Glass290a1802011-07-17 13:54:32 -070094 """This class encapsulates the entire bundle firmware logic.
Simon Glass89b86b82011-07-17 23:49:49 -070095
Simon Glass290a1802011-07-17 13:54:32 -070096 Sequence of events:
97 bundle = Bundle(tools.Tools(), cros_output.Output())
98 bundle.SetDirs(...)
99 bundle.SetFiles(...)
100 bundle.SetOptions(...)
101 bundle.SelectFdt(fdt.Fdt('filename.dtb')
Simon Glassa4934b72012-05-09 13:35:02 -0700102 .. can call bundle.AddConfigList(), AddEnableList() if required
Simon Glass290a1802011-07-17 13:54:32 -0700103 bundle.Start(...)
Simon Glass89b86b82011-07-17 23:49:49 -0700104
Simon Glass290a1802011-07-17 13:54:32 -0700105 Public properties:
106 fdt: The fdt object that we use for building our image. This wil be the
107 one specified by the user, except that we might add config options
108 to it. This is set up by SelectFdt() which must be called before
109 bundling starts.
110 uboot_fname: Full filename of the U-Boot binary we use.
111 bct_fname: Full filename of the BCT file we use.
Simon Glass559b6612012-05-23 13:28:45 -0700112 spl_source: Source device to load U-Boot from, in SPL:
113 straps: Select device according to CPU strap pins
114 spi: Boot from SPI
115 emmc: Boot from eMMC
Simon Glass23988ae2012-03-23 16:55:22 -0700116
117 Private attributes:
118 _small: True to create a 'small' signed U-Boot, False to produce a
119 full image. The small U-Boot is enough to boot but will not have
120 access to GBB, RW U-Boot, etc.
Simon Glass290a1802011-07-17 13:54:32 -0700121 """
Simon Glass89b86b82011-07-17 23:49:49 -0700122
Simon Glass290a1802011-07-17 13:54:32 -0700123 def __init__(self, tools, output):
124 """Set up a new Bundle object.
Simon Glass89b86b82011-07-17 23:49:49 -0700125
Simon Glass290a1802011-07-17 13:54:32 -0700126 Args:
127 tools: A tools.Tools object to use for external tools.
128 output: A cros_output.Output object to use for program output.
Simon Glass89b86b82011-07-17 23:49:49 -0700129 """
Simon Glass290a1802011-07-17 13:54:32 -0700130 self._tools = tools
131 self._out = output
132
133 # Set up the things we need to know in order to operate.
Rhyland Kleinc2df3ca2014-01-06 15:15:34 -0500134 self._board = None # Board name, e.g. nyan.
Simon Glass290a1802011-07-17 13:54:32 -0700135 self._fdt_fname = None # Filename of our FDT.
Vadim Bendebury7bfdb372013-03-27 11:52:58 -0700136 self._force_rw = None
Simon Glass00d027e2013-07-20 14:51:12 -0600137 self._force_efs = None
Vadim Bendebury7bfdb372013-03-27 11:52:58 -0700138 self._gbb_flags = None
139 self._keydir = None
140 self._small = False
Simon Glass290a1802011-07-17 13:54:32 -0700141 self.bct_fname = None # Filename of our BCT file.
Vadim Bendebury7bfdb372013-03-27 11:52:58 -0700142 self.blobs = {} # Table of (type, filename) of arbitrary blobs
Hung-Te Lin5b649382011-08-03 15:01:16 +0800143 self.bmpblk_fname = None # Filename of our Bitmap Block
Vadim Bendebury7bfdb372013-03-27 11:52:58 -0700144 self.coreboot_elf = None
Stefan Reinauer8d79d362011-08-16 14:20:43 -0700145 self.coreboot_fname = None # Filename of our coreboot binary.
Vadim Bendebury7bfdb372013-03-27 11:52:58 -0700146 self.ecro_fname = None # Filename of EC read-only file
147 self.ecrw_fname = None # Filename of EC file
Randall Spangler7307da92014-07-18 12:47:34 -0700148 self.pdrw_fname = None # Filename of PD file
Simon Glass7e199222012-03-13 15:51:18 -0700149 self.exynos_bl1 = None # Filename of Exynos BL1 (pre-boot)
150 self.exynos_bl2 = None # Filename of Exynos BL2 (SPL)
Vadim Bendebury7bfdb372013-03-27 11:52:58 -0700151 self.fdt = None # Our Fdt object.
152 self.kernel_fname = None
153 self.postload_fname = None
154 self.seabios_fname = None # Filename of our SeaBIOS payload.
Simon Glass07267952012-06-08 12:45:13 -0700155 self.skeleton_fname = None # Filename of Coreboot skeleton file
Vadim Bendebury7bfdb372013-03-27 11:52:58 -0700156 self.uboot_fname = None # Filename of our U-Boot binary.
Simon Glass290a1802011-07-17 13:54:32 -0700157
158 def SetDirs(self, keydir):
159 """Set up directories required for Bundle.
160
161 Args:
162 keydir: Directory containing keys to use for signing firmware.
163 """
164 self._keydir = keydir
165
Simon Glass6dcc2f22011-07-28 15:26:49 +1200166 def SetFiles(self, board, bct, uboot=None, bmpblk=None, coreboot=None,
Simon Glassa10282a2013-01-08 17:06:41 -0800167 coreboot_elf=None,
Simon Glass07267952012-06-08 12:45:13 -0700168 postload=None, seabios=None, exynos_bl1=None, exynos_bl2=None,
Randall Spangler7307da92014-07-18 12:47:34 -0700169 skeleton=None, ecrw=None, ecro=None, pdrw=None,
Aaron Durbin95ef60c2016-01-06 09:17:21 -0600170 kernel=None, blobs=None, skip_bmpblk=False, cbfs_files=None,
171 rocbfs_files=None):
Simon Glass290a1802011-07-17 13:54:32 -0700172 """Set up files required for Bundle.
173
174 Args:
Rhyland Kleinc2df3ca2014-01-06 15:15:34 -0500175 board: The name of the board to target (e.g. nyan).
Simon Glass290a1802011-07-17 13:54:32 -0700176 uboot: The filename of the u-boot.bin image to use.
177 bct: The filename of the binary BCT file to use.
Hung-Te Lin5b649382011-08-03 15:01:16 +0800178 bmpblk: The filename of bitmap block file to use.
Simon Glassa10282a2013-01-08 17:06:41 -0800179 coreboot: The filename of the coreboot image to use (on x86).
180 coreboot_elf: If not none, the ELF file to add as a Coreboot payload.
Simon Glass6dcc2f22011-07-28 15:26:49 +1200181 postload: The filename of the u-boot-post.bin image to use.
Vincent Palatinf7286772011-10-12 14:31:53 -0700182 seabios: The filename of the SeaBIOS payload to use if any.
Simon Glass07267952012-06-08 12:45:13 -0700183 exynos_bl1: The filename of the exynos BL1 file
184 exynos_bl2: The filename of the exynos BL2 file (U-Boot spl)
185 skeleton: The filename of the coreboot skeleton file.
Simon Glassbe0bc002012-08-16 12:50:48 -0700186 ecrw: The filename of the EC (Embedded Controller) read-write file.
187 ecro: The filename of the EC (Embedded Controller) read-only file.
Randall Spangler7307da92014-07-18 12:47:34 -0700188 pdrw: The filename of the PD (PD embedded controller) read-write file.
Simon Glassde9c8072012-07-02 22:29:02 -0700189 kernel: The filename of the kernel file if any.
Che-Liang Chiou3bc344c2013-02-21 15:18:03 -0800190 blobs: List of (type, filename) of arbitrary blobs.
Vadim Bendeburybfd227f2014-11-28 22:14:24 -0800191 skip_bmpblk: True if no bmpblk is required
Aaron Durbin95ef60c2016-01-06 09:17:21 -0600192 cbfs_files: Root directory of files to be stored in RO and RW CBFS
193 rocbfs_files: Root directory of files to be stored in RO CBFS
Simon Glass290a1802011-07-17 13:54:32 -0700194 """
195 self._board = board
196 self.uboot_fname = uboot
197 self.bct_fname = bct
Hung-Te Lin5b649382011-08-03 15:01:16 +0800198 self.bmpblk_fname = bmpblk
Stefan Reinauer8d79d362011-08-16 14:20:43 -0700199 self.coreboot_fname = coreboot
Simon Glassa10282a2013-01-08 17:06:41 -0800200 self.coreboot_elf = coreboot_elf
Simon Glass6dcc2f22011-07-28 15:26:49 +1200201 self.postload_fname = postload
Vincent Palatinf7286772011-10-12 14:31:53 -0700202 self.seabios_fname = seabios
Simon Glass7e199222012-03-13 15:51:18 -0700203 self.exynos_bl1 = exynos_bl1
204 self.exynos_bl2 = exynos_bl2
Simon Glass07267952012-06-08 12:45:13 -0700205 self.skeleton_fname = skeleton
Simon Glassbe0bc002012-08-16 12:50:48 -0700206 self.ecrw_fname = ecrw
207 self.ecro_fname = ecro
Randall Spangler7307da92014-07-18 12:47:34 -0700208 self.pdrw_fname = pdrw
Simon Glassde9c8072012-07-02 22:29:02 -0700209 self.kernel_fname = kernel
Che-Liang Chiou3bc344c2013-02-21 15:18:03 -0800210 self.blobs = dict(blobs or ())
Vadim Bendeburybfd227f2014-11-28 22:14:24 -0800211 self.skip_bmpblk = skip_bmpblk
Daisuke Nojiri69662892015-09-25 15:24:04 -0700212 self.cbfs_files = cbfs_files
Aaron Durbin95ef60c2016-01-06 09:17:21 -0600213 self.rocbfs_files = rocbfs_files
Simon Glass290a1802011-07-17 13:54:32 -0700214
Simon Glass00d027e2013-07-20 14:51:12 -0600215 def SetOptions(self, small, gbb_flags, force_rw=False, force_efs=False):
Simon Glass290a1802011-07-17 13:54:32 -0700216 """Set up options supported by Bundle.
217
218 Args:
219 small: Only create a signed U-Boot - don't produce the full packed
220 firmware image. This is useful for devs who want to replace just the
221 U-Boot part while keeping the keys, gbb, etc. the same.
Simon Glass6e486c22012-10-26 15:43:42 -0700222 gbb_flags: Specification for string containing adjustments to make.
223 force_rw: Force firmware into RW mode.
Simon Glass00d027e2013-07-20 14:51:12 -0600224 force_efs: Force firmware to use 'early firmware selection' feature,
225 where RW firmware is selected before SDRAM is initialized.
Simon Glass290a1802011-07-17 13:54:32 -0700226 """
227 self._small = small
Simon Glass157c0662012-10-23 13:52:42 -0700228 self._gbb_flags = gbb_flags
Simon Glass6e486c22012-10-26 15:43:42 -0700229 self._force_rw = force_rw
Simon Glass00d027e2013-07-20 14:51:12 -0600230 self._force_efs = force_efs
Simon Glass290a1802011-07-17 13:54:32 -0700231
Simon Glass22f39fb2013-02-09 13:44:14 -0800232 def _GetBuildRoot(self):
233 """Get the path to this board's 'firmware' directory.
234
235 Returns:
236 Path to firmware directory, with ## representing the path to the
237 chroot.
238 """
Simon Glass290a1802011-07-17 13:54:32 -0700239 if not self._board:
240 raise ValueError('No board defined - please define a board to use')
Simon Glass22f39fb2013-02-09 13:44:14 -0800241 return os.path.join('##', 'build', self._board, 'firmware')
242
243 def _CheckFdtFilename(self, fname):
244 """Check provided FDT filename and return the correct name if needed.
245
246 Where the filename lacks a path, add a default path for this board.
247 Where no FDT filename is provided, select a default one for this board.
248
249 Args:
250 fname: Proposed FDT filename.
251
252 Returns:
253 Selected FDT filename, after validation.
254 """
255 build_root = self._GetBuildRoot()
Julius Wernerb4b14392013-08-09 14:41:40 -0700256 dir_name = os.path.join(build_root, 'dtb')
Simon Glass22f39fb2013-02-09 13:44:14 -0800257 if not fname:
Simon Glassceff3ff2012-04-04 11:23:45 -0700258 # Figure out where the file should be, and the name we expect.
Simon Glassceff3ff2012-04-04 11:23:45 -0700259 base_name = re.sub('_', '-', self._board)
260
261 # In case the name exists with a prefix or suffix, find it.
Julius Wernerb4b14392013-08-09 14:41:40 -0700262 wildcard = os.path.join(dir_name, '*%s.dtb' % base_name)
Simon Glassceff3ff2012-04-04 11:23:45 -0700263 found_list = glob.glob(self._tools.Filename(wildcard))
264 if len(found_list) == 1:
Simon Glass22f39fb2013-02-09 13:44:14 -0800265 fname = found_list[0]
Simon Glassceff3ff2012-04-04 11:23:45 -0700266 else:
267 # We didn't find anything definite, so set up our expected name.
Julius Wernerb4b14392013-08-09 14:41:40 -0700268 fname = os.path.join(dir_name, '%s.dtb' % base_name)
Simon Glassceff3ff2012-04-04 11:23:45 -0700269
Simon Glass881964d2012-04-04 11:34:09 -0700270 # Convert things like 'exynos5250-daisy' into a full path.
Simon Glass22f39fb2013-02-09 13:44:14 -0800271 root, ext = os.path.splitext(fname)
Simon Glass881964d2012-04-04 11:34:09 -0700272 if not ext and not os.path.dirname(root):
Julius Wernerb4b14392013-08-09 14:41:40 -0700273 fname = os.path.join(dir_name, '%s.dtb' % root)
Simon Glass22f39fb2013-02-09 13:44:14 -0800274 return fname
275
276 def CheckOptions(self):
277 """Check provided options and select defaults."""
278 build_root = self._GetBuildRoot()
Simon Glass881964d2012-04-04 11:34:09 -0700279
Simon Glass49b026b2013-04-26 16:38:42 -0700280 board_type = self._board.split('_')[0]
281 model = type_to_model.get(board_type)
282
Simon Glass290a1802011-07-17 13:54:32 -0700283 if not self.uboot_fname:
284 self.uboot_fname = os.path.join(build_root, 'u-boot.bin')
285 if not self.bct_fname:
286 self.bct_fname = os.path.join(build_root, 'bct', 'board.bct')
Simon Glass2a7f0b32011-08-26 11:25:17 -0700287 if not self.bmpblk_fname:
David Hendricksbdecc542012-08-21 13:53:58 -0700288 self.bmpblk_fname = os.path.join(build_root, 'bmpblk.bin')
Simon Glass49b026b2013-04-26 16:38:42 -0700289 if model:
290 if not self.exynos_bl1:
Simon Glassd05696e2013-06-13 20:14:00 -0700291 self.exynos_bl1 = os.path.join(build_root, 'u-boot.bl1.bin')
Simon Glass49b026b2013-04-26 16:38:42 -0700292 if not self.exynos_bl2:
Julius Wernerb12c0052013-08-14 13:57:04 -0700293 self.exynos_bl2 = os.path.join(build_root, 'u-boot-spl.wrapped.bin')
Simon Glass07267952012-06-08 12:45:13 -0700294 if not self.coreboot_fname:
295 self.coreboot_fname = os.path.join(build_root, 'coreboot.rom')
296 if not self.skeleton_fname:
Stefan Reinauer728be822012-10-02 16:54:09 -0700297 self.skeleton_fname = os.path.join(build_root, 'coreboot.rom')
Stefan Reinauer9ad54842012-10-10 12:25:23 -0700298 if not self.seabios_fname:
299 self.seabios_fname = 'seabios.cbfs'
Simon Glassbe0bc002012-08-16 12:50:48 -0700300 if not self.ecrw_fname:
301 self.ecrw_fname = os.path.join(build_root, 'ec.RW.bin')
Randall Spangler7307da92014-07-18 12:47:34 -0700302 if not self.pdrw_fname:
303 self.pdrw_fname = os.path.join(build_root, 'pd.RW.bin')
Simon Glassbe0bc002012-08-16 12:50:48 -0700304 if not self.ecro_fname:
305 self.ecro_fname = os.path.join(build_root, 'ec.RO.bin')
Simon Glass89b86b82011-07-17 23:49:49 -0700306
Simon Glass75759302012-03-15 20:26:53 -0700307 def GetFiles(self):
308 """Get a list of files that we know about.
309
310 This is the opposite of SetFiles except that we may have put in some
311 default names. It returns a dictionary containing the filename for
312 each of a number of pre-defined files.
313
314 Returns:
315 Dictionary, with one entry for each file.
316 """
317 file_list = {
318 'bct' : self.bct_fname,
319 'exynos-bl1' : self.exynos_bl1,
320 'exynos-bl2' : self.exynos_bl2,
321 }
322 return file_list
323
Simon Glass4a887b12012-10-23 16:29:03 -0700324 def DecodeGBBFlagsFromFdt(self):
325 """Get Google Binary Block flags from the FDT.
326
327 These should be in the chromeos-config node, like this:
328
329 chromeos-config {
330 gbb-flag-dev-screen-short-delay;
331 gbb-flag-force-dev-switch-on;
332 gbb-flag-force-dev-boot-usb;
333 gbb-flag-disable-fw-rollback-check;
334 };
335
336 Returns:
337 GBB flags value from FDT.
338 """
339 chromeos_config = self.fdt.GetProps("/chromeos-config")
340 gbb_flags = 0
341 for name in chromeos_config:
342 if name.startswith('gbb-flag-'):
343 flag_value = gbb_flag_properties.get(name[9:])
344 if flag_value:
345 gbb_flags |= flag_value
346 self._out.Notice("FDT: Enabling %s." % name)
347 else:
348 raise ValueError("FDT contains invalid GBB flags '%s'" % name)
349 return gbb_flags
350
Simon Glass157c0662012-10-23 13:52:42 -0700351 def DecodeGBBFlagsFromOptions(self, gbb_flags, adjustments):
352 """Decode ajustments to the provided GBB flags.
353
354 We support three options:
355
356 hex value: c2
357 defined value: force-dev-boot-usb,load-option-roms
358 adjust default value: -load-option-roms,+force-dev-boot-usb
359
360 The last option starts from the passed-in GBB flags and adds or removes
361 flags.
362
363 Args:
364 gbb_flags: Base (default) FDT flags.
365 adjustments: String containing adjustments to make.
366
367 Returns:
368 Updated FDT flags.
369 """
370 use_base_value = True
371 if adjustments:
372 try:
373 return int(adjustments, base=16)
Vadim Bendebury7bfdb372013-03-27 11:52:58 -0700374 except (ValueError, TypeError):
Simon Glass157c0662012-10-23 13:52:42 -0700375 pass
376 for flag in adjustments.split(','):
377 oper = None
378 if flag[0] in ['-', '+']:
379 oper = flag[0]
380 flag = flag[1:]
381 value = gbb_flag_properties.get(flag)
382 if not value:
383 raise ValueError("Invalid GBB flag '%s'" % flag)
384 if oper == '+':
385 gbb_flags |= value
Simon Glass84816582012-11-20 10:53:10 -0800386 self._out.Notice("Cmdline: Enabling %s." % flag)
Simon Glass157c0662012-10-23 13:52:42 -0700387 elif oper == '-':
388 gbb_flags &= ~value
Simon Glass84816582012-11-20 10:53:10 -0800389 self._out.Notice("Cmdline: Disabling %s." % flag)
Simon Glass157c0662012-10-23 13:52:42 -0700390 else:
391 if use_base_value:
392 gbb_flags = 0
393 use_base_value = False
Simon Glass84816582012-11-20 10:53:10 -0800394 self._out.Notice('Cmdline: Resetting flags to 0')
Simon Glass157c0662012-10-23 13:52:42 -0700395 gbb_flags |= value
Simon Glass84816582012-11-20 10:53:10 -0800396 self._out.Notice("Cmdline: Enabling %s." % flag)
Simon Glass157c0662012-10-23 13:52:42 -0700397
398 return gbb_flags
399
Simon Glass56577572011-07-19 11:08:06 +1200400 def _CreateGoogleBinaryBlock(self, hardware_id):
Simon Glass89b86b82011-07-17 23:49:49 -0700401 """Create a GBB for the image.
402
Simon Glass56577572011-07-19 11:08:06 +1200403 Args:
404 hardware_id: Hardware ID to use for this board. If None, then the
405 default from the Fdt will be used
406
Simon Glass89b86b82011-07-17 23:49:49 -0700407 Returns:
408 Path of the created GBB file.
Simon Glass89b86b82011-07-17 23:49:49 -0700409 """
Simon Glass56577572011-07-19 11:08:06 +1200410 if not hardware_id:
Simon Glass02d124a2012-03-02 14:47:20 -0800411 hardware_id = self.fdt.GetString('/config', 'hwid')
Simon Glass89b86b82011-07-17 23:49:49 -0700412 gbb_size = self.fdt.GetFlashPartSize('ro', 'gbb')
Simon Glass290a1802011-07-17 13:54:32 -0700413 odir = self._tools.outdir
Simon Glass89b86b82011-07-17 23:49:49 -0700414
Simon Glass4a887b12012-10-23 16:29:03 -0700415 gbb_flags = self.DecodeGBBFlagsFromFdt()
Stefan Reinauer975e68f2012-02-27 13:27:08 -0800416
Simon Glass157c0662012-10-23 13:52:42 -0700417 # Allow command line to override flags
418 gbb_flags = self.DecodeGBBFlagsFromOptions(gbb_flags, self._gbb_flags)
419
Simon Glass4a887b12012-10-23 16:29:03 -0700420 self._out.Notice("GBB flags value %#x" % gbb_flags)
Simon Glass89b86b82011-07-17 23:49:49 -0700421 self._out.Progress('Creating GBB')
422 sizes = [0x100, 0x1000, gbb_size - 0x2180, 0x1000]
423 sizes = ['%#x' % size for size in sizes]
424 gbb = 'gbb.bin'
Simon Glass290a1802011-07-17 13:54:32 -0700425 keydir = self._tools.Filename(self._keydir)
Vadim Bendeburybfd227f2014-11-28 22:14:24 -0800426
427 gbb_set_command = ['-s',
428 '--hwid=%s' % hardware_id,
429 '--rootkey=%s/root_key.vbpubk' % keydir,
430 '--recoverykey=%s/recovery_key.vbpubk' % keydir,
431 '--flags=%d' % gbb_flags,
432 gbb]
433 if not self.skip_bmpblk:
434 gbb_set_command[-1:-1] = ['--bmpfv=%s' % self._tools.Filename(
435 self.bmpblk_fname),]
436
Simon Glass290a1802011-07-17 13:54:32 -0700437 self._tools.Run('gbb_utility', ['-c', ','.join(sizes), gbb], cwd=odir)
Vadim Bendeburybfd227f2014-11-28 22:14:24 -0800438 self._tools.Run('gbb_utility', gbb_set_command, cwd=odir)
Simon Glass290a1802011-07-17 13:54:32 -0700439 return os.path.join(odir, gbb)
Simon Glass89b86b82011-07-17 23:49:49 -0700440
Simon Glasse13ee2c2011-07-28 08:12:28 +1200441 def _SignBootstub(self, bct, bootstub, text_base):
Simon Glass89b86b82011-07-17 23:49:49 -0700442 """Sign an image so that the Tegra SOC will boot it.
443
444 Args:
445 bct: BCT file to use.
446 bootstub: Boot stub (U-Boot + fdt) file to sign.
447 text_base: Address of text base for image.
Simon Glass89b86b82011-07-17 23:49:49 -0700448
449 Returns:
450 filename of signed image.
Simon Glass89b86b82011-07-17 23:49:49 -0700451 """
452 # First create a config file - this is how we instruct cbootimage
Simon Glasse13ee2c2011-07-28 08:12:28 +1200453 signed = os.path.join(self._tools.outdir, 'signed.bin')
Simon Glass89b86b82011-07-17 23:49:49 -0700454 self._out.Progress('Signing Bootstub')
Simon Glasse13ee2c2011-07-28 08:12:28 +1200455 config = os.path.join(self._tools.outdir, 'boot.cfg')
Simon Glass89b86b82011-07-17 23:49:49 -0700456 fd = open(config, 'w')
457 fd.write('Version = 1;\n')
458 fd.write('Redundancy = 1;\n')
459 fd.write('Bctfile = %s;\n' % bct)
Doug Anderson0eeb0742011-09-15 18:11:40 -0700460
461 # TODO(dianders): Right now, we don't have enough space in our flash map
462 # for two copies of the BCT when we're using NAND, so hack it to 1. Not
463 # sure what this does for reliability, but at least things will fit...
464 is_nand = "NvBootDevType_Nand" in self._tools.Run('bct_dump', [bct])
465 if is_nand:
466 fd.write('Bctcopy = 1;\n')
467
Simon Glass89b86b82011-07-17 23:49:49 -0700468 fd.write('BootLoader = %s,%#x,%#x,Complete;\n' % (bootstub, text_base,
469 text_base))
Doug Anderson0eeb0742011-09-15 18:11:40 -0700470
Simon Glass89b86b82011-07-17 23:49:49 -0700471 fd.close()
472
473 self._tools.Run('cbootimage', [config, signed])
474 self._tools.OutputSize('BCT', bct)
475 self._tools.OutputSize('Signed image', signed)
476 return signed
477
Doug Anderson86ce5f42011-07-27 10:40:18 -0700478 def SetBootcmd(self, bootcmd, bootsecure):
Simon Glass290a1802011-07-17 13:54:32 -0700479 """Set the boot command for U-Boot.
Simon Glass89b86b82011-07-17 23:49:49 -0700480
481 Args:
Simon Glass290a1802011-07-17 13:54:32 -0700482 bootcmd: Boot command to use, as a string (if None this this is a nop).
Doug Anderson86ce5f42011-07-27 10:40:18 -0700483 bootsecure: We'll set '/config/bootsecure' to 1 if True and 0 if False.
Simon Glass89b86b82011-07-17 23:49:49 -0700484 """
Simon Glass468d8752012-09-19 16:36:19 -0700485 if bootcmd is not None:
486 if bootcmd == 'none':
487 bootcmd = ''
Simon Glass02d124a2012-03-02 14:47:20 -0800488 self.fdt.PutString('/config', 'bootcmd', bootcmd)
489 self.fdt.PutInteger('/config', 'bootsecure', int(bootsecure))
Simon Glass290a1802011-07-17 13:54:32 -0700490 self._out.Info('Boot command: %s' % bootcmd)
Simon Glass89b86b82011-07-17 23:49:49 -0700491
Simon Glassa4934b72012-05-09 13:35:02 -0700492 def SetNodeEnabled(self, node_name, enabled):
493 """Set whether an node is enabled or disabled.
494
495 This simply sets the 'status' property of a node to "ok", or "disabled".
496
497 The node should either be a full path to the node (like '/uart@10200000')
498 or an alias property.
499
500 Aliases are supported like this:
501
502 aliases {
503 console = "/uart@10200000";
504 };
505
506 pointing to a node:
507
508 uart@10200000 {
Simon Glass4c5066f2012-06-20 16:51:19 -0700509 status = "okay";
Simon Glassa4934b72012-05-09 13:35:02 -0700510 };
511
512 In this case, this function takes the name of the alias ('console' in
513 this case) and updates the status of the node that is pointed to, to
514 either ok or disabled. If the alias does not exist, a warning is
515 displayed.
516
517 Args:
518 node_name: Name of node (e.g. '/uart@10200000') or alias alias
519 (e.g. 'console') to adjust
520 enabled: True to enable, False to disable
521 """
522 # Look up the alias if this is an alias reference
523 if not node_name.startswith('/'):
524 lookup = self.fdt.GetString('/aliases', node_name, '')
525 if not lookup:
526 self._out.Warning("Cannot find alias '%s' - ignoring" % node_name)
527 return
528 node_name = lookup
529 if enabled:
Simon Glass4c5066f2012-06-20 16:51:19 -0700530 status = 'okay'
Simon Glassa4934b72012-05-09 13:35:02 -0700531 else:
532 status = 'disabled'
533 self.fdt.PutString(node_name, 'status', status)
534
535 def AddEnableList(self, enable_list):
536 """Process a list of nodes to enable/disable.
537
538 Args:
Vadim Bendebury7dac18c2014-05-06 14:13:35 -0700539 enable_list: List of (node, value) tuples to add to the fdt. For each
Simon Glassa4934b72012-05-09 13:35:02 -0700540 tuple:
541 node: The fdt node to write to will be <node> or pointed to by
542 /aliases/<node>. We can tell which
543 value: 0 to disable the node, 1 to enable it
Vadim Bendebury7dac18c2014-05-06 14:13:35 -0700544
Vadim Bendebury507c0012013-06-09 12:49:25 -0700545 Raises:
546 CmdError if a command fails.
Simon Glassa4934b72012-05-09 13:35:02 -0700547 """
548 if enable_list:
549 for node_name, enabled in enable_list:
550 try:
551 enabled = int(enabled)
552 if enabled not in (0, 1):
553 raise ValueError
Vadim Bendebury7bfdb372013-03-27 11:52:58 -0700554 except ValueError:
Simon Glassa4934b72012-05-09 13:35:02 -0700555 raise CmdError("Invalid enable option value '%s' "
Vadim Bendebury7bfdb372013-03-27 11:52:58 -0700556 "(should be 0 or 1)" % str(enabled))
Simon Glassa4934b72012-05-09 13:35:02 -0700557 self.SetNodeEnabled(node_name, enabled)
558
Simon Glass290a1802011-07-17 13:54:32 -0700559 def AddConfigList(self, config_list, use_int=False):
560 """Add a list of config items to the fdt.
561
562 Normally these values are written to the fdt as strings, but integers
563 are also supported, in which case the values will be converted to integers
564 (if necessary) before being stored.
565
566 Args:
567 config_list: List of (config, value) tuples to add to the fdt. For each
568 tuple:
569 config: The fdt node to write to will be /config/<config>.
570 value: An integer or string value to write.
571 use_int: True to only write integer values.
572
573 Raises:
574 CmdError: if a value is required to be converted to integer but can't be.
575 """
576 if config_list:
577 for config in config_list:
578 value = config[1]
579 if use_int:
580 try:
581 value = int(value)
Vadim Bendebury7bfdb372013-03-27 11:52:58 -0700582 except ValueError:
Simon Glass290a1802011-07-17 13:54:32 -0700583 raise CmdError("Cannot convert config option '%s' to integer" %
Vadim Bendebury7bfdb372013-03-27 11:52:58 -0700584 str(value))
Simon Glass290a1802011-07-17 13:54:32 -0700585 if type(value) == type(1):
Simon Glass02d124a2012-03-02 14:47:20 -0800586 self.fdt.PutInteger('/config', '%s' % config[0], value)
Simon Glass290a1802011-07-17 13:54:32 -0700587 else:
Simon Glass02d124a2012-03-02 14:47:20 -0800588 self.fdt.PutString('/config', '%s' % config[0], value)
Simon Glass290a1802011-07-17 13:54:32 -0700589
Simon Glass7c2d5572011-11-15 14:47:08 -0800590 def DecodeTextBase(self, data):
591 """Look at a U-Boot image and try to decode its TEXT_BASE.
592
593 This works because U-Boot has a header with the value 0x12345678
594 immediately followed by the TEXT_BASE value. We can therefore read this
595 from the image with some certainty. We check only the first 40 words
596 since the header should be within that region.
597
Simon Glass96b50302012-07-20 06:55:28 +0100598 Since upstream Tegra has moved to having a 16KB SPL region at the start,
599 and currently this does holds the U-Boot text base (e.g. 0x10c000) instead
600 of the SPL one (e.g. 0x108000), we search in the U-Boot part as well.
601
Simon Glass7c2d5572011-11-15 14:47:08 -0800602 Args:
603 data: U-Boot binary data
604
605 Returns:
606 Text base (integer) or None if none was found
607 """
608 found = False
Simon Glass96b50302012-07-20 06:55:28 +0100609 for start in (0, 0x4000):
610 for i in range(start, start + 160, 4):
611 word = data[i:i + 4]
Simon Glass7c2d5572011-11-15 14:47:08 -0800612
Simon Glass96b50302012-07-20 06:55:28 +0100613 # TODO(sjg): This does not cope with a big-endian target
614 value = struct.unpack('<I', word)[0]
615 if found:
616 return value - start
617 if value == 0x12345678:
618 found = True
Simon Glass7c2d5572011-11-15 14:47:08 -0800619
620 return None
621
622 def CalcTextBase(self, name, fdt, fname):
623 """Calculate the TEXT_BASE to use for U-Boot.
624
625 Normally this value is in the fdt, so we just read it from there. But as
626 a second check we look at the image itself in case this is different, and
627 switch to that if it is.
628
629 This allows us to flash any U-Boot even if its TEXT_BASE is different.
630 This is particularly useful with upstream U-Boot which uses a different
631 value (which we will move to).
632 """
633 data = self._tools.ReadFile(fname)
Andrew Chewaa092542013-01-09 16:30:52 -0800634 # The value that comes back from fdt.GetInt is signed, which makes no
635 # sense for an address base. Force it to unsigned.
636 fdt_text_base = fdt.GetInt('/chromeos-config', 'textbase', 0) & 0xffffffff
Simon Glass7c2d5572011-11-15 14:47:08 -0800637 text_base = self.DecodeTextBase(data)
Simon Glass96b50302012-07-20 06:55:28 +0100638 text_base_str = '%#x' % text_base if text_base else 'None'
639 self._out.Info('TEXT_BASE: fdt says %#x, %s says %s' % (fdt_text_base,
640 fname, text_base_str))
Simon Glass7c2d5572011-11-15 14:47:08 -0800641
642 # If they are different, issue a warning and switch over.
643 if text_base and text_base != fdt_text_base:
644 self._out.Warning("TEXT_BASE %x in %sU-Boot doesn't match "
645 "fdt value of %x. Using %x" % (text_base, name,
646 fdt_text_base, text_base))
647 fdt_text_base = text_base
648 return fdt_text_base
649
Simon Glass6dcc2f22011-07-28 15:26:49 +1200650 def _CreateBootStub(self, uboot, base_fdt, postload):
Simon Glass89b86b82011-07-17 23:49:49 -0700651 """Create a boot stub and a signed boot stub.
652
Simon Glass6dcc2f22011-07-28 15:26:49 +1200653 For postload:
654 We add a /config/postload-text-offset entry to the signed bootstub's
655 fdt so that U-Boot can find the postload code.
656
657 The raw (unsigned) bootstub will have a value of -1 for this since we will
658 simply append the postload code to the bootstub and it can find it there.
659 This will be used for RW A/B firmware.
660
661 For the signed case this value will specify where in the flash to find
662 the postload code. This will be used for RO firmware.
663
Simon Glass89b86b82011-07-17 23:49:49 -0700664 Args:
665 uboot: Path to u-boot.bin (may be chroot-relative)
Simon Glass29b96ad2012-03-09 15:34:33 -0800666 base_fdt: Fdt object containing the flat device tree.
Simon Glass6dcc2f22011-07-28 15:26:49 +1200667 postload: Path to u-boot-post.bin, or None if none.
Simon Glass89b86b82011-07-17 23:49:49 -0700668
669 Returns:
670 Tuple containing:
Simon Glass6dcc2f22011-07-28 15:26:49 +1200671 Full path to bootstub (uboot + fdt(-1) + postload).
672 Full path to signed (uboot + fdt(flash pos) + bct) + postload.
Simon Glass89b86b82011-07-17 23:49:49 -0700673
674 Raises:
675 CmdError if a command fails.
676 """
Simon Glasse13ee2c2011-07-28 08:12:28 +1200677 bootstub = os.path.join(self._tools.outdir, 'u-boot-fdt.bin')
Simon Glass7c2d5572011-11-15 14:47:08 -0800678 text_base = self.CalcTextBase('', self.fdt, uboot)
Simon Glass89b86b82011-07-17 23:49:49 -0700679 uboot_data = self._tools.ReadFile(uboot)
Simon Glass6dcc2f22011-07-28 15:26:49 +1200680
681 # Make a copy of the fdt for the bootstub
682 fdt = base_fdt.Copy(os.path.join(self._tools.outdir, 'bootstub.dtb'))
Vadim Bendebury7bfdb372013-03-27 11:52:58 -0700683 fdt.PutInteger('/config', 'postload-text-offset', 0xffffffff)
Simon Glass290a1802011-07-17 13:54:32 -0700684 fdt_data = self._tools.ReadFile(fdt.fname)
Simon Glasse13ee2c2011-07-28 08:12:28 +1200685
Simon Glass89b86b82011-07-17 23:49:49 -0700686 self._tools.WriteFile(bootstub, uboot_data + fdt_data)
Simon Glass290a1802011-07-17 13:54:32 -0700687 self._tools.OutputSize('U-Boot binary', self.uboot_fname)
688 self._tools.OutputSize('U-Boot fdt', self._fdt_fname)
Simon Glass89b86b82011-07-17 23:49:49 -0700689 self._tools.OutputSize('Combined binary', bootstub)
690
Simon Glasse13ee2c2011-07-28 08:12:28 +1200691 # Sign the bootstub; this is a combination of the board specific
Simon Glass89b86b82011-07-17 23:49:49 -0700692 # bct and the stub u-boot image.
Simon Glass290a1802011-07-17 13:54:32 -0700693 signed = self._SignBootstub(self._tools.Filename(self.bct_fname),
Simon Glasse13ee2c2011-07-28 08:12:28 +1200694 bootstub, text_base)
Simon Glass6dcc2f22011-07-28 15:26:49 +1200695
696 signed_postload = os.path.join(self._tools.outdir, 'signed-postload.bin')
697 data = self._tools.ReadFile(signed)
698
699 if postload:
700 # We must add postload to the bootstub since A and B will need to
701 # be able to find it without the /config/postload-text-offset mechanism.
702 bs_data = self._tools.ReadFile(bootstub)
703 bs_data += self._tools.ReadFile(postload)
704 bootstub = os.path.join(self._tools.outdir, 'u-boot-fdt-postload.bin')
705 self._tools.WriteFile(bootstub, bs_data)
706 self._tools.OutputSize('Combined binary with postload', bootstub)
707
708 # Now that we know the file size, adjust the fdt and re-sign
709 postload_bootstub = os.path.join(self._tools.outdir, 'postload.bin')
Simon Glass02d124a2012-03-02 14:47:20 -0800710 fdt.PutInteger('/config', 'postload-text-offset', len(data))
Simon Glass6dcc2f22011-07-28 15:26:49 +1200711 fdt_data = self._tools.ReadFile(fdt.fname)
712 self._tools.WriteFile(postload_bootstub, uboot_data + fdt_data)
713 signed = self._SignBootstub(self._tools.Filename(self.bct_fname),
714 postload_bootstub, text_base)
715 if len(data) != os.path.getsize(signed):
716 raise CmdError('Signed file size changed from %d to %d after updating '
717 'fdt' % (len(data), os.path.getsize(signed)))
718
719 # Re-read the signed image, and add the post-load binary.
720 data = self._tools.ReadFile(signed)
721 data += self._tools.ReadFile(postload)
722 self._tools.OutputSize('Post-load binary', postload)
723
724 self._tools.WriteFile(signed_postload, data)
725 self._tools.OutputSize('Final bootstub with postload', signed_postload)
726
727 return bootstub, signed_postload
Simon Glass89b86b82011-07-17 23:49:49 -0700728
Aaron Durbin95ef60c2016-01-06 09:17:21 -0600729 def _AddCbfsFiles(self, bootstub, cbfs_files):
730 for dir, subs, files in os.walk(cbfs_files):
Aaron Durbin5751c3e2016-01-04 11:45:22 -0600731 for file in files:
732 file = os.path.join(dir, file)
Aaron Durbin95ef60c2016-01-06 09:17:21 -0600733 cbfs_name = file.replace(cbfs_files, '', 1).strip('/')
Aaron Durbin5751c3e2016-01-04 11:45:22 -0600734 self._tools.Run('cbfstool', [bootstub, 'add', '-f', file,
735 '-n', cbfs_name, '-t', 'raw', '-c', 'lzma'])
736
737 def _CreateCorebootStub(self, pack, coreboot):
738 """Create a coreboot boot stub and add pack properties.
Stefan Reinauerc2e1e4d2011-08-23 14:50:59 -0700739
740 Args:
Aaron Durbina113f522016-01-05 09:09:55 -0600741 pack: a PackFirmware object describing the firmware image to build.
Stefan Reinauerc2e1e4d2011-08-23 14:50:59 -0700742 coreboot: Path to coreboot.rom
Stefan Reinauerc2e1e4d2011-08-23 14:50:59 -0700743 """
744 bootstub = os.path.join(self._tools.outdir, 'coreboot-full.rom')
Simon Glassf2b3a5c2012-06-07 14:02:36 -0700745 shutil.copyfile(self._tools.Filename(coreboot), bootstub)
Simon Glasscbc83552012-07-23 15:26:22 +0100746
Aaron Durbin5751c3e2016-01-04 11:45:22 -0600747 pack.AddProperty('coreboot', bootstub)
748 pack.AddProperty('image', bootstub)
Stefan Reinauerc2e1e4d2011-08-23 14:50:59 -0700749
Aaron Durbin95ef60c2016-01-06 09:17:21 -0600750 # Add files to to RO and RW CBFS if provided.
Aaron Durbin5751c3e2016-01-04 11:45:22 -0600751 if self.cbfs_files:
Aaron Durbin95ef60c2016-01-06 09:17:21 -0600752 self._AddCbfsFiles(bootstub, self.cbfs_files)
Simon Glass7e199222012-03-13 15:51:18 -0700753
Aaron Durbina113f522016-01-05 09:09:55 -0600754 # Create a coreboot copy to use as a scratch pad. Order matters. The
755 # cbfs_files were added prior to this action. That's so the RW CBFS
Patrick Georgi3a332672015-11-20 10:02:51 +0100756 # regions inherit the files from the RO CBFS region. Additionally,
757 # include the full FMAP within the file.
758 cb_copy = os.path.abspath(os.path.join(self._tools.outdir, 'cb_with_fmap'))
Aaron Durbina113f522016-01-05 09:09:55 -0600759 self._tools.WriteFile(cb_copy, self._tools.ReadFile(bootstub))
Patrick Georgi3a332672015-11-20 10:02:51 +0100760 binary = self._tools.ReadFile(bootstub)
761 fmap_offset, fmap = pack.GetFmap()
762 if len(binary) < fmap_offset + len(fmap):
763 raise CmdError('FMAP will not fit')
764 # Splice in FMAP data.
765 binary = binary[:fmap_offset] + fmap + binary[fmap_offset + len(fmap):]
766 self._tools.WriteFile(cb_copy, binary)
767 # Publish where coreboot is with the FMAP data.
768 pack.AddProperty('cb_with_fmap', cb_copy)
Aaron Durbina113f522016-01-05 09:09:55 -0600769
Aaron Durbin95ef60c2016-01-06 09:17:21 -0600770 # Add files to to RO CBFS if provided. This done here such that the
771 # copy above does not contain the RO CBFS files.
772 if self.rocbfs_files:
773 self._AddCbfsFiles(bootstub, self.rocbfs_files)
774
Aaron Durbina113f522016-01-05 09:09:55 -0600775
Simon Glass89b86b82011-07-17 23:49:49 -0700776 def _PackOutput(self, msg):
777 """Helper function to write output from PackFirmware (verbose level 2).
778
779 This is passed to PackFirmware for it to use to write output.
780
781 Args:
782 msg: Message to display.
783 """
784 self._out.Notice(msg)
785
Aaron Durbin80564452015-12-21 15:25:06 -0600786 def _FmapNameByPath(self, path):
787 """ Take list of names to form node path. Return FMAP name.
788
789 Obtain the FMAP name described by the node path.
790
791 Args:
792 path: list forming a node path.
793
794 Returns:
795 FMAP name of fdt node.
796
797 Raises:
798 CmdError if path not found.
799 """
800 lbl = self.fdt.GetLabel(self.fdt.GetFlashNode(*path))
801 return re.sub('-', '_', lbl).upper()
802
803 def _PrepareCbfsHash(self, pack, blob_name):
804 """Create blob in rw-{a,b}-boothash with 'cbfstool hashcbfs'.
805
806 When the blob name is defined as cbfshash/<section>/<subsection>, fill the
807 <section>_<subsection> area in the flash map with CBFS hash generated
808 using the 'cbfstool hashcbfs' command.
809
810 Args:
811 pack: a PackFirmware object describing the firmware image to build.
812 blob_name: a string, blob name describing what FMAP section this CBFS
813 copy is destined to
814 Raises:
815 CmdError if cbfs-files node has incorrect parameters.
816 BlobDeferral if the CBFS region is not populated yet or if the coreboot
817 image with fmap is not available yet.
818 """
819 cb_copy = pack.GetProperty('cb_with_fmap')
820 if cb_copy is None:
821 raise BlobDeferral("Waiting for '%s'" % cb_copy)
822
823 part_sections = blob_name.split('/')[1:]
824 fmap_dst = self._FmapNameByPath(part_sections)
825
826 # Example of FDT ndoes asking for CBFS hash:
827 # rw-b-boot {
828 # label = "fw-main-b";
829 # reg = <0x00700000 0x002dff80>;
830 # type = "blob cbfs/rw/b-boot";
831 # };
832 # rw-b-boothash {
833 # label = "fw-main-b-hash";
834 # reg = <0x009dff80 0x00000040>;
835 # type = "blob cbfshash/rw/b-boothash";
836 # cbfs-node = "cbfs/rw/b-boot";
837 # };
838 hash_node = self.fdt.GetFlashNode(*part_sections)
839 cbfs_blob_name = self.fdt.GetString(hash_node, 'cbfs-node')
840
841 if not pack.GetProperty(cbfs_blob_name):
842 raise BlobDeferral("Waiting for '%s'" % cbfs_blob_name)
843
844 cbfs_node_path = cbfs_blob_name.split('/')[1:]
845 fmap_src = self._FmapNameByPath(cbfs_node_path)
846
847 # Compute CBFS hash and place it in the corect spot.
848 self._tools.Run('cbfstool', [cb_copy, 'hashcbfs', '-r', fmap_dst,
849 '-R', fmap_src, '-A', 'sha256'])
850
851 # Base address and size of the desitnation partition
852 base, size = self.fdt.GetFlashPart(*part_sections)
853
854 # And extract the blob for the FW section
855 rw_section = os.path.join(self._tools.outdir, '_'.join(part_sections))
856 self._tools.WriteFile(rw_section,
857 self._tools.ReadFile(cb_copy)[base:base+size])
858
859 pack.AddProperty(blob_name, rw_section)
860
861
Vadim Bendeburyc9600c62014-12-22 16:31:13 -0800862 def _PrepareCbfs(self, pack, blob_name):
863 """Create CBFS blob in rw-boot-{a,b} FMAP sections.
864
865 When the blob name is defined as cbfs#<section>#<subsection>, fill the
866 <section>_<subsection> area in the flash map with a CBFS copy, putting the
867 CBFS header of the copy at the base of the section.
868
869 If --coreboot-elf parameter was specified during cros_bumdle_firmware
870 invocation, add the parameter of this option as the payload to the new
871 CBFS instance.
872
873 Args:
874 pack: a PackFirmware object describing the firmware image to build.
875 blob_name: a string, blob name describing what FMAP section this CBFS
876 copy is destined to
877 Raises:
Patrick Georgi3a332672015-11-20 10:02:51 +0100878 CmdError if cbfs-files node has incorrect parameters.
Aaron Durbina113f522016-01-05 09:09:55 -0600879 BlobDeferral if coreboot image with fmap is not available yet.
Vadim Bendeburyc9600c62014-12-22 16:31:13 -0800880 """
Patrick Georgi3a332672015-11-20 10:02:51 +0100881 cb_copy = pack.GetProperty('cb_with_fmap')
Aaron Durbina113f522016-01-05 09:09:55 -0600882 if cb_copy is None:
Patrick Georgi3a332672015-11-20 10:02:51 +0100883 raise BlobDeferral("Waiting for 'cb_with_fmap' property")
Vadim Bendeburyc9600c62014-12-22 16:31:13 -0800884
885 part_sections = blob_name.split('/')[1:]
Aaron Durbin80564452015-12-21 15:25:06 -0600886 fmap_src = self._FmapNameByPath('ro-boot'.split('-'))
887 fmap_dst = self._FmapNameByPath(part_sections)
Vadim Bendeburyc9600c62014-12-22 16:31:13 -0800888
889 # Base address and size of the desitnation partition
890 base, size = self.fdt.GetFlashPart(*part_sections)
891
Patrick Georgi10ea5ef2015-10-22 19:14:26 +0200892 # Check if there's an advanced CBFS configuration request
893 node = self.fdt.GetFlashNode(*part_sections)
894 try:
895 cbfs_config = self.fdt.GetProps(node + '/cbfs-files')
896 except CmdError:
897 cbfs_config = None
898
Vadim Bendeburyc9600c62014-12-22 16:31:13 -0800899 # Copy CBFS to the required offset
Patrick Georgi10690b42015-11-20 22:06:38 +0100900 self._tools.Run('cbfstool', [cb_copy, 'copy', '-r', fmap_dst,
901 '-R', fmap_src])
902
903 # Add a CBFS master header for good measure
904 self._tools.Run('cbfstool', [cb_copy, 'add-master-header',
905 '-r', fmap_dst])
Vadim Bendeburyc9600c62014-12-22 16:31:13 -0800906
907 # Add coreboot payload if so requested. Note that the some images use
908 # different payload for the rw sections, which is passed in as the value
909 # of the --uboot option in the command line.
910 if self.uboot_fname:
911 payload_fname = self.uboot_fname
912 elif self.coreboot_elf:
913 payload_fname = self.coreboot_elf
914 else:
915 payload_fname = None
916
917 if payload_fname:
918 self._tools.Run('cbfstool', [
919 cb_copy, 'add-payload', '-f', payload_fname,
Patrick Georgi10690b42015-11-20 22:06:38 +0100920 '-n', 'fallback/payload', '-c', 'lzma' , '-r', fmap_dst])
Vadim Bendeburyc9600c62014-12-22 16:31:13 -0800921
Patrick Georgi964fb542015-10-16 16:52:03 +0200922 if self.ecrw_fname:
923 self._tools.Run('cbfstool', [
924 cb_copy, 'add', '-f', self.ecrw_fname, '-t', 'raw',
Patrick Georgi10690b42015-11-20 22:06:38 +0100925 '-n', 'ecrw', '-A', 'sha256', '-r', fmap_dst ])
Patrick Georgi964fb542015-10-16 16:52:03 +0200926
927 if self.pdrw_fname:
928 self._tools.Run('cbfstool', [
929 cb_copy, 'add', '-f', self.pdrw_fname, '-t', 'raw',
Patrick Georgi10690b42015-11-20 22:06:38 +0100930 '-n', 'pdrw', '-A', 'sha256', '-r', fmap_dst ])
Patrick Georgi964fb542015-10-16 16:52:03 +0200931
Patrick Georgi10ea5ef2015-10-22 19:14:26 +0200932 # add files to CBFS in RW regions more flexibly:
933 # rw-a-boot {
934 # ...
935 # cbfs-files {
936 # ecfoo = "add -n ecrw-copy -f ec.RW.bin -t raw -A sha256";
937 # };
938 # };
939 # adds a file called "ecrw-copy" of raw type to FW_MAIN_A with the
940 # content of ec.RW.bin in the build root, with a SHA256 hash.
941 # The dts property name ("ecfoo") is ignored but should be unique,
Patrick Georgi8ec72552016-01-13 17:27:34 +0100942 # all cbfstool commands that start with "add" are allowed, as is "remove".
Patrick Georgi10ea5ef2015-10-22 19:14:26 +0200943 # The second and third argument need to be "-n <cbfs file name>".
944 if cbfs_config != None:
945 # remove all files slated for addition, in case they already exist
946 for val in cbfs_config.itervalues():
947 f = val.split(' ')
948 command = f[0]
Patrick Georgib6886bc2016-01-12 16:43:11 +0100949 if command[:3] != 'add' and command != 'remove':
950 raise CmdError("'%s' doesn't add or remove a file", f)
Patrick Georgi10ea5ef2015-10-22 19:14:26 +0200951 if f[1] != '-n':
952 raise CmdError("second argument in '%s' must be '-n'", f)
953 cbfsname = f[2]
954 try:
Patrick Georgie920c2b2015-12-10 21:59:56 +0100955 # Calling through shell isn't strictly necessary here, but we still
956 # do it to keep operation more similar to the invocation in the next
957 # loop.
958 self._tools.Run('sh', [ '-c',
Patrick Georgi10690b42015-11-20 22:06:38 +0100959 ' '.join(['cbfstool', cb_copy, 'remove', '-r', fmap_dst,
Patrick Georgie920c2b2015-12-10 21:59:56 +0100960 '-n', cbfsname]) ])
Patrick Georgi10ea5ef2015-10-22 19:14:26 +0200961 except CmdError:
962 pass # the most likely error is that the file doesn't already exist
963
964 # now add the files
965 for val in cbfs_config.itervalues():
966 f = val.split(' ')
967 command = f[0]
968 cbfsname = f[2]
969 args = f[3:]
Patrick Georgib6886bc2016-01-12 16:43:11 +0100970 if command == 'remove':
971 continue
Patrick Georgie920c2b2015-12-10 21:59:56 +0100972 # Call through shell so variable expansion can happen. With a change
973 # to the ebuild this enables specifying filename arguments to
974 # cbfstool as -f romstage.elf${COREBOOT_VARIANT} and have that be
975 # resolved to romstage.elf.serial when appropriate.
976 self._tools.Run('sh', [ '-c',
Patrick Georgi10690b42015-11-20 22:06:38 +0100977 ' '.join(['cbfstool', cb_copy, command, '-r', fmap_dst,
Patrick Georgie920c2b2015-12-10 21:59:56 +0100978 '-n', cbfsname] + args)],
979 self._tools.Filename(self._GetBuildRoot()))
Patrick Georgi10ea5ef2015-10-22 19:14:26 +0200980
Vadim Bendeburyc9600c62014-12-22 16:31:13 -0800981 # And extract the blob for the FW section
982 rw_section = os.path.join(self._tools.outdir, '_'.join(part_sections))
983 self._tools.WriteFile(rw_section,
984 self._tools.ReadFile(cb_copy)[base:base+size])
985
986 pack.AddProperty(blob_name, rw_section)
987
988
Simon Glass439fe7a2012-03-09 16:19:34 -0800989 def _BuildBlob(self, pack, fdt, blob_type):
990 """Build the blob data for a particular blob type.
991
992 Args:
Vadim Bendebury7dac18c2014-05-06 14:13:35 -0700993 pack: a PackFirmware object describing the firmware image to build.
994 fdt: an fdt object including image layout information
Simon Glass439fe7a2012-03-09 16:19:34 -0800995 blob_type: The type of blob to create data for. Supported types are:
996 coreboot A coreboot image (ROM plus U-boot and .dtb payloads).
997 signed Nvidia T20/T30 signed image (BCT, U-Boot, .dtb).
Vadim Bendebury507c0012013-06-09 12:49:25 -0700998
999 Raises:
1000 CmdError if a command fails.
Aaron Durbin41c85b62015-12-17 17:40:29 -06001001 BlobDeferral if a blob is waiting for a dependency.
Simon Glass439fe7a2012-03-09 16:19:34 -08001002 """
Vadim Bendebury7bfdb372013-03-27 11:52:58 -07001003 # stupid pylint insists that sha256 is not in hashlib.
1004 # pylint: disable=E1101
Simon Glass439fe7a2012-03-09 16:19:34 -08001005 if blob_type == 'coreboot':
Aaron Durbin5751c3e2016-01-04 11:45:22 -06001006 self._CreateCorebootStub(pack, self.coreboot_fname)
Stefan Reinauer9ad54842012-10-10 12:25:23 -07001007 elif blob_type == 'legacy':
1008 pack.AddProperty('legacy', self.seabios_fname)
Simon Glass439fe7a2012-03-09 16:19:34 -08001009 elif blob_type == 'signed':
1010 bootstub, signed = self._CreateBootStub(self.uboot_fname, fdt,
1011 self.postload_fname)
1012 pack.AddProperty('bootstub', bootstub)
1013 pack.AddProperty('signed', signed)
1014 pack.AddProperty('image', signed)
Simon Glass7e199222012-03-13 15:51:18 -07001015 elif blob_type == 'exynos-bl1':
1016 pack.AddProperty(blob_type, self.exynos_bl1)
Simon Glassbe0bc002012-08-16 12:50:48 -07001017
1018 # TODO(sjg@chromium.org): Deprecate ecbin
1019 elif blob_type in ['ecrw', 'ecbin']:
1020 pack.AddProperty('ecrw', self.ecrw_fname)
1021 pack.AddProperty('ecbin', self.ecrw_fname)
Randall Spangler7307da92014-07-18 12:47:34 -07001022 elif blob_type == 'pdrw':
1023 pack.AddProperty('pdrw', self.pdrw_fname)
Gabe Blackcdbdfe12013-02-06 05:37:52 -08001024 elif blob_type == 'ecrwhash':
1025 ec_hash_file = os.path.join(self._tools.outdir, 'ec_hash.bin')
1026 ecrw = self._tools.ReadFile(self.ecrw_fname)
1027 hasher = hashlib.sha256()
1028 hasher.update(ecrw)
1029 self._tools.WriteFile(ec_hash_file, hasher.digest())
1030 pack.AddProperty(blob_type, ec_hash_file)
Randall Spangler7307da92014-07-18 12:47:34 -07001031 elif blob_type == 'pdrwhash':
1032 pd_hash_file = os.path.join(self._tools.outdir, 'pd_hash.bin')
1033 pdrw = self._tools.ReadFile(self.pdrw_fname)
1034 hasher = hashlib.sha256()
1035 hasher.update(pdrw)
1036 self._tools.WriteFile(pd_hash_file, hasher.digest())
1037 pack.AddProperty(blob_type, pd_hash_file)
Simon Glassbe0bc002012-08-16 12:50:48 -07001038 elif blob_type == 'ecro':
Simon Glass693b40f2012-08-28 10:51:05 -07001039 # crosbug.com/p/13143
1040 # We cannot have an fmap in the EC image since there can be only one,
1041 # which is the main fmap describing the whole image.
1042 # Ultimately the EC will not have an fmap, since with software sync
1043 # there is no flashrom involvement in updating the EC flash, and thus
1044 # no need for the fmap.
1045 # For now, mangle the fmap name to avoid problems.
1046 updated_ecro = os.path.join(self._tools.outdir, 'updated-ecro.bin')
1047 data = self._tools.ReadFile(self.ecro_fname)
1048 data = re.sub('__FMAP__', '__fMAP__', data)
1049 self._tools.WriteFile(updated_ecro, data)
1050 pack.AddProperty(blob_type, updated_ecro)
Simon Glass0a047bc2013-07-19 15:44:43 -06001051 elif blob_type.startswith('exynos-bl2'):
1052 # We need to configure this per node, so do it later
1053 pass
Aaron Durbin80564452015-12-21 15:25:06 -06001054 elif blob_type.startswith('cbfshash'):
1055 self._PrepareCbfsHash(pack, blob_type)
Vadim Bendeburyc9600c62014-12-22 16:31:13 -08001056 elif blob_type.startswith('cbfs'):
1057 self._PrepareCbfs(pack, blob_type)
Simon Glass439fe7a2012-03-09 16:19:34 -08001058 elif pack.GetProperty(blob_type):
1059 pass
Che-Liang Chiou3bc344c2013-02-21 15:18:03 -08001060 elif blob_type in self.blobs:
1061 pack.AddProperty(blob_type, self.blobs[blob_type])
Simon Glass439fe7a2012-03-09 16:19:34 -08001062 else:
1063 raise CmdError("Unknown blob type '%s' required in flash map" %
1064 blob_type)
1065
Aaron Durbin41c85b62015-12-17 17:40:29 -06001066 def _BuildBlobs(self, pack, fdt):
1067 """Build the blob data for the list of blobs in the pack.
1068
1069 Args:
1070 pack: a PackFirmware object describing the firmware image to build.
1071 fdt: an fdt object including image layout information
1072
1073 Raises:
1074 CmdError if a command fails.
1075 BlobDeferral if dependencies cannot be met because of cycles.
1076 """
1077 blob_list = pack.GetBlobList()
1078 self._out.Info('Building blobs %s\n' % blob_list)
1079
1080 complete = False
1081 deferred_list = []
1082
1083 # Build blobs allowing for dependencies between blobs. While this is
1084 # an potential O(n^2) operation, in practice most blobs aren't dependent
1085 # and should resolve in a few passes.
1086 while not complete:
1087 orig = set(blob_list)
1088 for blob_type in blob_list:
1089 try:
1090 self._BuildBlob(pack, fdt, blob_type)
1091 except (BlobDeferral):
1092 deferred_list.append(blob_type)
1093 if not deferred_list:
1094 complete = True
1095 # If deferred is the same as the original no progress is being made.
1096 if not orig - set(deferred_list):
1097 raise BlobDeferral("Blob cyle '%s'" % orig)
1098 # Process the deferred blobs
1099 blob_list = deferred_list[:]
1100 deferred_list = []
1101
Simon Glass290a1802011-07-17 13:54:32 -07001102 def _CreateImage(self, gbb, fdt):
Simon Glass89b86b82011-07-17 23:49:49 -07001103 """Create a full firmware image, along with various by-products.
1104
1105 This uses the provided u-boot.bin, fdt and bct to create a firmware
1106 image containing all the required parts. If the GBB is not supplied
1107 then this will just return a signed U-Boot as the image.
1108
1109 Args:
Vadim Bendebury7dac18c2014-05-06 14:13:35 -07001110 gbb: a string, full path to the GBB file, or empty if a GBB is not
1111 required.
1112 fdt: an fdt object containing required information.
Simon Glasse13ee2c2011-07-28 08:12:28 +12001113
1114 Returns:
1115 Path to image file
Simon Glass89b86b82011-07-17 23:49:49 -07001116 """
Simon Glass02d124a2012-03-02 14:47:20 -08001117 self._out.Notice("Model: %s" % fdt.GetString('/', 'model'))
Simon Glass89b86b82011-07-17 23:49:49 -07001118
Simon Glass439fe7a2012-03-09 16:19:34 -08001119 pack = PackFirmware(self._tools, self._out)
Simon Glassb8c6d952012-12-01 06:14:35 -08001120 if self._force_rw:
Vadim Bendebury7bfdb372013-03-27 11:52:58 -07001121 fdt.PutInteger('/flash/rw-a-vblock', 'preamble-flags', 0)
1122 fdt.PutInteger('/flash/rw-b-vblock', 'preamble-flags', 0)
Simon Glass00d027e2013-07-20 14:51:12 -06001123 if self._force_efs:
1124 fdt.PutInteger('/chromeos-config', 'early-firmware-selection', 1)
Simon Glassa7e66e22013-07-23 07:21:16 -06001125 pack.use_efs = fdt.GetInt('/chromeos-config', 'early-firmware-selection',
1126 0)
Simon Glassb8c6d952012-12-01 06:14:35 -08001127
Simon Glass4f318912013-07-20 16:13:06 -06001128 pack.SelectFdt(fdt, self._board)
Simon Glass439fe7a2012-03-09 16:19:34 -08001129
1130 # Get all our blobs ready
Vadim Bendebury466a7d82014-12-22 10:08:58 -08001131 if self.uboot_fname:
1132 pack.AddProperty('boot', self.uboot_fname)
Simon Glass284cb892013-02-09 13:38:03 -08001133 if self.skeleton_fname:
1134 pack.AddProperty('skeleton', self.skeleton_fname)
Simon Glass3b85f712012-06-21 07:06:46 -07001135 pack.AddProperty('dtb', fdt.fname)
Simon Glass50f74602012-03-15 21:04:25 -07001136
Simon Glassde9c8072012-07-02 22:29:02 -07001137 # If we are writing a kernel, add its offset from TEXT_BASE to the fdt.
1138 if self.kernel_fname:
1139 fdt.PutInteger('/config', 'kernel-offset', pack.image_size)
1140
Vadim Bendebury466a7d82014-12-22 10:08:58 -08001141 if gbb:
1142 pack.AddProperty('gbb', gbb)
Aaron Durbin41c85b62015-12-17 17:40:29 -06001143
1144 # Build the blobs out.
1145 self._BuildBlobs(pack, fdt)
Simon Glass89b86b82011-07-17 23:49:49 -07001146
Simon Glass7306b902012-12-17 15:06:21 -08001147 self._out.Progress('Packing image')
Simon Glass89b86b82011-07-17 23:49:49 -07001148 if gbb:
Simon Glasse76bf7b2012-03-13 15:34:41 -07001149 pack.RequireAllEntries()
Hung-Te Lina7462e72011-07-27 19:17:10 +08001150 fwid = '.'.join([
Simon Glass02d124a2012-03-02 14:47:20 -08001151 re.sub('[ ,]+', '_', fdt.GetString('/', 'model')),
Hung-Te Lina7462e72011-07-27 19:17:10 +08001152 self._tools.GetChromeosVersion()])
Simon Glass89b86b82011-07-17 23:49:49 -07001153 self._out.Notice('Firmware ID: %s' % fwid)
Simon Glass439fe7a2012-03-09 16:19:34 -08001154 pack.AddProperty('fwid', fwid)
Simon Glass439fe7a2012-03-09 16:19:34 -08001155 pack.AddProperty('keydir', self._keydir)
Simon Glassc90cf582012-03-13 15:40:47 -07001156
Simon Glass0a047bc2013-07-19 15:44:43 -06001157 # Some blobs need to be configured according to the node they are in.
Simon Glass4c24f662013-07-19 15:53:02 -06001158 todo = pack.GetMissingBlobs()
1159 for blob in todo:
Simon Glass0a047bc2013-07-19 15:44:43 -06001160 if blob.key.startswith('exynos-bl2'):
1161 bl2 = ExynosBl2(self._tools, self._out)
1162 pack.AddProperty(blob.key, bl2.MakeSpl(pack, fdt, blob,
1163 self.exynos_bl2))
1164
Simon Glassc90cf582012-03-13 15:40:47 -07001165 pack.CheckProperties()
Simon Glass8884b982012-06-21 12:41:41 -07001166
1167 # Record position and size of all blob members in the FDT
Gabe Blackcc22d772013-02-04 23:12:02 -08001168 pack.UpdateBlobPositionsAndHashes(fdt)
Simon Glass8884b982012-06-21 12:41:41 -07001169
Simon Glass4c24f662013-07-19 15:53:02 -06001170 # Recalculate the Exynos BL2, since it may have a hash. The call to
1171 # UpdateBlobPositionsAndHashes() may have updated the hash-target so we
1172 # need to recalculate the hash.
1173 for blob in todo:
1174 if blob.key.startswith('exynos-bl2'):
1175 bl2 = ExynosBl2(self._tools, self._out)
1176 pack.AddProperty(blob.key, bl2.MakeSpl(pack, fdt, blob,
1177 self.exynos_bl2))
1178
Simon Glass6207efe2012-12-17 15:04:36 -08001179 # Make a copy of the fdt for the bootstub
1180 fdt_data = self._tools.ReadFile(fdt.fname)
Vadim Bendebury466a7d82014-12-22 10:08:58 -08001181 if self.uboot_fname:
1182 uboot_data = self._tools.ReadFile(self.uboot_fname)
1183 uboot_copy = os.path.join(self._tools.outdir, 'u-boot.bin')
1184 self._tools.WriteFile(uboot_copy, uboot_data)
Simon Glass6207efe2012-12-17 15:04:36 -08001185
Vadim Bendebury466a7d82014-12-22 10:08:58 -08001186 uboot_dtb = os.path.join(self._tools.outdir, 'u-boot-dtb.bin')
1187 self._tools.WriteFile(uboot_dtb, uboot_data + fdt_data)
Simon Glass6207efe2012-12-17 15:04:36 -08001188
Simon Glassa10282a2013-01-08 17:06:41 -08001189 # Fix up the coreboot image here, since we can't do this until we have
1190 # a final device tree binary.
Aaron Durbin41c85b62015-12-17 17:40:29 -06001191 if 'coreboot' in pack.GetBlobList():
Simon Glasscbc83552012-07-23 15:26:22 +01001192 bootstub = pack.GetProperty('coreboot')
1193 fdt = fdt.Copy(os.path.join(self._tools.outdir, 'bootstub.dtb'))
Simon Glassa10282a2013-01-08 17:06:41 -08001194 if self.coreboot_elf:
1195 self._tools.Run('cbfstool', [bootstub, 'add-payload', '-f',
1196 self.coreboot_elf, '-n', 'fallback/payload', '-c', 'lzma'])
Vadim Bendebury466a7d82014-12-22 10:08:58 -08001197 elif self.uboot_fname:
Simon Glass0a7cf112013-05-21 23:08:21 -07001198 text_base = 0x1110000
1199
1200 # This is the the 'movw $GD_FLG_COLD_BOOT, %bx' instruction
1201 # 1110015: 66 bb 00 01 mov $0x100,%bx
1202 marker = struct.pack('<L', 0x0100bb66)
1203 pos = uboot_data.find(marker)
1204 if pos == -1 or pos > 0x100:
1205 raise ValueError('Cannot find U-Boot cold boot entry point')
1206 entry = text_base + pos
1207 self._out.Notice('U-Boot entry point %#08x' % entry)
Simon Glassa10282a2013-01-08 17:06:41 -08001208 self._tools.Run('cbfstool', [bootstub, 'add-flat-binary', '-f',
1209 uboot_dtb, '-n', 'fallback/payload', '-c', 'lzma',
Simon Glass0a7cf112013-05-21 23:08:21 -07001210 '-l', '%#x' % text_base, '-e', '%#x' % entry])
Stefan Reinauer1502ea62012-11-01 10:15:38 -07001211 self._tools.Run('cbfstool', [bootstub, 'add', '-f', fdt.fname,
1212 '-n', 'u-boot.dtb', '-t', '0xac'])
Simon Glassb8ea1802012-12-17 15:08:00 -08001213 data = self._tools.ReadFile(bootstub)
1214 bootstub_copy = os.path.join(self._tools.outdir, 'coreboot-8mb.rom')
1215 self._tools.WriteFile(bootstub_copy, data)
Vadim Bendebury9f36e712014-06-12 13:37:59 -07001216
Julius Werneraa1fe942014-11-21 17:16:11 -08001217 # Use offset and size from fmap.dts to extract CBFS area from coreboot.rom
1218 cbfs_offset, cbfs_size = fdt.GetFlashPart('ro', 'boot')
1219 self._tools.WriteFile(bootstub, data[cbfs_offset:cbfs_offset+cbfs_size])
Simon Glasscbc83552012-07-23 15:26:22 +01001220
Simon Glass208ad952013-02-10 11:16:46 -08001221 pack.AddProperty('fdtmap', fdt.fname)
Simon Glassc90cf582012-03-13 15:40:47 -07001222 image = os.path.join(self._tools.outdir, 'image.bin')
1223 pack.PackImage(self._tools.outdir, image)
1224 pack.AddProperty('image', image)
Simon Glass89b86b82011-07-17 23:49:49 -07001225
Simon Glass439fe7a2012-03-09 16:19:34 -08001226 image = pack.GetProperty('image')
Simon Glass89b86b82011-07-17 23:49:49 -07001227 self._tools.OutputSize('Final image', image)
Simon Glassc90cf582012-03-13 15:40:47 -07001228 return image, pack
Simon Glass89b86b82011-07-17 23:49:49 -07001229
Simon Glassdedda6f2013-02-09 13:44:14 -08001230 def SelectFdt(self, fdt_fname, use_defaults):
Simon Glass290a1802011-07-17 13:54:32 -07001231 """Select an FDT to control the firmware bundling
1232
Simon Glassdedda6f2013-02-09 13:44:14 -08001233 We make a copy of this which will include any on-the-fly changes we want
1234 to make.
1235
Simon Glass290a1802011-07-17 13:54:32 -07001236 Args:
1237 fdt_fname: The filename of the fdt to use.
Simon Glassdedda6f2013-02-09 13:44:14 -08001238 use_defaults: True to use a default FDT name if available, and to add
1239 a full path to the provided filename if necessary.
Simon Glass290a1802011-07-17 13:54:32 -07001240
Simon Glassc0f3dc62011-08-09 14:19:05 -07001241 Returns:
1242 The Fdt object of the original fdt file, which we will not modify.
1243
Simon Glassdedda6f2013-02-09 13:44:14 -08001244 Raises:
1245 ValueError if no FDT is provided (fdt_fname is None and use_defaults is
1246 False).
Simon Glass290a1802011-07-17 13:54:32 -07001247 """
Simon Glassdedda6f2013-02-09 13:44:14 -08001248 if use_defaults:
1249 fdt_fname = self._CheckFdtFilename(fdt_fname)
Simon Glass22f39fb2013-02-09 13:44:14 -08001250 if not fdt_fname:
1251 raise ValueError('Please provide an FDT filename')
1252 fdt = Fdt(self._tools, fdt_fname)
Simon Glass290a1802011-07-17 13:54:32 -07001253 self._fdt_fname = fdt_fname
Simon Glassc3e42c32012-12-17 15:00:04 -08001254
1255 # For upstream, select the correct architecture .dtsi manually.
1256 if self._board == 'link' or 'x86' in self._board:
1257 arch_dts = 'coreboot.dtsi'
1258 elif self._board == 'daisy':
1259 arch_dts = 'exynos5250.dtsi'
1260 else:
Rhyland Kleinc2df3ca2014-01-06 15:15:34 -05001261 arch_dts = 'tegra124.dtsi'
Simon Glassc3e42c32012-12-17 15:00:04 -08001262
1263 fdt.Compile(arch_dts)
Simon Glasse53abbc2013-08-21 22:29:55 -06001264 fdt = fdt.Copy(os.path.join(self._tools.outdir, 'updated.dtb'))
1265
1266 # Get the flashmap so we know what to build. For board variants use the
1267 # main board name as the key (drop the _<variant> suffix).
1268 default_flashmap = default_flashmaps.get(self._board.split('_')[0], [])
1269
1270 if not fdt.GetProp('/flash', 'reg', ''):
1271 fdt.InsertNodes(default_flashmap)
1272
Rhyland Kleinc2df3ca2014-01-06 15:15:34 -05001273 # Only check for /iram and /config nodes for boards that require it.
1274 if self._board in ('daisy', 'peach'):
1275 # Insert default values for any essential properties that are missing.
1276 # This should only happen for upstream U-Boot, until our changes are
1277 # upstreamed.
1278 if not fdt.GetProp('/iram', 'reg', ''):
1279 self._out.Warning('Cannot find /iram, using default')
1280 fdt.InsertNodes([i for i in default_flashmap if i['path'] == '/iram'])
Simon Glasse53abbc2013-08-21 22:29:55 -06001281
Rhyland Kleinc2df3ca2014-01-06 15:15:34 -05001282 # Sadly the pit branch has an invalid /memory node. Work around it
1283 # for now. crosbug.com/p/22184
1284 if (not fdt.GetProp('/memory', 'reg', '') or
1285 fdt.GetIntList('/memory', 'reg')[0] == 0):
1286 self._out.Warning('Cannot find /memory, using default')
1287 fdt.InsertNodes([i for i in default_flashmap if i['path'] == '/memory'])
Simon Glasse53abbc2013-08-21 22:29:55 -06001288
Rhyland Kleinc2df3ca2014-01-06 15:15:34 -05001289 if not fdt.GetProp('/config', 'samsung,bl1-offset', ''):
1290 self._out.Warning('Missing properties in /config, using defaults')
1291 fdt.InsertNodes([i for i in default_flashmap if i['path'] == '/config'])
Simon Glasse53abbc2013-08-21 22:29:55 -06001292
Simon Glass7df773b2013-08-25 18:02:29 -06001293 # Remember our board type.
1294 fdt.PutString('/chromeos-config', 'board', self._board)
1295
Simon Glasse53abbc2013-08-21 22:29:55 -06001296 self.fdt = fdt
1297 return fdt
Simon Glass290a1802011-07-17 13:54:32 -07001298
Simon Glassc90cf582012-03-13 15:40:47 -07001299 def Start(self, hardware_id, output_fname, show_map):
Simon Glass290a1802011-07-17 13:54:32 -07001300 """This creates a firmware bundle according to settings provided.
Simon Glass89b86b82011-07-17 23:49:49 -07001301
1302 - Checks options, tools, output directory, fdt.
1303 - Creates GBB and image.
Simon Glass290a1802011-07-17 13:54:32 -07001304
1305 Args:
Simon Glass56577572011-07-19 11:08:06 +12001306 hardware_id: Hardware ID to use for this board. If None, then the
1307 default from the Fdt will be used
Simon Glass290a1802011-07-17 13:54:32 -07001308 output_fname: Output filename for the image. If this is not None, then
1309 the final image will be copied here.
Simon Glassc90cf582012-03-13 15:40:47 -07001310 show_map: Show a flash map, with each area's name and position
Simon Glass290a1802011-07-17 13:54:32 -07001311
1312 Returns:
1313 Filename of the resulting image (not the output_fname copy).
Simon Glass89b86b82011-07-17 23:49:49 -07001314 """
Vadim Bendebury5baeec12013-04-02 13:01:22 -07001315 if self._small or self.fdt.GetProp('/config', 'nogbb', 'any') != 'any':
1316 gbb = '' # Building a small image or `nogbb' is requested in device tree.
1317 else:
Simon Glass56577572011-07-19 11:08:06 +12001318 gbb = self._CreateGoogleBinaryBlock(hardware_id)
Simon Glass89b86b82011-07-17 23:49:49 -07001319
1320 # This creates the actual image.
Simon Glassc90cf582012-03-13 15:40:47 -07001321 image, pack = self._CreateImage(gbb, self.fdt)
1322 if show_map:
1323 pack.ShowMap()
Simon Glass290a1802011-07-17 13:54:32 -07001324 if output_fname:
1325 shutil.copyfile(image, output_fname)
1326 self._out.Notice("Output image '%s'" % output_fname)
Simon Glass794217e2012-06-07 11:40:37 -07001327 return image, pack.props