#!/usr/bin/python
# Copyright (c) 2012 Intel Corporation. All rights reserved.
# Copyright (c) 2011 QLogic Corporation. All rights reserved.
#
# This software is available to you under a choice of one of two
# licenses.  You may choose to be licensed under the terms of the GNU
# General Public License (GPL) Version 2, available from the file
# COPYING in the main directory of this source tree, or the
# OpenIB.org BSD license below:
#
#     Redistribution and use in source and binary forms, with or
#     without modification, are permitted provided that the following
#     conditions are met:
#
#      - Redistributions of source code must retain the above
#        copyright notice, this list of conditions and the following
#        disclaimer.
#
#      - Redistributions in binary form must reproduce the above
#        copyright notice, this list of conditions and the following
#        disclaimer in the documentation and/or other materials
#        provided with the distribution.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

# This script sets performance tuning driver parameters based on the
# type of node it is being run on.
# This script is intended for standalone use, once per system
# installation
__author__  = "Mitko Haralanov <mitko@qlogic.com>"
__version__ = "0.5"

import os, re, platform, sys, getopt, commands, signal, time
import dircache, traceback

TUNE_MODE_NODE    = (0)
TUNE_MODE_STORAGE = (1<<0)

CPU_TYPE_UNKNOWN     = (-1)

INTEL_CPU_HARPERTOWN = (1<<0)
INTEL_CPU_WESTMERE   = (1<<1)
INTEL_CPU_NEHALEM    = (1<<2)
INTEL_CPU_OTHER      = (1<<31)
INTERL_CPU_ALL       = (INTEL_CPU_HARPERTOWN | INTEL_CPU_WESTMERE|
                        INTEL_CPU_NEHALEM | INTEL_CPU_OTHER)

AMD_CPU_INTERLAGOS   = (1<<32)
AMD_CPU_OTHER        = (1<<63)
AMD_CPU_ALL          = (AMD_CPU_INTERLAGOS | AMD_CPU_OTHER)

CPU_DETECT = {
    INTEL_CPU_OTHER : {
        INTEL_CPU_HARPERTOWN : r'Intel\(R\)\s*.*\s*[EX]?54[0-9]*',
        INTEL_CPU_NEHALEM    : r'Intel\(R\)\s*.*\s*[EX]?55[0-9]*',
        INTEL_CPU_WESTMERE   : r'Intel\(R\)\s*.*\s*[EX]?56[0-9]*'
        },
    AMD_CPU_OTHER : {
        AMD_CPU_INTERLAGOS : r'.*AMD\sOpteron\([Tt][Mm]\)\s.*\s62[0-9]*'
        }
    }

DRV_OPTION_TYPE_UNKNOWN  = 0
DRV_OPTION_TYPE_DRV      = 1
DRV_OPTION_TYPE_UNIT     = 2
DRV_OPTION_TYPE_PORT     = 3

# The order in which the tests appear in this list is important!
# Re-arranging should be done for a reason
DRV_OPTION_MAPPING = [("pcie_caps",         DRV_OPTION_TYPE_UNIT),
                      ("singleport",        DRV_OPTION_TYPE_UNIT),
                      ("krcvqs",            DRV_OPTION_TYPE_PORT),
                      ("rcvhdrcnt",         DRV_OPTION_TYPE_DRV),
                      ("pcie_coalesce",     DRV_OPTION_TYPE_UNIT),
                      ("cache_bypass_copy", DRV_OPTION_TYPE_DRV),
                      ("numa_aware",        DRV_OPTION_TYPE_DRV)]


DRV_OPTION_NAMES = [x[0] for x in DRV_OPTION_MAPPING]
DRV_OPTION_TYPES = [x[1] for x in DRV_OPTION_MAPPING]
DRV_OPTIONS = {}.fromkeys(DRV_OPTION_NAMES, None)

PERFORMANCE_CHECKS = DRV_OPTION_NAMES + ["cstates", "services"]

SELECT_BOOL = 0
SELECT_INT  = 1
SELECT_STR  = 2
SELECT_MENU = 3

# Let's not import the entire errno module
EINVAL = 22

MODPROBE_PREFIX = r"(options\ *ib_qib\ *)"
EXE = os.path.basename (sys.argv[0])
DUAL_PORT_MODELS = ("7342","7362")
QUIET_MODE = False
IPATH_PERF_LOGFILE = "/var/log/%s.log"%EXE
logger = None

