#!/usr/bin/env python
#
# Ensure that the MTRR registers are set up appropriately for best performance
# of the InfiniPath driver.
#
#  Copyright (c) 2013 Intel Corporation, All rights reserved. 
#  Copyright 2008, QLogic Corporation.  All rights reserved.
#
#  Permission is granted to Intel customers to use this software in source and
#  binary forms, with or without modification, provided that the following
#  conditions are met: 
#  
#  * All copies of source code must retain the above copyright notice, this
#    list of conditions and the following disclaimer. 
#  
#  * Customer has a valid license agreement from Intel Corporation for the 
#    software product with which this software is originally distributed. 
#  
#  * Redistribution of original or modified versions to third parties is 
#    prohibited without specific prior written permission of Intel
#    Corporation. 
#  
#  * If customer makes modifications to this software, and provides those 
#    modifications to Intel, customer assigns to Intel Corporation ownership
#    of the provided modifications and all intellectual property rights
#    embodied in those modifications. 
#  
#  * The name of Intel Corporation may not be used to endorse or promote 
#    products derived from this software without specific prior written
#    permission. 
#  
#  THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION AND ITS LICENSORS "AS IS"
#  AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
#  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
#  ARE DISCLAIMED.  IN NO EVENT SHALL INTEL CORPORATION OR ITS LICENSORS BE
#  LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
#  CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
#  SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
#  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
#  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
#  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
#  POSSIBILITY OF SUCH DAMAGE. 
#
import os
import re
import sys
import signal
import syslog


# Variables for options.
#
MaxRegs         = 8
ScriptFile      = None
Optimize        = True
DoBugHiMtrr     = True
DoInfiniPath    = True
Force           = False
Verbose         = False
ShowExec        = False
UseSyslog       = False
WriteMtrr       = False
ForceAnyway     = False
InitModprobe    = False


# Static variables.
#
NoHCAs          = 0
Handle          = 1
UnMappedMem     = 0
AddList         = []
DelList         = []
MtrrSlots       = []
MtrrText        = ''
RegsUsed        = None
MtrrMods        = None
AMD             = False
DefModeWB       = False
SeenCpuData     = False
SeenMtrrData    = False
SeenLspciData   = False
FoundAmdIssue   = False
FoundHiMtrrBug  = False


# Main program.
#
def main():
    signal.signal(signal.SIGINT, goodbye)
    parse_args()
    if InitModprobe:
        write_init_modprobe()
    else:
        fix_mtrr()


# Leave silently.
#
def goodbye(signo, frame):
    sys.exit(1)


# Parse arguments.
#
def parse_args():
    global Force
    global Verbose
    global MaxRegs
    global ShowExec
    global Optimize
    global UseSyslog
    global WriteMtrr
    global ScriptFile
    global DoBugHiMtrr
    global ForceAnyway
    global DoInfiniPath
    global InitModprobe

    argz = [1, sys.argv]
    filenames = []
    while 1:
        arg = arg_seq(argz)
        if arg is None:
            break
        elif arg in ('-f', '--force'):
            Force = True;
        elif arg in ('-ff', '--force_anyway'):
            ForceAnyway = True;
        elif arg in ('-h', '--help'):
            usage()
        elif arg in ('-l', '--lspci_file'):
            filenames.append(arg_one(argz))
        elif arg in ('-m', '--mtrr_file'):
            filenames.append(arg_one(argz))
        elif arg in ('-nh', '--no_hi_mtrr_bug'):
            DoBugHiMtrr =  False
        elif arg in ('-ni', '--no_infinipath'):
            DoInfiniPath = False
        elif arg in ('-no', '--no_optimize'):
            Optimize = False
        elif arg in ('-r', '--max_registers'):
            MaxRegs = arg_pos(argz)
        elif arg in ('-s', '--script_file'):
            ScriptFile = arg_one(argz)
        elif arg in ('-v', '--verbose'):
            Verbose = True
        elif arg in ('-w', '--write_mtrr'):
            WriteMtrr = True
        elif arg in ('-x', '--show_exec'):
            ShowExec = True
        elif arg in ('-I', '--init_modprobe'):
            InitModprobe = True
        elif arg in ('-S', '--use_syslog'):
            UseSysLog = True
        elif arg[0:1] == '-':
            panic('unknown option: %s; try: ipath_mtrr --help' % arg)
        else:
            filenames.append(arg)

    if not filenames:
        read_all(None)
    else:
        for filename in filenames:
            read_all(filename)

    if InitModprobe:
        if (filenames or Force or ForceAnyway or
                ScriptFile or ShowExec or WriteMtrr):
            panic('-I should not be used with other options')

    if not SeenMtrrData:
        panic('no MTRR registers; need output of cat /proc/mtrr')
    if not SeenLspciData and DoInfiniPath:
        warning('no lspci information; need output of lspci -vvv')
    if not SeenCpuData:
        warning('no cpuinfo; need output of cat /proc/cpuinfo')
    if WriteMtrr:
        if filenames:
            panic('-w cannot be used with remote data; probably want -s')

    if UseSyslog:
        if WriteMtrr:
            syslog.openlog("ipath_mtrr")
        else:
            UseSyslog = False


