1#! /bin/sh -e
2# Copyright (c) 2010 The Chromium OS Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5#
6# Finds the largest NV space that can be defined on the TPM in this state
7# (i.e. without removing existing spaces).
8#
9# The TPM must be unowned, and physical presence must be on.
10
11low=1
12high=1500
13try=$high
14
15# Binary search with no upper bound
16while true; do
17  ## echo trying $try [ $low $high ]
18  if /usr/bin/tpmc definespace 0xf004 $(printf "0x%x" $try) 0x1 \
19                                                      > /dev/null 2>&1; then
20    # definespace success: end, or $try must grow
21    if [ $try -eq $low ]; then
22      echo $low
23      exit 0
24    elif [ $try -lt $high ]; then
25      low=$try
26      try=$(( ( $high + $low ) / 2 ))
27    else
28      # special case: when try == high, expand the search
29      low=$try
30      try=$(( $try * 2 ))
31      high=$try
32    fi
33  else
34    # check for unexpected errors
35    result=$?
36    if [ $result -ne 17 ]; then
37      echo running tpmc definespace 0xf004 0x1 0x1
38      /usr/bin/tpmc definespace 0xf004 0x1 0x1
39      echo please correct this condition and try again
40      exit 1
41    fi
42    # definespace failure: end, or $try must shrink
43    if [ $try -eq $low ]; then
44      echo 0
45      exit 0
46    fi
47    high=$try
48    try=$(( ( $high + $low ) / 2 ))
49  fi
50done
51