# Last In, First Out logging queue class.
# Log messages are read in from the log and then kept in the
# internal queue while the script is running (unless
# instanciated with flush=True). Log messages are written to
# the file on exit. Using Python's loggin modules don't really
# give us what we want and are "overkill" for our purposes.
#
# All script ERRORS are logged. Log message from the test
# functions should be prefaced with the name of the test.
# Log message should be used so it is easy to understand what
# the script is doing.
class LifoLog:
    def __init__(self, logfile=None, size=1000, flush=False):
        self.logfile = logfile
        self.size = size
        self.lifo = []
        self.flush_on_log = flush

    def open(self):
        if self.logfile and os.path.exists(self.logfile) and \
               os.access(self.logfile, os.R_OK):
            try:
                fd = open(self.logfile, 'r')
                self.lifo = fd.readlines()
                fd.close()
                return True
            except IOError: return False
        return False

    def write(self):
        dirname = os.path.dirname(self.logfile)
        if self.logfile and os.path.exists(dirname) and \
               os.path.isdir(dirname) and \
               os.access(dirname, os.W_OK):
            try:
                fd = open(self.logfile, 'w')
                fd.writelines([x.rstrip()+"\n" for x in self.lifo])
                fd.close()
                return True
            except IOError: return False
        return False

    def close(self):
        self.write()

    def flush(self):
        if self.flush_on_log: self.write()

    def log(self, fmt, *args):
        msg = time.strftime("%Y-%m-%d-%H:%M:%S") + ": " + \
              (args and fmt % args or fmt)
        if len(self.lifo) >= self.size: self.lifo.pop(0)
        self.lifo.append(msg)
        self.flush()

# Python < 2.5 does not accept tuples are arguments to
# the .startswith and .endswith string methods.
def startswith(string, *args):
    if not string: return 0
    if len(args) == 1 and \
       (isinstance(args[0], tuple) or \
        isinstance(args[0], list)):
        args = args[0]
    for prefix in args:
        if not isinstance(prefix, basestring):
            continue
        if string[:len(prefix)] == prefix:
            return 1
    return 0

def endswith(string, *args):
    if not string: return 0
    if len(args) == 1 and \
       (isinstance(args[0], tuple) or \
        isinstance(args[0], list)):
        args = args[0]
    for suffix in args:
        if not isinstance(suffix, basestring):
            continue
        if string[-len(suffix):] == suffix:
            return 1
    return 0

# Some distributions pacakge distutils.version into their
# python-devel RPMs. Therefore, distutils.version.StrictVersion
# might not be available.
def versioncmp(x, y):
    ret, x, y = 0, x.split('.'), y.split('.')
    try: x, y = [int(i) for i in x], [int(i) for i in y]
    except ValueError: return -EINVAL
    mlen = max(len(x), len(y))
    x += [0] * (mlen - len(x))
    y += [0] * (mlen - len(y))
    for i in range(mlen):
        ret = cmp(x[i], y[i])
        if ret != 0: return ret
    return ret

def error(format, *args):
    # Log all errors
    log("ERROR: " + format, *args)
    print "ERROR: " + format % args

def warning(format, *args):
    if not QUIET_MODE:
        print "WARNING: " + format % args

def get_num_qib_units():
    '''Return the number of QLogic HCAs in the system.'''
    units = 0
    upath = "/sys/class/infiniband"
    try:
        l = dircache.listdir(upath)
        for d in l:
            if startswith(d, "qib"): units += 1
    except:
        pci = get_qlgc_pci_info()
        units = len(pci)
    return units

def get_num_qib_ports(unit=0):
    '''Return the number of ports on the TrueScale board in this node.'''
    upath = "/sys/class/infiniband/qib%s/ports" % unit
    try: return len (dircache.listdir(upath))
    except: return 0

def get_board_model(unit=0):
    '''Return the model name/number of the TrueScale board in this node.'''
    prefix = "InfiniPath_"
    upath = "/sys/class/infiniband/qib%s/hca_type" % unit
    try: board = open(upath, 'r').readline()
    except: return None
    if board.startswith(prefix): return board[len(prefix):].strip()
    return board.strip()