# Allow everyone to extract their information from a file.
#
def read_all(filename):
    read_mtrr(filename)
    read_lspci(filename)
    read_cpuinfo(filename)


# Return the next argument ensuring it is a positive integer.
#
def arg_pos(argz):
    (i, argv) = argz
    arg = arg_one(argz)
    try:
        n = int(arg)
    except ValueError:
        panic('argument to %s must be a positive integer' % argv[i-1])
    if n <= 0:
        panic('argument to %s must be a positive integer' % argv[i-1])
    return n


# Return the next argument and complain if it is not there.
#
def arg_one(argz):
    (i, argv) = argz
    arg = arg_seq(argz)
    if arg is None:
        panic('%s requires an argument' % argv[i-1])
    return arg


# Return the next argument and move our list forward.
#
def arg_seq(argz):
    (i, argv) = argz
    if i >= len(argv):
        return None
    argz[0] += 1
    return argv[i]


# Print out a usage message and exit.
#
def usage():
    s = '''
        Usage
            ipath_mtrr OPTIONS FILES
        Description
            Set the MTRR registers to enable maximum performance from the
            InfiniPath driver.  This must be run as root.  Most common usage is
                ipath_mtrr -w
            If one specifies files, they are assumed to contain data from a
            remote machine.  ipath_mtrr needs the output of
                cat /proc/mtrr
                cat /proc/cpuinfo
                lspci -vvv
            This output may be placed in several files or appended into one
            file.  If these files are specified, -w can no longer be used as it
            will change the settings on the current machines.  In that case,
            one probably wants to use the -s option.
        Options
            -f, --force
                Used in conjunction with -w.  Force -w to update the MTRR
                registers even if it results in leaving some memory mapped as
                uncachable which was intended to be write-back.
            -ff, --force_anyway
                Used in conjunction with -w.  Force -w to update the MTRR
                registers even if it might crash your system.
            -h, --help
                Show this help information.
            -nh, --no_hi_mtrr_bug
                Do not attempt to fix the bug where the MTRR registers are set
                incorrectly due to the expansion of some registers from 36 to
                38 bits on some of the newer processors.
            -ni, --no_infinipath
                Do not attempt to ensure that the memory used by the InfiniPath
                driver is settable as write-combining.
            -no, --no_optimize
                Do not Attempt to minimize and clean up the MTRR registers that
                are being used.
            -r, --max_registers N
                Assume the maximum number of MTRR registers that are settable
                is N.  Default is 8.
            -s, --script_file File
                Create a script in File that contains the commands to set the
                MTRR registers.
            -v, --verbose
                Turn on verbose mode.
            -w, --write_mtrr
                Actually cause the MTRR registers to be changed.  This option
                must be specified in order to fixup the MTRR registers if
                necessary.  The default is to just assess the situation.  This
                cannot be used if files are specified which contain data from a
                remote machine.  One probably wants to use -s in that case.
            -x, --show_exec
                Used in conjunction with -w.  Show the change command to the
                MTRR register as it is happening.
            -I, --init_modprobe
                Edit modprobe.conf (modprobe.conf.local for SuSE/SLES or ib_qib.conf
                for RHEL6 and later) to fix MTRR registers at boot time. May not
                be used with other options.  If used with other options, an error
                is generated.
                NOTE: This option may re-insert the content into
                modprobe.conf/modprobe.conf.local/ib_qib.conf if the previously
                inserted line have been edited.
            -S, --syslog
                Used  in  conjunction  with -w. All messages are logged to
                syslog. If not specified, messages go to stdout. This does not
                work on SuSE/SLES systems during early system boot.
    '''
    s = re.sub('^\n*', '', s)
    s = re.sub('(?m)^ {8}', '', s)
    s = s.rstrip() + '\n'
    sys.stdout.write(s)
    sys.exit(0)