def get_qlgc_pci_info():
    '''Query lspci for QLogic InfiniBand HW.'''
    try: us = commands.getoutput("/sbin/lspci|grep 'QLogic Corp'").split("\n")
    except: us = []
    qlgc_pci = []
    parse_reg = r'^(?P<bus>[0-9a-f]+:[0-9a-f]+\.[0-9a-f]+) (?P<system>[A-Za-z0-9 ]+):' + \
                r' QLogic Corp. (?P<model>[A-Za-z0-9]+)(?: (?P<speed>QDR|DDR|SDR))?' + \
                r' .* \(rev (?P<rev>[0-9]+)'
    reg = re.compile(parse_reg)
    for unit in us:
        match = reg.match(unit)
        if match:
            hw = match.groupdict()
            if hw["system"] == "InfiniBand":
                hw["rev"] = int(hw["rev"])
                qlgc_pci += [hw]
    return qlgc_pci

def get_system_distro():
    '''Return a tuple containing the disto name, version, and patch
    level.'''
    distro = version = ident = patch = None
    try: distro, version, ident = platform.dist()
    except:
        reg = re.compile(".*-with-(.*)")
        m = reg.match(platform.platform ())
        if m: distro, version, ident = m.group(1).split('-', 2)

    if distro and version:
	# centos7 presents version string as x.y.z, we need just x part
	if distro == "centos":
		match = re.search("([0-9]+)", version)
		if match:
			version = match.group(0)

        # SLES misidentifies itself as SuSE, which causes confusion
        if distro == 'SuSE':
            try:
                line = open('/etc/SuSE-release').readline()
                if re.search("Enterprise", line): distro = "sles"
            except IOError: pass
        distro = distro.lower()

        # Try to find the patch level
        try: version, patch = version.split(".")
        except ValueError:
            if distro == "redhat":
                match = re.search("Update ([0-9]+)", ident)
                if match: patch = match.group(1)
            elif distro in ("SuSE", "SLES"):
                for line in open("/etc/SuSE-release").readlines():
                    if line.startswith("PATCHLEVEL"):
                        patch = line.split("=")[1].strip()
        return (distro, int(version), int(patch or '0'))
    return ()

def get_system_cpu(cpunum=None, item=None):
    """Return the system CPU information (taken from /proc/cpuinfo)."""
    cpuinfo = []
    try: fd = open("/proc/cpuinfo", 'r')
    except IOError: return cpuinfo

    info = {}
    for line in fd.readlines():
        try:
            key, value = line.strip().split(":")
            key, value = key.strip(), value.strip()
            try: info[key] = int(value)
            except ValueError:
                try: info[key] = round(float(value), 3)
                except ValueError: info[key] = value
        except ValueError:
            # the blank line in the cpuinfo file will generate an exception and
            # signal the end of the per-core section
            if info:
                cputype = CPU_TYPE_UNKNOWN
                if info["vendor_id"] == "GenuineIntel":
                    cputype = INTEL_CPU_OTHER
                elif info["vendor_id"] == "AuthenticAMD":
                    cputype = AMD_CPU_OTHER
                name = info["model name"]
                if cputype != CPU_TYPE_UNKNOWN:
                    for cpu, reg in CPU_DETECT[cputype].items():
                        r = re.compile(reg)
                        if r.match(name):
                            cputype = cpu
                            break
                info["cputype"] = cputype
                cpuinfo.append(info)
            info = {}
    fd.close()

    for c in cpuinfo:
        if c["cputype"] == CPU_TYPE_UNKNOWN:
            log("cpu%d: unknown type: %s", cpuinfo.index(c), cpuinfo["model name"])
            warning("Could not determine CPU Type for CPU%d", cpuinfo.index(c))

    if cpunum: return cpuinfo[int(cpunum)]
    elif item: return cpuinfo[0].get(item, None)
    else: return cpuinfo

def check_system_services(service_list=[]):
    '''Return a list of every enabled service from the input list.'''
    enabled = []
    for service in service_list:
        try: output = commands.getoutput("/sbin/chkconfig --list %s 2>/dev/null" %
                                         service)
        except: continue

        reg = re.compile("[0-9]:on")
        r = reg.findall(output)
        if r : enabled.append(service)
    return enabled

def check_system_cstates():
    '''Check whether C-States are enabled for any of the CPUs on this node.'''
    path = "/proc/acpi/processor"
    try: processors = dircache.listdir(path)
    except: processors = []
    cstate_reg = re.compile("\s*\*?C([0-9]):")
    for proc in processors:
        cstate_enabled = []
        filename = os.sep.join([path, proc, "power"])
        if os.path.exists(filename):
            try: content = open(filename, 'r').readlines()
            except IOError, e:
                error("Error reading %s: %s", filename, str(e))
                continue
            for line in content:
                match = cstate_reg.match(line)
                if match: cstate_enabled.append(int(match.group(1)))
            if len(cstate_enabled) > 1 or \
               (len(cstate_enabled) == 1 and cstate_enabled[0] != 1):
                return True
    return False