# Read MTRR registers.
#
def read_mtrr(filename):
    global RegsUsed
    global MtrrText
    global MtrrSlots
    global SeenMtrrData

    if filename is None:
        filename = '/proc/mtrr'

    try:
        f = file(filename)
    except IOError, msg:
        panic(msg)
    lines = f.readlines()
    f.close()

    pat = re.compile(
          'reg(\d\d):'
        + ' base=0x([0-9a-f]+)'
        + ' \( *\d+.B\),'
        + ' size= *(\d+)([KMG])B:'
        + ' ([a-z-]+),'
        + ' count=(\d+)$'
    )

    found = False
    RegsUsed = 0
    seen = SeenMtrrData
    for line in lines:
        m = pat.match(line)
        if m is None:
            if found:
                return
            else:
                continue
            bad_mtrr(line)
        found = True
        if seen:
            panic('duplicate sets of MTRR registers found')
        SeenMtrrData = True
        MtrrText += line

        try:
            reg  = int(m.group(1))
            base = int(m.group(2), 16)
            size = int(m.group(3))
            unit = m.group(4)
            if unit == 'K':
                size *= 1024
            elif unit == 'M':
                size *= 1024 * 1024
            elif unit == 'G':
                size *= 1024 * 1024 * 1024
            else:
                bad_mtrr(line)
        except ValueError:
            bad_mtrr(line)
        slot = (handle(), reg, base, size, m.group(5),'original reg%02d' % reg)
        MtrrSlots.append(slot)
        RegsUsed += 1


# Complain about not being able to interpret MTRR data.
#
def bad_mtrr(line):
    panic('failed to interpret MTRR register: ' + line.rstrip())


# Read output from lspci.
#
def read_lspci(filename):
    global NoHCAs
    global MaxRegs
    global SeenLspciData

    if not DoInfiniPath:
        return
    if filename is None:
        data = run_command('lspci -vvv')
    else:
        data = read_data(filename)

    if not re.search('(?m)^\d{2}:\d{2}\.\d', data):
        return
    if SeenLspciData:
        panic('duplicate lspci information given')
    SeenLspciData = True

    i = 0
    NoHCAs = 0
    patdev = re.compile('(?m)^[0-9a-f]{2}:[0-9a-f]{2}\.\d\s+InfiniBand: '
                       +'(?:PathScale|QLogic|Intel).*\n(?:[ \t].*\n)*')
    patmem = re.compile('Memory at ([0-9a-z]+).*?\[size=([0-9]+)([A-Z])')
    while 1:
        m = patdev.search(data, i)
        if m is None:
            break
        i = m.end(0)
        m = patmem.search(m.group(0))
        if m is None:
            warning('could not deciper lspci format')
            return
        NoHCAs += 1
        base = int(m.group(1), 16)
        size = mul_unit(m.group(2), m.group(3))
        if not ipath_wc_set(base, size):
            add_slot(base, size, 'write-combining', 'InfiniPath')
            MaxRegs -= 1