def find_modprobe_file():
    '''Find the modprobe file on this node. This is distro-dependant.'''
    distro = get_system_distro()
    filename = None
    if distro[0] in ("redhat", "sclnx", "centos"):
        if distro[1] >= 6:
            filename = "/etc/modprobe.d/ib_qib.conf"
        else:
            filename = "/etc/modprobe.conf"
    elif distro[0] in ("suse", "sles"):
        if distro[1] >= 11:
            filename = "/etc/modprobe.d/ib_qib.conf"
        else:
            filename = "/etc/modprobe.conf.local"
    else:
        error("Unsupported distribution: %s %d.%d", distro[0].upper(), distro[1],
              distro[2])
        return filename

    if os.path.exists(filename):
        if not os.access(filename , os.R_OK|os.W_OK):
            error("Can not read/write %s file! Are you running as root?", filename)
    else:
        # It might be that we have to create the modprobe file
        # unlikely but possible (especially, if it's ib_qib.conf)
        if not os.access(os.path.dirname(filename), os.W_OK):
            error("%s file path does not exist and we can't create it!", filename)
    return filename

def read_modprobe():
    '''Read in and return the content of the modprobe file as a list.'''
    filename = find_modprobe_file()
    if not filename:
        error("Could not find suitable modprobe file")
        return []

    try:
        fd = open(filename, 'r')
        content = fd.readlines()
        fd.close()
    except IOError:
        # We've already checked whether the parent directory exists and
        # that we have read/write permissions on it. We've also checked
        # if the file exists and is readable, so if we are here, it
        # means that the file does not exist.
        return []

    return content

def write_modprobe(content):
    '''Write the input content to the modprobe file. This function
    completely replaces the content of the modprobe file.'''
    filename = find_modprobe_file()
    if not filename:
        error("Could not find suitable modprobe file")
        return False

    try:
        fd = open(filename, 'w')
        fd.writelines([x[-1]!="\n" and x+"\n" or x for x in content])
        fd.close()
    except IOError, e:
        error("Could not write %s: %s", filename, str(e))
        return False
    return True

def generate_qib_options(opts):
    '''Translate the options dictionary into a list of strings
    suitable for writing to the modprobe configuration file.'''
    options = []
    for k, v in opts.items():
        try: t = DRV_OPTION_TYPES[DRV_OPTION_NAMES.index(k)]
        except ValueError: t = DRV_OPTION_TYPE_UNKNOWN
        if t == DRV_OPTION_TYPE_UNIT:
            if not isinstance(v, list):
                # this format is used when the option sets only a default
                options.append("%s=%s" % (k, v))
            else:
                same = len([x for x in v if x != v[0]]) == 0
                val = None
                if same:
                    if v and v[0] not in (None, False, 0, ""):
                        val = "%s" % (type(v[0]) == bool and int(v[0]) or \
                                      v[0])
                else:
                    val = ",".join(["%d=%s"%(e, (type(v[e]) == bool and int(v[e]) \
                                                 or v[e])) \
                                    for e in range(len(v)) if v[e] not in \
                                    (None, False, 0, "")])
                if val: options.append("%s=%s" % (k, val))
        elif t == DRV_OPTION_TYPE_PORT:
            if not isinstance(v, list):
                # this format is used when the option sets only a default
                options.append("%s=%s" % (k, v))
            else:
                opt = []
                for u in range(len(v)):
                    for p in range(len(v[u])):
                        if v[u][p] not in (None, False, 0, ""):
                            opt.append("%d:%d=%s" % \
                                       (u, p+1, (type(v[u][p])==bool and int(v[u][p]) or \
                                                 v[u][p])))
                if opt: options.append("%s=%s" % (k, ",".join(opt)))
        elif v not in (None, 0, ""):
            if type(v) == bool: options.append("%s=%s"%(k, int(v)))
            else: options.append("%s=%s"%(k, v))
    return options