# See if one of the write-combining registers is inside of the InfiniPath
# address space.
#
def ipath_wc_set(ibase, isize):
    for slot in get_slots('write-combining'):
        (h, reg, base, size, kind, name) = slot
        if base >= ibase and base+size <= ibase+isize:
            return True
    return False


# Multiply a number by its units.
#
def mul_unit(num, unit):
    try:
        n = int(num)
        if unit == 'K':
            return n * 1024
        if unit == 'M':
            return n * 1024 * 1024
        if unit == 'G':
            return n * 1024 * 1024 * 1024
        raise ValueError
    except ValueError:
        panic('failed to interpret %s%s in %s' % (num, unit, where))


# Read output from /proc/cpuinfo.
#
def read_cpuinfo(filename):
    global AMD
    global SeenCpuData

    if filename is None:
        filename = '/proc/cpuinfo'
    data = read_data(filename)

    if not re.search('(?m)^vendor_id\s*:', data):
        return
    if SeenCpuData:
        panic('duplicate cpuinfo information given')
    SeenCpuData = True

    if re.search('(?m)^vendor_id\s*:\s*.*AMD', data):
        AMD = True


# Read all data from a file.
#
def read_data(filename):
    try:
        f = open(filename)
        data = f.read()
        f.close()
    except IOError, msg:
        panic('failed to read %s: %s' % (filename, msg))
    return data


# Run a command and return its output.
#
def run_command(line):
    line = 'PATH=$PATH:/sbin:/usr/sbin ' + line
    (wf, rf) = os.popen4(line)
    wf.close()
    data = rf.read()
    rf.close()
    return data


# Fix MTRR registers.
#
def fix_mtrr():
    check_def_mode_wb()
    if DoBugHiMtrr:
        fix_bug_hi_mtrr()
    for slot in get_slots('write-back'):
        fix_wb(slot)
    if Optimize:
        clean_uc()
    show_mods()


# See if the default mode in the BIOS might be write-back rather than
# uncachable.
#
def check_def_mode_wb():
    global DefModeWB

    if get_slots('uncachable') and not get_slots('write-back'):
        DefModeWB = True


# Fix MTRR registers due to a bug which sometimes causes bits 36 and 37 to be
# set when they should not be.
#
def fix_bug_hi_mtrr():
    global FoundHiMtrrBug

    big = 1 << 36
    for slot in get_slots(None):
        (h, reg, base, size, kind, name) = slot
        if size >= big:
            FoundHiMtrrBug = True
            del_slot(h, "fixing high mtrr bits bug");
            size = size & (big-1)
            add_slot(base, size, kind, name)


# Fix a write-back entry if necessary.
#
def fix_wb(slot):
    (h, reg, base, size, kind, name) = slot
    (action, why) = wb_status(slot)
    if action == 'keep':
        if h is None:
            add_wb(base, size, kind, name)
        return
    if h is not None:
        del_slot(h, why)
    if action == 'half':
        size2 = size / 2
        fix_wb((None, None, base, size2, kind, name))
        fix_wb((None, None, base+size2, size2, kind, name))


# Get the status of a write-back entry.
#
def wb_status(wbslot):
    (_, wbreg, wbbase, wbsize, _, _) = wbslot
    if wbsize == 0:
        return ('toss', 'zero size')
    wbhigh = wbbase + wbsize

    for slot in get_slots(None):
        (_, _, base, size, kind, name) = slot
        if kind not in ('write-combining', 'write-through'):
            continue
        if size == 0:
            continue
        high = base + size
        if wbbase >= base and wbhigh <= high:
            return ('toss', 'to enable %s' % name)
        if wbbase < high and base < wbhigh:
            return ('half', 'to enable %s' % name)
    ucname = inside_uc(wbbase, wbsize)
    if ucname is not None:
        return ('toss', 'overlapped by %s' % ucname)
    return ('keep', None)