def parse_modprobe_options(interactive=False):
    '''Parse the content of the modprobe file, extracting any relevant
    information. This function will determine whether a new (or modified)
    ib_qib option line needs to be inserted.'''
    content = read_modprobe()
    log("modprobe: raw original modprobe content:")
    for l in content: log("modprobe:\t%s", l)
    modprobe = {"options": {},
                "content": [],
                "orig" : None,
                "insert" : True,
                "version": "0.0"}
    index = 0
    modreg = re.compile(MODPROBE_PREFIX)
    while index < len(content):
        line = content[index]
        match = modreg.match(line)
        if match:
            modprobe["orig"] = line
            if not modprobe["insert"]:
                modprobe["content"].append(line)
                index = index + 1
                continue
            # handle double ib_qib modprobe lines
            if modprobe["options"]:
                if interactive:
                    log("modprobe: detected multiple 'options ib_qib' lines")
                    warning("Your modprobe configuration file contains multiple")
                    warning("TrueScale configration lines. This is not advisable.")
                    if not get_answer(SELECT_BOOL, ["n", "y"],
                                      "Would you like to correct this?"):
                        modprobe["content"].append(line)
                index = index + 1
                continue
            opts=line[len(match.group(1)):].split()
            for option in opts:
                try:
                    key, value = option.split("=", 1)
                    try: modprobe["options"][key] = int(value)
                    except ValueError: modprobe["options"][key] = value
                except ValueError: continue
        elif line.startswith ("# %s"%EXE):
            rewind = 0
            # This script has already modified the options
            if modprobe["version"] == "0.0":
                ver_reg = re.compile("# %s v([0-9]\.[0-9]):"%EXE)
                try: modprobe["version"] = ver_reg.match(line).group(1)
                except AttributeError: pass
            # If this is an old version of the script or same version but
            # not in interactive mode leave current comment and options
            # unchanged.
            if versioncmp(__version__, modprobe["version"]) == -1 or \
               (versioncmp(__version__, modprobe["version"]) == 0 and \
                not interactive):
                modprobe["content"].append(line)
                rewind = rewind + 1
                index = index + 1
                # Handle a corner case where the modprobe file contains
                # only the script's comments at the end of the file
                if index < len(content):
                    if content[index].startswith("# %s"%EXE):
                        modprobe["content"].append(content[index])
                        rewind = rewind + 1
                        index = index + 1
                    # Just in case we have multiple consequtive comment sections
                    if index < len(content) and \
                       not content[index].startswith("# %s"%EXE):
                        # Handle special case with comment left from the INSTALL
                        modprobe["content"].append(content[index])
                        if not line.startswith("# If this comment is present,"):
                            modprobe["insert"] = False
                    else:
                        # rewind
                        modprobe["content"] = modprobe["content"][:-rewind]
                        continue
                else:
                    # we are at the end of the file - previous content was bogus,
                    # reinsert the option line
                    modprobe["content"] = modprobe["content"][:-rewind]
        else: modprobe["content"].append(line)
        index = index + 1

    return modprobe

def change_qib_options(modprobe, interactive=False):
    '''Modify the TrueScale driver options from the modprobe
    content. If a TrueScale driver option line does not exist
    add one.'''
    content = modprobe["content"][:]
    date = time.strftime("%y-%m-%d %H:%M")
    for key, value in DRV_OPTIONS.items():
        if DRV_OPTIONS[key] != None:
            modprobe["options"][key] = value
    options = generate_qib_options(modprobe["options"])

    if modprobe["insert"] and options:
        log("modprobe: setting options: %s", ' '.join(options))
        if not modprobe["orig"]:
            content.append("# %s v%s: options ib_qib line modified on %s" %
                           (EXE, __version__, date))
            content.append("options ib_qib %s" % " ".join(options))
        else:
            content.append("# %s v%s: options ib_qib line modified on %s" %
                           (EXE, __version__, date))
            content.append("# %s v%s: original options line: %s" %
                           (EXE, __version__, modprobe["orig"]))
            content.append("options ib_qib %s" % " ".join(options))
    else: log("Leaving options unchanged")
    return content