# Add a write-back range.  We could just replace this function with the
# add_slot at the end but instead we make some attempts to see if only half the
# entry is needed.  If so, we might be able to optimize the UC entry later.
#
def add_wb(base, size, kind, name):
    if inside_uc(base, size):
        return
    if Optimize:
        size2 = size / 2
        if inside_uc(base, size2) is not None:
            add_slot(base+size2, size2, kind, name)
            return
        if inside_uc(base+size2, size2) is not None:
            add_slot(base, size2, kind, name)
            return
    add_slot(base, size, kind, name)


# See if a write combining entry is contained in an uncachable entry and if so
# return its name; else None.
#
def inside_uc(wbbase, wbsize):
    wbhigh = wbbase + wbsize
    for slot in get_slots('uncachable'):
        (_, _, base, size, _, name) = slot
        high = base + size
        if wbbase >= base and wbhigh <= high:
            return name
    return None


# Remove any uncachable entries that we can.
#
def clean_uc():
    wblist = map(lambda a:(a[2], a[3]), get_slots('write-back'))
    wblist.sort()
    wblen = len(wblist)
    for slot in get_slots('uncachable'):
        (h, _, base, size, _, _) = slot
        high = base + size
        i = 0
        while i < wblen:
            (l1, h1) = wblist[i]
            if i < wblen-1:
                (l2, h2) = wblist[i+1]
            else:
                (l2, h2) = (high, 0)
            if base >= h1 and high <= l2:
                del_slot(h, 'no longer needed')
                break
            i += 1


# Add a slot.
#
def add_slot(base, size, kind, name):
    MtrrSlots.append((handle(), None, base, size, kind, name))


# Delete a slot.
#
def del_slot(h, why):
    global FoundAmdIssue

    try:
        i = map(lambda a:a[0], MtrrSlots).index(h)
    except ValueError:
        panic('internal error: failed to delete handle %d' % h)
    (_, reg, base, _, kind, _) = MtrrSlots[i]
    if reg is not None:
        if AMD and base == 0 and kind == 'write-back':
            FoundAmdIssue = True
        DelList.append((reg, kind, why))
    del MtrrSlots[i]


# Get the current slots.
#
def get_slots(k):
    slots = []
    for slot in MtrrSlots:
        (h, reg, base, size, kind, name) = slot
        if k is not None and k <> kind:
            continue
        slots.append(slot)
    return slots


# Return a unique handle.
#
def handle():
    global Handle

    h = Handle
    Handle += 1
    return h


# Show modifications.
#
def show_mods():
    global MtrrMods
    global UnMappedMem

    addlist = [
        slot[2:] for slot in get_slots(None)
            if slot[1] == None
            if slot[4] in ('write-back', 'uncachable')
    ]

    MtrrMods = []
    DelList.sort(cmp_del)
    for l in DelList:
        mtrr_del(*l)

    addlist.sort(cmp_add_urgency)
    n = MaxRegs - RegsUsed + len(DelList)
    if n < 0:
        n = 0
    uselist = addlist[:n]
    uselist.sort(cmp_add_address)
    for l in uselist:
        mtrr_add(*l)
    for (base, size, kind, name) in addlist[n:]:
        UnMappedMem += size
    msg = make_msg(addlist, n)

    if not Verbose:
        print_msg(msg.rstrip())
    else:
        indent = '    '
        print_msg('Comments')
        print_msg(addprior(msg, indent))
        print_msg('Original MTRR')
        print_msg(addprior(MtrrText, indent))
        if MtrrMods:
            print_msg('Changes')
            for (command, comment) in MtrrMods:
                print_msg('%s# %s' % (indent, comment))
                print_msg("%secho '%s' >/proc/mtrr" % (indent, command))

    if ScriptFile:
        try:
            f = open(ScriptFile, 'w')
            f.write('#!/bin/sh\n')
            if not MtrrMods:
                f.write('# No changes necessary to MTRR\n')
            else:
                f.write('\n# Original MTRR:\n')
                f.write('%s\n' % addprior(MtrrText, '#   '))
                f.write('\n')
                for (command, comment) in MtrrMods:
                    f.write('# %s\n' % comment)
                    f.write("echo '%s' >/proc/mtrr\n" % command)
                f.write('echo please restart InfiniPath driver\n')
            f.close()
            os.chmod(ScriptFile, 0755)
        except IOError, msg:
            panic('failed to write %s: %s' % (ScriptFile, msg))

    if WriteMtrr:
        if UnMappedMem and not Force:
            panic('must use -f to force write')
        if DefModeWB and not ForceAnyway:
            m  = 'set MTRR default to uncachable in BIOS'
            m += ' or use -ff to force write'
            panic(m)
        if FoundAmdIssue and not ForceAnyway:
            m  = 'set BIOS to discrete MTRR'
            m += ' or use -ff to force write'
            panic(m)
        try:
            for (command, _) in MtrrMods:
                if ShowExec:
                    print_msg('+ echo %s >/proc/mtrr' % command)
                f = open('/proc/mtrr', 'w')
                f.write(command + '\n')
                f.close()
        except IOError, msg:
            panic('failed to write /proc/mtrr: %s' % msg)
        print 'please restart InfiniPath driver'


# Put together the message we print out.
#
def make_msg(addlist, n):
    msg = ''

    # Number of InfiniPath HCAs found
    if NoHCAs == 0:
        msg += 'no InfiniPath HCAs found\n'
    elif NoHCAs == 1:
        msg += 'one InfiniPath HCA found\n'
    elif NoHCAs > 1:
        msg += '%s InfiniPath HCAs found\n' % NoHCAs

    # See if we found the AMD Issue
    if FoundAmdIssue:
        msg += 'issue with AMD processors detected\n'

    # See if we found the MTRR high bits bug
    if FoundHiMtrrBug:
        msg += 'MTRR high bits bug detected\n'

    # See if the MTRR default mode might be write-back
    if DefModeWB:
        msg += 'MTRR default mode might be write-back\n'

    # Show what needs to be done to the MTRR registers
    d = len(DelList)
    a = len(addlist)
    if a > n:
        a = '%d/%d' % (n, a)
    if d and a:
        msg += 'will delete %s and add %s MTRR registers\n' % (d, a)
    elif a:
        msg += 'will add %s MTRR registers\n' % a
    elif d:
        msg += 'will delete %s MTRR registers\n' % d
    else:
        msg += 'no changes necessary to MTRR\n'

    # See if any memory will be left in the wrong mode
    if UnMappedMem:
        s = 'however %s of memory will be uncachable rather than write-back'
        msg += s % nice_size(UnMappedMem)
    return msg


def write_init_modprobe ():
    import re, platform
    distro = version = id = None
    try:
        distro, version, id = platform.dist ()
    except:
        mobj = re.match (".*-with-(.*)", platform.platform ())
        if mobj:
            distro, version, id = mobj.group (1).split ('-', 2)
    del platform, re

    if not distro:
        panic('could not determine distribution')

    add_syslog = " -S"
    modprobe_file = "/etc/modprobe.conf"
    if distro.lower () in ("suse", "sles"):
        add_syslog = ""
        modprobe_file = modprobe_file + ".local"
    elif distro.lower () in ("redhat", "rhel") and version >= '6.0':
        modprobe_file = "/etc/modprobe.d/ib_qib.conf"
        
    add_line = "install ib_qib /bin/ipath_mtrr -v -w%s ; "%add_syslog + \
               "/sbin/modprobe --ignore-install ib_qib $CMDLINE_OPTS " + \
               "# Auto-generated by /bin/ipath_mtrr"
    
    try:
        f = open (modprobe_file)
        content = f.readlines ()
        f.close ()
    except IOError, e:
        panic('Could not read %s: %s'%(modprobe_file, e))

    for line in content:
        if line == add_line:
            # The modprobe line already exists
            return

    try:
        f = open (modprobe_file, 'a')
        f.write (add_line + "\n")
        f.close ()
    except IOError, e:
        panic('Could not write %s: %s'%(modprobe_file, e))
    return