def get_answer(qtype, *args):
    '''Prompt for user input and return the answer in integer form.
    Arguments:
       qtype - type of input (Boolean, Integer, String, Menu)
       args - remaining agruments depend on type of input:
           BOOL: (choices, prompt)
           INT:  (default, prompt)
           STR:  (prompt)
           MENU: (factor, prompt, choices)
    Returns: BOOL - 0 or 1 (index of selected choice)
             INT - input value
             STR - input string
             MENU - index of selected choice  - factor
    '''
    a, answer = None, None
    if qtype == SELECT_BOOL:
        while a not in args[0]:
            a = raw_input(args[1]+" (%s)-> "%'/'.join(args[0]))
        answer = args[0].index(a)
        log("%s -> %s", args[1], a)
    elif qtype == SELECT_MENU:
        factor = 1 - args[0]
        while a not in range(1, len(args[2])+1):
            print args[1]
            for x in args[2]:
                print "   %d: %s"%(args[2].index(x)+1, x)
            try: a = int (raw_input("-> "))
            except ValueError: continue
        answer = a - factor
        log("%s -> %d", args[1], a)
    elif qtype == SELECT_INT:
        while True:
            a = raw_input(args[1]+"-> ")
            if not a: answer = int(args[0])
            else:
                try: answer = int(a)
                except ValueError: pass
        log("%s -> %d", args[1], answer)
    elif qtype == SELECT_STR:
        answer = raw_input(args[0]+"-> ")
        log("%s -> %s", args[0], answer)
    return answer

def handler(signo, frame):
    if signo == signal.SIGINT:
        error("Interrupted! Exiting...")
        logger.close()
        sys.exit(1)

def select_pcie_caps(interactive, nodetype, modinfo):
    cpus = get_system_cpu()
    nunits = get_num_qib_units()
    log("pcie_caps: cpu type 0x%x", cpus[0]["cputype"])
    if cpus[0]["cputype"] & AMD_CPU_ALL:
        log("pcie_caps: setting caps to 0x51")
        DRV_OPTIONS["pcie_caps"] = ["0x51"] * nunits
    elif cpus[0]["cputype"] == INTEL_CPU_HARPERTOWN and \
         interactive and nunits:
        warning("The CPU(s) in this system are Harpertowns. Setting")
        warning("the pcie_caps TrueScale driver parameter could be")
        warning("risky.")
        if get_answer(SELECT_BOOL, ["n", "y"],
                      "Do you want to set the pcie_caps parameter?"):
            log("pcie_caps: setting caps to 0x51")
            DRV_OPTIONS["pcie_caps"] = ["0x51"] * nunits
        else:
            log("pcie_caps: removing caps")
            DRV_OPTIONS["pcie_caps"] = [None] * nunits
    return

def select_singleport(interactive, nodetype, modinfo):
    nunits = get_num_qib_units()
    DRV_OPTIONS["singleport"] = [DRV_OPTIONS["singleport"]] * nunits
    if interactive:
        for unit in range(nunits):
            board = get_board_model(unit)
            num_ports = get_num_qib_ports(unit)
            # Check against the board since a board with "singleport" on will
            # report only one active port
            if (endswith(board, DUAL_PORT_MODELS) or num_ports > 1):
                if get_answer(SELECT_BOOL, ["n", "y"],
                              "Enable singleport option for HCA%d?"%unit):
                    log("singleport: enabling on unit%d", unit)
                    DRV_OPTIONS["singleport"][unit] = True
                else:
                    log("singleport: disabling on unit%d", unit)
                    DRV_OPTIONS["singleport"][unit] = False
            else:
                log("singleport: unit%d has only one physical port", unit)
                DRV_OPTIONS["singleport"][unit] = False
    return

def select_cstates(interactive, nodetype, modinfo):
    cpus = get_system_cpu()
    if cpus[0]["cputype"] == AMD_CPU_INTERLAGOS:
        log("cstates: ignoring cstates on Interlagos CPUS")
        return
    if check_system_cstates():
        log("cstates: cstates enabled")
        if interactive:
            warning("C-States seem to be enabled on this node.")
            warning("It is recommended that C-States be turned off for")
            warning("optimal performance.")
            print "C-States can be turned off in the BIOS or with a"
            print "kernel boot line option."
    else: log("cstates: cstates disabled")
    return