# Compare function for DelList to sort entries.  We delete the write-combining
# and write-through first, the write-back second and the uncachable last.
#
def cmp_del(d1, d2):
    k1 = order_del(d1)
    k2 = order_del(d2)
    if k1 < k2:
        return -1
    if k1 > k2:
        return 1
    return 0


# Return an ordering for a delete entry.
#
def order_del(d):
    (reg, kind, _) = d
    l = ['write-combining', 'write-through', 'write-back', 'uncachable']
    try:
        k = l.index(kind)
    except AttributeError:
        k = len(l)
    return (k, reg)


# Delete a MTRR register.
#
def mtrr_del(reg, kind, msg):
    global MtrrMods

    comment = 'disabling reg%02d: %s' % (reg, msg)
    command = 'disable=%d' % reg
    MtrrMods.append((command, comment))


# Add a MTRR register.
#
def mtrr_add(base, size, kind, name):
    global MtrrMods

    comment = ('setting WB base=%s size=%s: due to %s' %
                                    (nice_size(base), nice_size(size), name))
    command = 'base=0x%x size=0x%x type=%s' % (base, size, kind)
    MtrrMods.append((command, comment))


# Return a readable size.
#
def nice_size(size):
    if size == 0:
        return '0'
    (k, r) = (size / 1024, size % 1024)
    if r <> 0:
        return '%d' % size
    (m, r) = (k / 1024, k % 1024)
    if r <> 0:
        return '%dKB' % k
    (g, r) = (m / 1024, m % 1024)
    if r <> 0:
        return '%dMB' % m
    return '%dGB' % g


# Compare function for AddList to sort entries by importance.  Uncachables are
# more important than write-combining.  Sort by greatest size and then least
# base.
#
def cmp_add_urgency(q1, q2):
    (base1, size1, kind1, _) = q1
    (base2, size2, kind2, _) = q2
    if kind1 < kind2:
        return -1
    if kind1 > kind2:
        return 1
    if size1 > size2:
        return -1
    if size1 < size2:
        return 1
    if base1 < base2:
        return -1
    if base1 > base2:
        return 1
    return 0


# Compare function for AddList to sort entries by base address.
#
def cmp_add_address(q1, q2):
    (base1, _, _, _) = q1
    (base2, _, _, _) = q2
    if base1 < base2:
        return -1
    if base1 > base2:
        return 1
    return 0


# Add the given text at the beginning of each line and remove any trailing
# newlines.
#
def addprior(msg, text):
    return re.sub('(?m)^', text, msg.rstrip())


# Print a standard message.  Could send message to syslog if UseSyslog is true.
#
def print_msg(msg):
    if UseSyslog:
        for line in msg.split('\n'):
            if line:
                syslog.syslog(line)
    else:
        print msg


# Print out a warning to standard error.
#
def warning(msg):
    msg = 'warning: ' + str(msg)
    if UseSyslog:
        syslog.syslog(msg)
    else:
        sys.stderr.write(msg + '\n')


# Print out a message to standard error.
#
def panic(msg):
    msg = 'error: ' + str(msg)
    if UseSyslog:
        syslog.syslog(msg)
    else:
        sys.stderr.write(msg + '\n')
    sys.exit(1)


if __name__ == '__main__':
    main()
    sys.exit(0)