def select_krcvqs(interactive, nodetype, modinfo):
    # cleanup any old values of krcvqs
    DRV_OPTIONS["krcvqs"] = [[False]]

    # krcvqs are only needed for storage nodes
    if nodetype == TUNE_MODE_NODE:
        log("krcvqs: compute nodes don't need krcvqs set")
        return

    nunits = get_num_qib_units()
    cpus = get_system_cpu()
    num_cpus = len(cpus) / (nunits or 1)
    DRV_OPTIONS["krcvqs"] = [[]] * nunits

    log("krcvqs: num_cpus/unit = %d", num_cpus)
    krcvqs = 0
    if (num_cpus >= 4 and num_cpus <= 7) or \
       (num_cpus >= 57 and num_cpus <= 60): krcvqs = 2
    elif (num_cpus >= 8 and num_cpus <= 11) or \
         (num_cpus >= 53 and num_cpus <= 56): krcvqs = 3
    elif num_cpus >= 12 and num_cpus <= 52: krcvqs = 4
    log("krcvqs: krcvqs = %d", krcvqs)

    for unit in range(nunits):
        board = get_board_model(unit)
        num_ports = get_num_qib_ports(unit)
        # If singleport is not enabled, divide kcvqs by the number of
        # available ports
        if endswith(board, DUAL_PORT_MODELS):
            log("krcvqs: unit%d is dualport (singleport=%s)", unit,
                DRV_OPTIONS["singleport"][unit])
            if DRV_OPTIONS["singleport"][unit] in (False, None):
                # singleport will be turned off and the board is dual-port
                num_ports = 2
            else:
                # if singleport is being turned on with this script but the
                # board has two currently active ports, adjust number of port
                # for correct calculation below
                num_ports = 1

        DRV_OPTIONS["krcvqs"][unit] = [0] * num_ports
        for port in range(num_ports):
            if (port % 2) == 0:
                DRV_OPTIONS["krcvqs"][unit][port] = (krcvqs / (num_ports or 1)) + \
                                                    (krcvqs % num_ports)
            else:
                DRV_OPTIONS["krcvqs"][unit][port] = krcvqs - \
                                                    DRV_OPTIONS["krcvqs"][unit][port-1]
            log("krcvqs%d: setting option %d:%d=%d", unit, unit, port+1,
                DRV_OPTIONS["krcvqs"][unit][port])
    return

def select_services(interactive, nodetype, modinfo):
    service_list = ["powersaved", "cpuspeed"]
    enabled = check_system_services(service_list)

    if enabled:
        log("services: enabled services: %s", " ".join(enabled))
        if interactive:
            warning("The following services, which can affect performance")
            warning("are enabled:")
            warning("   %s", ", ".join(enabled))
            if get_answer(SELECT_BOOL, ["n", "y"],
                          "Would you like to turn them off?"):
                log("services: Disabling services")
                for service in enabled:
                    log("services:\tdisable service %s", service)
                    try:
                        st1 = commands.getstatusoutput("/sbin/chkconfig %s off" %
                                                       service)
                        st2 = commands.getstatusoutput("/sbin/service %s stop" %
                                                service)
                        if st1[0] or st2[0]:
                            warning("Could not turn off service %s", service)
                            warning("%s", "\n".join([x[1] for x in [st1, st2] \
                                                     if x[0]]))
                            log("services:\t\tdisable service %s failed", service)
                    except:
                        log("services:\t\tdisable service %s failed", service)
                        warning("Could not turn off service %s", service)
    else: log("services: services not running")
    return

def select_pcie_coalesce(interactive, nodetype, modinfo):
    nunits = get_num_qib_units()
    cpus = get_system_cpu()
    DRV_OPTIONS["pcie_coalesce"] = [False] * nunits
    if cpus[0]["cputype"] == INTEL_CPU_HARPERTOWN:
        if interactive and nunits:
            warning("The CPU(s) in this system are Harpertowns. Setting")
            warning("the pcie_coalesce TrueScale driver parameter could be")
            warning("risky.")
            for unit in range(nunits):
                if get_answer(SELECT_BOOL, ["n", "y"],
                              "Do you want to set the pcie_coalesce parameter " + \
                              "for HCA%d?"%unit):
                    log("pcie_coalesce: setting unit%d to True", unit)
                    DRV_OPTIONS["pcie_coalesce"][unit] = True
                else: log("pcie_coalesce: setting unit%d to False", unit)
    else: log("pcie_coalesce: cpu not Harpertown")
    return

def select_rcvhdrcnt(interactive, nodetype, modinfo):
    # If the previous version of the script is older than 0.4 and
    # the rcvhdrcnt options is present and set to 4096, remove it
    # (driver already sets it to that value).
    if versioncmp(modinfo["version"], "0.4") == -1 and \
       (modinfo["options"].has_key("rcvhdrcnt") and \
        modinfo["options"]["rcvhdrcnt"] == 4096):
        log("rcvhdrcnt: removing stale option")
        DRV_OPTIONS["rcvhdrcnt"] = 0
    return

def select_cache_bypass_copy(interactive, nodetype, modinfo):
    cpus = get_system_cpu()
    if cpus[0]["cputype"] & AMD_CPU_ALL:
        log("cache_bypass_copy: enabling option")
        DRV_OPTIONS["cache_bypass_copy"] = True
    else: log("cache_bypass_copy: cpu not AMD")
    return

def select_numa_aware(interactive, nodetype, modinfo):
    if DRV_OPTIONS["numa_aware"]:
        log("numa_aware: option enabled. warning...")
        warning("The 'numa_aware' option is enabled but is not recommended.")
        warning("If you don't require it being set, please remove it.")
    return

def select_driver_options(checks, interactive=False, nodetype=TUNE_MODE_NODE,
                          modprobe=None):
    mod = {"version":"0,0", "options":{}}
    if modprobe:
        mod["version"] = modprobe["version"]
        mod["options"] = modprobe["options"]
    for option in checks:
        eval("select_%s(interactive, nodetype, mod)" % option)

def usage(msg=None):
    if msg:
        print msg+"\n"
    print EXE+" [-T <check>[,<check>]] [-Iqh]"
    print
    print "  -T  - Peform only selected checks (list of comma-separated"
    print "        check names). Available checks are:"
    print "           %s" %  ",".join(PERFORMANCE_CHECKS)
    print "  -I  - Run in interactive mode. In interactive mode, the user"
    print "        is prompted to make selection on some configuration options."
    print "  -q  - Run in Quiet mode. In this mode, warnings are suppressed."
    print "  -h  - Show this help screen."
    return

def setup_logging():
    global logger
    logger = LifoLog(IPATH_PERF_LOGFILE)
    logger.open()

def log(fmt, *args):
    if not logger: setup_logging()
    logger.log(fmt, *args)

def main():
    global QUIET_MODE
    interactive = False
    mode = TUNE_MODE_NODE
    do_checks = PERFORMANCE_CHECKS

    try: opts, args = getopt.getopt(sys.argv[1:], "IT:qh", [])
    except getopt.GetoptError, e:
        usage(str(e))
        return 1

    for opt, value in opts:
        if opt == "-I": interactive = True
        if opt == "-T":
            chks = [x.strip() for x in value.split(",")]
            do_checks = []
            for chk in chks:
                if chk not in PERFORMANCE_CHECKS:
                    warning("Test %s not recognized! See program usage.")
                else: do_checks.append(chk)
        if opt == "-q":
            QUIET_MODE = True
        if opt == "-h":
            usage ()
            return 0

    log("-"*30)
    log("ipath_perf_tuning started in %s mode", (interactive and "interactive"
                                                 or "automatic"))

    cpus = get_system_cpu()
    log("system: cpu information:")
    log("system:\tnumber of cores: %d", len(cpus))
    log("system:\tcpu model name: %s", cpus[0]["model name"])
    log("system:\tcpu type: %d", cpus[0]["cputype"])
    units = get_num_qib_units()
    log("system: HCA information:")
    log("system:\tnumber of units: %d", units)
    for u in range(units):
        board = get_board_model(u)
        pnum = get_num_qib_ports(u)
        log("system:\tunit%d model: %s", u, board)
        log("system:\tunit%d number of enabled ports: %d", u, pnum)
        del board, pnum
    del cpus, units

    if interactive:
        mode = get_answer(SELECT_MENU, 0, "Please, select node type:",
                          ["Compute Node", "Storage Node"])
    log("Node mode selected: %d", mode)

    modprobe = parse_modprobe_options(interactive)
    DRV_OPTIONS.update(modprobe["options"])

    log("Performing tests: %s", ','.join(do_checks))
    select_driver_options(do_checks, interactive, mode, modprobe)

    modprobe = change_qib_options(modprobe, interactive)
    return write_modprobe(modprobe)

if __name__ == "__main__":
    signal.signal(signal.SIGINT, handler)
    setup_logging()
    ret = True
    try: ret = main()
    except Exception, e:
        exc_type, exc_value, exc_tb = sys.exc_info()
        tb = traceback.format_tb(exc_tb)
        log(str(e))
        for l in tb: log(l)
        error("(Exception) %s", str(e))
        ret = False
    logger.close()
    sys.exit (int (not ret))
