예제 #1
0
    def __init__(self):
        log = Logger(__name__)
        self.logger = log.getLogger()
        self.ioexp = IOExpander()
        self.cpld = CPLD()
        self.lpc = LPC()
        self.ioexp = IOExpander()

        #GPIO REGs
        self.ALERT_GPIO_REG = 0x1
        #I2C Alert REGs
        self.ALERT_STATUS_REG = 0x0
        self.ALERT_DIS_REG = 0x11
class ROVUtility:
    def __init__(self):
        log = Logger(__name__)
        self.logger = log.getLogger()
        self.cpld = CPLD()
        self.rov_controller = ROVController()

    def platform_check(self):
        # NCP 1-1 beta (JR2 B1) and later
        #0x2[9abcdefABCDEF])
        board_info = self.cpld.get_board_info()
        if board_info["hw_rev"] >= 2:
            return True
        else:
            return False

    def get_j2_rov(self):
        try:
            if not self.platform_check():
                self.logger.error("Not supported")
                return {}

            j2_rov_stamp = self.cpld.get_j2_rov_stamp()
            rov_controller_config = self.rov_controller.get_rov_config()
            rov_controller_output = self.rov_controller.get_rov_output()
            return {
                "j2_rov_stamp":
                j2_rov_stamp,
                "rov_controller_config":
                "0x{:02X}".format(rov_controller_config),
                "rov_controller_config_volt":
                self.rov_controller._vid_to_volt_str(rov_controller_config),
                "rov_controller_output":
                "0x{:02X}".format(rov_controller_output),
                "rov_controller_output_volt":
                self.rov_controller._vid_to_volt_str(rov_controller_output)
            }
        except Exception as e:
            self.logger.error("get_j2_rov failed, error: {0}".format(e))

    def set_j2_rov(self):
        try:
            if not self.platform_check():
                self.logger.error("Not supported")
                return

            j2_rov_stamp = self.cpld.get_j2_rov_stamp()
            self.rov_controller.set_rov_config(j2_rov_stamp)

        except Exception as e:
            self.logger.error("set_j2_rov failed, error: {}".format(e))
class PSUUtility:
    def __init__(self):
        log = Logger(__name__)
        self.logger = log.getLogger()
        self.cpld = CPLD()

    def _check_psu_range(self, psu_num):
        if psu_num not in range(PSU.MAX_PSU):
            raise ValueError("PSU number({0}) is out of range (0-{1})".format(
                psu_num, PSU.MAX_PSU - 1))

    def get_psu_presence(self, psu_num):
        try:
            self._check_psu_range(psu_num)

            result = self.cpld.get_psu_presence(psu_num)
            if result == PSUStatus.ABSENCE:
                ret_val = {"presence": "absence"}
            else:
                ret_val = {"presence": "presence"}

            return ret_val
        except Exception as e:
            self.logger.error(
                "get_psu_presence failed, psu_num={}, error: {}".format(
                    psu_num, e))

    def get_psu_power_ok(self, psu_num):
        try:
            self._check_psu_range(psu_num)

            result = self.cpld.get_psu_power_ok(psu_num)
            if result == PSUStatus.POWER_FAIL:
                ret_val = {"power": "failed"}
            else:
                ret_val = {"power": "ok"}

            return ret_val
        except Exception as e:
            self.logger.error(
                "get_psu_power_ok failed, psu_num={0}, error: {1}".format(
                    psu_num, e))
    def __init__(self):
        try:
            log = Logger(__name__)
            self.logger = log.getLogger()

            # I2C drivers
            self._load_i2c_drivers()

            #Check Mux Ctrl
            self.lpc = LPC()
            self._check_i2c_mux_ctrl()

            self.ioexp = IOExpander()

            self.i2c_mux = I2CMux()
            self.eeprom = EEPRom()
            self.cpld = CPLD()
            self.thermal = Thermal()
            self.rov_util = ROVUtility()
            self.intr_util = INTRUtility()
            self.bsp_util = BSPUtility()
        except Exception:
            raise
 def __init__(self):
     log = Logger(__name__)
     self.logger = log.getLogger()
     self.cpld = CPLD()
     self.rov_controller = ROVController()
 def __init__(self):
     log = Logger(__name__)
     self.logger = log.getLogger()
     self.cpld = CPLD()
예제 #7
0
class CPLDUtility:
    def __init__(self):
        log = Logger(__name__)
        self.logger = log.getLogger()
        self.cpld = CPLD()

    def _check_cpld_num(self, cpld_num):
        if cpld_num not in range(CPLDConst.CPLD_MAX):
            raise ValueError("CPLD number({0}) is out of range (0-{1})".format(
                cpld_num, CPLDConst.CPLD_MAX - 1))

    def _check_dev_type(self, devType):
        if devType not in range(DevType.DEV_MAX):
            raise ValueError("Dev Type({}) is out of range (0-{})".format(
                devType, DevType.DEV_MAX))

        board_info = self.cpld.get_board_info()

        if board_info["hw_rev"] == 0:
            if devType != DevType.J2:
                raise ValueError(
                    "Dev Type({}) Reset is not supported ".format(devType))
        '''
        else:
            if devType not in range(DevType.RETIMER+1):
                raise ValueError("Dev Type({}) Reset is not supported ".format(devType))    
        '''

    def _version_h(self, version):
        return "{}.{:02d}".format(version >> 6, version & 0b00111111)

    def get_board_info(self):
        try:
            board_info = self.cpld.get_board_info()
            return board_info
        except Exception as e:
            self.logger.error("get_board_info failed, error: {0}".format(e))

    def get_cpld_version(self, target):
        try:
            if target == CPLDSource.CPU:
                cpld_version = self.cpld.get_cpu_board_cpld_version()
                return {
                    "version": "X.%02x" % cpld_version,
                    "version_h": self._version_h(cpld_version)
                }
            elif target == CPLDSource.MB:
                result = []
                result_h = []
                cpld_versions = self.cpld.get_main_board_cpld_version()
                for i in range(len(cpld_versions)):
                    result.append("X.%02x" % cpld_versions[i])
                    result_h.append(self._version_h(cpld_versions[i]))
                return {"version": result, "version_h": result_h}
            else:
                raise ValueError("target(" + str(target) + ") is out of range")

        except Exception as e:
            self.logger.error(
                "get_cpld_version failed, target={0}, error: {1}".format(
                    target, e))

    def get_cpld_id(self):
        try:
            result = []
            cpld_ids = self.cpld.get_main_board_cpld_id()
            for i in range(len(cpld_ids)):
                result.append("X.%02x" % cpld_ids[i])
            return {"id": result}
        except Exception as e:
            self.logger.error("get_cpld_id failed, error: {0}".format(e))

    def get_cpld_port_interrupt(self, cpld_num):
        try:
            self._check_cpld_num(cpld_num)

            result = self.cpld.get_port_interrupt(cpld_num)
            if result == PortStatus.INTERRUPTED:
                ret_val = {"interrupt_status": "interrupted"}
            else:
                ret_val = {"interrupt_status": "no interrupt"}
            return ret_val
        except Exception as e:
            self.logger.error(
                "get_cpld_port_interrupt failed, error: {0}".format(e))

    def reset_dev(self, devType):
        try:
            self._check_dev_type(devType)
            self.cpld.reset_dev(devType)
        except Exception as e:
            self.logger.error("reset_dev {} failed, error: {}".format(
                devType, e))

    def get_reset_ctrl(self, devType):
        try:
            result = self.cpld.get_reset_ctrl(devType)

            if result == ResetStatus.RESET:
                ret_val = {"reset": "true"}
            elif result == ResetStatus.UNSET:
                ret_val = {"reset": "false"}
            else:
                ret_val = {"reset": "not supported"}
            return ret_val
        except Exception as e:
            self.logger.error("get_reset_ctrl {} failed, error: {}".format(
                devType, e))

    def set_reset_ctrl(self, devType, reset_status):
        try:
            result = self.cpld.set_reset_ctrl(devType, reset_status)
            if result == False:
                self.logger.error(
                    "reset_ctrl failed, devType={}, reset_status={}".format(
                        devType, reset_status))
        except Exception as e:
            self.logger.error("set_reset_ctrl {} failed, error: {}".format(
                devType, e))
class QSFPDDUtility:
            
    def __init__(self):
        log = Logger(__name__)
        self.logger = log.getLogger()        
        self.cpld = CPLD()

    def _check_qsfpdd_port(self, port):
        if port not in range(QSFPDD.MAX_PORT):                
            raise ValueError("Port number({0}) is out of range (0-{1})".format(port, QSFPDD.MAX_PORT-1))
    
    def _check_enable(self, enable):
        if enable not in range(LPMode.ENABLE+1):
            raise ValueError("enable ({0}) is out of range (0-{1})".format(enable, LPMode.ENABLE))    
    
    def _check_reset(self, reset):
        if reset not in range(PortStatus.NO_RESET+1):
            raise ValueError("reset ({0}) is out of range (0-{1})".format(reset, PortStatus.NO_RESET))
        
    def get_presence(self, port_num):
        try:
            self._check_qsfpdd_port(port_num)

            result = self.cpld.qsfpdd_get_presence(port_num)

            if result == PortStatus.PORT_ABSENCE:
                ret_val = {"presence":"absence"}
            else:
                ret_val = {"presence":"presence"}

            return ret_val
        except Exception as e:
            self.logger.error("get_presence failed, port_num={0}, error: {1}".format(port_num, e))

    def get_interrupt(self, port_num):
        try:
            self._check_qsfpdd_port(port_num)

            result = self.cpld.qsfpdd_get_interrupt(port_num)

            if result == PortStatus.INTERRUPTED:
                ret_val = {"interrupt_status":"interrupted"}
            else:
                ret_val = {"interrupt_status":"no interrupt"}

            return ret_val
        except Exception as e:
            self.logger.error("get_port_interrupt failed, error: {0}".format(e))
            
    def set_lp_mode(self, port_num, enable):
        try:
            self._check_qsfpdd_port(port_num)
            self._check_enable(enable)            
            
            self.cpld.qsfpdd_set_lp_mode(port_num, enable)
        except Exception as e:
            self.logger.error("set_lp_mode failed, port_num={0}, enable={1}, error: {2}".format(port_num, enable, e))

    def get_lp_mode(self, port_num):
        try:
            self._check_qsfpdd_port(port_num)

            result = self.cpld.qsfpdd_get_lp_mode(port_num)

            if result == LPMode.DISABLE:
                ret_val = {"lp_mode":"disabled"}
            else:
                ret_val = {"lp_mode":"enabled"}

            return ret_val
        except Exception as e:
            self.logger.error("get_lp_mode failed, port_num={0}, error: {1}".format(port_num, e))

    def reset_port(self, port_num):
        try:
            self._check_qsfpdd_port(port_num)

            self.cpld.qsfpdd_reset_port(port_num)
        except Exception as e:
            self.logger.error("reset_port failed, port_num={0}, error: {1}".format(port_num, e))
    
    def get_reset(self, port_num):
        try:
            self._check_qsfpdd_port(port_num)

            result = self.cpld.qsfpdd_get_reset(port_num)
            if result == PortStatus.RESET:
                ret_val = {"reset":"true"}
            else:
                ret_val = {"reset":"false"}

            return ret_val
        except Exception as e:
            self.logger.error("get_reset failed, port_num={0}, error: {1}".format(port_num, e))
    
    def set_reset(self, port_num, reset):
        try:
            self._check_qsfpdd_port(port_num)
            self._check_reset(reset)

            self.cpld.qsfpdd_set_reset(port_num, reset)            
        except Exception as e:
            self.logger.error("set_reset failed, port_num={0}, error: {1}".format(port_num, e))
class PlatformUtility:

    builtin_pca954x_path = "/lib/modules/{}/kernel/drivers/i2c/muxes/i2c-mux-pca954x.ko"
    #kernel release version
    kr_version_cmd = "uname -r"
    depmod_cmd = "depmod -a"
    #pci device
    PCI_CHECK_LIST = {
        "00:14.0": "USB controller",
        "00:1d.0": "USB controller",
        "00:1f.2": "SATA controller",
        "00:1f.3": "SMBus",
        "02:00.0": "10 GbE SFP+",
        "02:00.1": "10 GbE SFP+",
        "06:00.0": "PEX 8724",
        "07:01.0": "PEX 8724",
        "07:02.0": "PEX 8724",
        "07:08.0": "PEX 8724",
        "07:09.0": "PEX 8724",
        "07:0a.0": "PEX 8724",
        "0b:00.0": "J2",
        "0c:00.0": "OP2",
        "0d:00.0": "I210"
    }
    USB_CHECK_LIST = {"046b:ff20": "BMC", "046b:ff01": "BMC"}
    BSP_INIT_STOP = "[BSP Init Stop]"
    IGNORE_ERR = True

    def __init__(self):
        try:
            log = Logger(__name__)
            self.logger = log.getLogger()

            # I2C drivers
            self._load_i2c_drivers()

            #Check Mux Ctrl
            self.lpc = LPC()
            self._check_i2c_mux_ctrl()

            self.ioexp = IOExpander()

            self.i2c_mux = I2CMux()
            self.eeprom = EEPRom()
            self.cpld = CPLD()
            self.thermal = Thermal()
            self.rov_util = ROVUtility()
            self.intr_util = INTRUtility()
            self.bsp_util = BSPUtility()
        except Exception:
            raise

    def device_init(self):
        try:
            # Unmount kernel modules
            self._unload_kernel_module("gpio_ich")

            # Mount kernel modules

            # I2C Mux
            subprocess.run(
                ['modprobe', 'i2c_mux_pca954x', 'force_deselect_on_exit=1'])
            self.i2c_mux.init()

            # EEPROM
            self._load_kernel_module("x86_64_ufispace_s9700_53dx_eeprom_mb")
            self._load_kernel_module("x86_64_ufispace_s9700_53dx_optoe")
            self.eeprom.init()

            # Thermal
            self._load_kernel_module("lm75")
            self.thermal.init()

            # GPIO
            self._load_kernel_module("gpio-pca953x")
            self.ioexp.init(self.i2c_mux.MUXs)

            # IPMI
            self._load_kernel_module("ipmi_devintf")
            self._load_kernel_module("ipmi_si")

            # CPLD
            self._load_kernel_module(self.cpld.DRIVER_NAME)
            self.cpld.init()

        except Exception:
            raise

    def device_deinit(self):
        try:
            # Remove kernel modules
            # CPLD
            self.cpld.deinit()
            self._unload_kernel_module(self.cpld.DRIVER_NAME)

            # GPIO
            self.ioexp.deinit(self.i2c_mux.MUXs)
            self._unload_kernel_module("gpio-pca953x")

            # Thermal
            self.thermal.deinit()
            self._unload_kernel_module("lm75")

            # MB EEPROM
            self._unload_kernel_module("x86_64_ufispace_s9700_53dx_eeprom_mb")

            # OPTOE EEPROM
            self._unload_kernel_module("x86_64_ufispace_s9700_53dx_optoe")

            # I2C Mux
            self.i2c_mux.deinit()
            self._unload_kernel_module("i2c_mux_pca954x")

        except Exception:
            raise

    def _get_kernel_release(self):
        try:
            return subprocess.getoutput(self.kr_version_cmd)
        except Exception:
            raise

    def _check_bsp_init(self):
        try:
            is_bsp_inited = self.bsp_util.is_bsp_inited()

            if is_bsp_inited:
                self.logger.error(
                    "BSP may be already initialized. Please run 'platform_utility.py deinit' first"
                )
                self.logger.error(self.BSP_INIT_STOP)
                sys.exit()
        except Exception:
            raise

    def _check_ko(self):
        try:
            #get kernel release
            kr = self._get_kernel_release()

            #remove built-in i2c-mux-pca954x.ko if exist
            pca954x_path = self.builtin_pca954x_path.format(kr)
            if os.path.exists(pca954x_path):
                os.remove(pca954x_path)
                #generate modules.dep
                subprocess.run(self.depmod_cmd, shell=True)

        except Exception:
            raise

    def check_idt(self):
        try:
            #Open Mux(0x73) for IDT(0x53)
            retcode, _ = subprocess.getstatusoutput("i2cset -y 0 0x73 0x8")
            if retcode != 0:
                self.logger.error(
                    "Open I2C Mux channel (0x73) for IDT failed.")
                return

            #Check IDT
            retcode, _ = subprocess.getstatusoutput("i2cget -y 0 0x53 0x0")
            if retcode != 0:
                self.logger.error(
                    "Access IDT(0x53) failed. Trying to reset IDT")

                #Reset IDT
                self.lpc.regSet(LPCDevType.CPLD_ON_MAIN_BOARD, 0x4D, 0xF7)
                sleep(0.5)

                #Access IDT again
                retcode, _ = subprocess.getstatusoutput("i2cget -y 0 0x53 0x0")
                if retcode != 0:
                    self.logger.error(
                        "Access IDT(0x53) failed and reset still failed")
                else:
                    self.logger.error(
                        "Access IDT(0x53) failed and reset succeed")

            #Close Mux(0x73)
            retcode, _ = subprocess.getstatusoutput("i2cset -y 0 0x73 0x0")
            if retcode != 0:
                self.logger.error("Close I2C Mux channel (0x73) failed.")

        except Exception:
            raise

    def _check_intr(self):
        try:
            alert_dis = self.intr_util.get_alert_dis()
            if alert_dis == 0:
                self.logger.warning(
                    "I2C Alert is already enabled. I2C tree performance may be affected."
                )
        except Exception:
            raise

    def _check_i2c_mux_ctrl(self):
        try:
            default_val = 0x80
            reg_val = self.lpc.regGet(LPCDevType.CPLD_ON_MAIN_BOARD,
                                      CPLDMBReg.REG_MUX_CTRL)

            if reg_val != default_val:
                self.logger.error(
                    "I2C Mux Ctrl [0x{:02X}] is not valid. Expected [0x{:02X}]"
                    .format(reg_val, default_val))
                self.logger.error(self.BSP_INIT_STOP)
                sys.exit()
            else:
                self.logger.info("[Check Mux Control Register] Pass")
        except Exception as e:
            self.logger.error(e)
            raise

    def _check_cpld(self):

        #CPLD missing workaround :BEGIN

        #open mux 0x75
        retcode, _ = subprocess.getstatusoutput("i2cset -y 0 0x75 0x1")
        if retcode != 0:
            self.logger.error(
                "Open I2C Mux channel 0x75 for CPLD WA failed, return code = {}, exit"
                .format(retcode))
            self.logger.error(self.BSP_INIT_STOP)
            sys.exit()

        #Read CPLD version
        for i in range(len(self.cpld.CPLD_I2C_ADDR)):
            retcode, _ = subprocess.getstatusoutput(
                "i2cget -y 0 {} 0x2".format(self.cpld.CPLD_I2C_ADDR[i]))
            if retcode != 0:
                #log info for reading cpld version
                self.logger.info("Reading CPLD{} 0x{:02X} failed".format(
                    i + 1, self.cpld.CPLD_I2C_ADDR[i]))

        #Check CPLD version
        for i in range(len(self.cpld.CPLD_I2C_ADDR)):
            retcode, _ = subprocess.getstatusoutput(
                "i2cget -y 0 {} 0x2".format(self.cpld.CPLD_I2C_ADDR[i]))
            if retcode != 0:
                #log error for checking cpld version
                self.logger.error(
                    "Reading CPLD{} 0x{:02X} failed, return code = {}, exit".
                    format(i + 1, self.cpld.CPLD_I2C_ADDR[i], retcode))
                self.logger.error(self.BSP_INIT_STOP)
                sys.exit()

        #close mux 0x75
        retcode, _ = subprocess.getstatusoutput("i2cset -y 0 0x75 0x0")
        if retcode != 0:
            self.logger.error(
                "Close I2C Mux channel for CPLD WA failed, return code = {}, exit"
                .format(retcode))
            self.logger.error(self.BSP_INIT_STOP)
            sys.exit()

        #CPLD missing workaround :END

        self.logger.info("[Check CPLD] Pass")

    def _check_pci(self):
        err_cnt = 0
        result = ""
        err_list = ["rev ff"]
        err_desc = ["under reset"]
        cmd_lspci = "lspci"
        cmd_lspci_s = "lspci -s {}"

        #check lspci command
        retcode, _ = subprocess.getstatusoutput(cmd_lspci)
        if retcode != 0:
            self.logger.warning(
                "lspci commnad not found, skip checking pci devices")
            return

        #check pci devices
        for pci_id in self.PCI_CHECK_LIST.keys():
            pci_name = self.PCI_CHECK_LIST[pci_id]
            retcode, output = subprocess.getstatusoutput(
                cmd_lspci_s.format(pci_id))
            #check device existence
            if retcode != 0:
                self.logger.error(
                    "Invalid PCI device {} ({}), retcode={}, output={}".format(
                        pci_name, pci_id, retcode, output))
                err_cnt += 1
            elif len(output) == 0:
                self.logger.error("PCI device {} ({}) not found".format(
                    pci_name, pci_id))
                if not self.IGNORE_ERR:
                    self.logger.error(self.BSP_INIT_STOP)
                    sys.exit()
            else:
                #check device error status
                for i in range(len(err_list)):
                    if output.find(err_list[i]) >= 0:
                        self.logger.warning("PCI device {} ({}) {}".format(
                            pci_name, pci_id, err_desc[i]))
                        err_cnt += 1

        if err_cnt == 0:
            result = "Pass"
            self.logger.info("[Check PCI] {}".format(result))
        else:
            result = "Fail"
            self.logger.warning("[Check PCI] {}".format(result))

    def _check_usb(self):
        warn_cnt = 0
        result = ""
        cmd_lsusb = "lsusb"
        cmd_lsusb_s = "lsusb -d {}"

        #check lsusb command
        retcode, _ = subprocess.getstatusoutput(cmd_lsusb)
        if retcode != 0:
            self.logger.warning(
                "cmd_lsusb commnad not found, skip checking usb devices")
            return

        #check usb devices
        for usb_id in self.USB_CHECK_LIST.keys():
            usb_name = self.USB_CHECK_LIST[usb_id]
            retcode, output = subprocess.getstatusoutput(
                cmd_lsusb_s.format(usb_id))
            #check device existence
            if retcode != 0:
                self.logger.warning("USB device {} ({}) not found".format(
                    usb_name, usb_id))
                warn_cnt += 1
            elif len(output) == 0:
                self.logger.warning("USB device {} ({}) not found".format(
                    usb_name, usb_id))
                warn_cnt += 1
            else:
                if output.find(usb_id) < 0:
                    self.logger.warning("USB device {} ({}) not found".format(
                        usb_name, usb_id))
                    warn_cnt += 1

        if warn_cnt == 0:
            result = "Pass"
            self.logger.info("[Check USB] {}".format(result))
        else:
            result = "Warning"
            self.logger.warning("[Check USB] {}".format(result))
        return 0

    def pre_init(self):
        self._check_bsp_init()
        # don't check ko for sonic platform
        #self._check_ko()
        self._check_intr()
        retcode = self.i2c_mux.pre_init()
        if retcode != 0:
            self.logger.error(self.BSP_INIT_STOP)
            sys.exit()
        self._check_cpld()
        self.check_idt()
        self._check_pci()
        self._check_usb()

    def post_init(self):
        try:
            #set j2 rov
            if self.rov_util.platform_check():
                self.rov_util.set_j2_rov()
        except Exception:
            raise

    def _load_i2c_drivers(self):
        # I2C I801
        self._load_kernel_module("i2c_i801")
        # I2C Dev
        self._load_kernel_module("i2c_dev")

    def _load_kernel_module(self, module_name):
        #replace "-" to "_" since lsmod show module name with "_"
        module_name = module_name.replace("-", "_")

        #check if module is already loaded
        retcode, _ = subprocess.getstatusoutput(
            "lsmod | grep {}".format(module_name))
        #module is not loaded yet
        if retcode != 0:
            retcode, _ = subprocess.getstatusoutput(
                "modprobe {}".format(module_name))
            #load module failed
            if retcode != 0:
                self.logger.error(
                    "Load kernel module {} failed, retcode={}".format(
                        module_name, retcode))
                if not self.IGNORE_ERR:
                    self.logger.error(self.BSP_INIT_STOP)
                    sys.exit()

    def _unload_kernel_module(self, module_name):
        #replace "-" to "_" since lsmod show module name with "_"
        module_name = module_name.replace("-", "_")

        #check if module is already loaded
        retcode, _ = subprocess.getstatusoutput(
            "lsmod | grep {}".format(module_name))
        #module is loaded
        if retcode == 0:
            retcode, _ = subprocess.getstatusoutput(
                "rmmod {}".format(module_name))
            #unload module failed
            if retcode != 0:
                self.logger.error(
                    "Unload kernel module {} failed, retcode={}".format(
                        module_name, retcode))
예제 #10
0
class INTRUtility:
    def __init__(self):
        log = Logger(__name__)
        self.logger = log.getLogger()
        self.ioexp = IOExpander()
        self.cpld = CPLD()
        self.lpc = LPC()
        self.ioexp = IOExpander()

        #GPIO REGs
        self.ALERT_GPIO_REG = 0x1
        #I2C Alert REGs
        self.ALERT_STATUS_REG = 0x0
        self.ALERT_DIS_REG = 0x11

    def init_i2c_alert(self):
        i2c_detect_cmd = "i2cdetect -y 0"

        #i2cdetect -y 0
        retcode, _ = subprocess.getstatusoutput(i2c_detect_cmd)
        if retcode != 0:
            self.logger.error("i2c command error: {}".format(i2c_detect_cmd))

        #Set pin function to alert mode on CPU
        #./ioset 0x501 0xf7
        #IO_x500[11]  SMBALERT_N_GPIO11
        #0/Alert mode,1/GPIO mode
        #Default is 0
        regVal = self.lpc.regGet(LPCDevType.BDE_GPIO_ON_CPU_BOARD,
                                 self.ALERT_GPIO_REG)
        self.lpc.regSet(LPCDevType.BDE_GPIO_ON_CPU_BOARD, self.ALERT_GPIO_REG,
                        regVal & 0xF7)

        #Enable alert function on CPU
        #./ioset 0xf011 0x0
        #IO_xF011[2]  SMBALERT_DIS
        #0/Enable Alert, 1/Disable alert
        #Default is 1
        regVal = self.lpc.regGet(LPCDevType.CPU_I2C_ALERT, self.ALERT_DIS_REG)
        self.lpc.regSet(LPCDevType.CPU_I2C_ALERT, self.ALERT_DIS_REG,
                        regVal & 0xFB)

    def deinit_i2c_alert(self):
        regVal = self.lpc.regGet(LPCDevType.CPU_I2C_ALERT, self.ALERT_DIS_REG)
        self.lpc.regSet(LPCDevType.CPU_I2C_ALERT, self.ALERT_DIS_REG,
                        regVal | 0x04)

    def get_alert_gpio(self):
        regVal = self.lpc.regGet(LPCDevType.BDE_GPIO_ON_CPU_BOARD,
                                 self.ALERT_GPIO_REG)
        return (regVal >> 3) & 1

    def get_alert_dis(self):
        regVal = self.lpc.regGet(LPCDevType.CPU_I2C_ALERT, self.ALERT_DIS_REG)
        return (regVal >> 2) & 1

    def get_alert_sts(self):
        regVal = self.lpc.regGet(LPCDevType.CPU_I2C_ALERT,
                                 self.ALERT_STATUS_REG)
        return (regVal >> 5) & 1

    def clear_i2c_alert(self):
        intr_reg = "9539_HOST_GPIO_I2C"
        cpu_gpio_reg = "9539_CPU_I2C"

        #clear alert on ioexpander
        #i2cdump -y 0 0x74
        reg_vals = self.ioexp.dump_reg(intr_reg)
        self.logger.info("clear_i2c_alert() intr_reg_vals={}".format(reg_vals))

        #i2cdump -y 0 0x77
        reg_vals = self.ioexp.dump_reg(cpu_gpio_reg)
        self.logger.info(
            "clear_i2c_alert() cpu_gpio_reg_vals={}".format(reg_vals))

        #clear i2c alert status on CPU
        #./ioset 0xf000 0x60
        self.lpc.regSet(LPCDevType.CPU_I2C_ALERT, self.ALERT_STATUS_REG, 0x60)

    def get_cpld_to_cpu_intr(self):
        cpld_intr_name = [
            "op2", "cpld_1_2", "cpld_3", "cpld_4", "cpld_5", "j2"
        ]
        cpld_intr = {}
        try:
            cpld_intr_val = self.ioexp.get_cpld_to_cpu_intr()
            for i in range(len(cpld_intr_val)):
                cpld_intr[cpld_intr_name[i]] = cpld_intr_val[i]

            return cpld_intr

        except Exception as e:
            self.logger.error(
                "get_cpld_to_cpu_intr failed, error: {}".format(e))

    def get_all_cpld_intr(self):
        cpld_name = "cpld_"
        all_cpld_intr = {}
        try:
            for i in range(CPLDConst.CPLD_MAX):
                cpld_intr = self.get_cpld_intr(i)
                all_cpld_intr[cpld_name + str(i + 1)] = cpld_intr

            return all_cpld_intr
        except Exception as e:
            self.logger.error("get_cpld_intr failed, error: {}".format(e))

    def get_cpld_intr(self, cpld_num):
        cpld_intr_name = [
            "port_intr", "gearbox", "usb", "port_presence", "psu0", "psu1",
            "pex8724", "cs4227", "retimer"
        ]
        cpld_intr = {}
        try:
            intr_reg = self.cpld.get_intr_reg(cpld_num, 0)

            if cpld_num == CPLDConst.CPLD_1:
                intr_reg_2 = self.cpld.get_intr_reg(cpld_num, 1)

                for i in range(8):
                    cpld_intr[cpld_intr_name[i]] = intr_reg >> i & 0b1

                cpld_intr[cpld_intr_name[8]] = intr_reg_2 & 0b1
            else:
                cpld_intr[cpld_intr_name[0]] = intr_reg >> 0 & 0b1
                cpld_intr[cpld_intr_name[3]] = intr_reg >> 3 & 0b1

            return cpld_intr

        except Exception as e:
            self.logger.error("get_cpld_intr failed, error: {}".format(e))

    def clear_all_intr(self):
        try:
            for i in range(CPLDConst.CPLD_MAX):
                self.get_cpld_intr(i)
            self.clear_i2c_alert()

        except Exception as e:
            self.logger.error("clear_all_intr failed, error: {}".format(e))

    def get_gbox_intr(self):
        gbox_name = "gearbox"
        gbox_intr = {}
        gbox_max_1 = 8
        gbox_max_2 = 2

        try:
            reg1, reg2 = self.cpld.gbox_get_intr()

            for i in range(gbox_max_1):
                gbox_intr[gbox_name + "_" + str(i)] = reg1 >> i & 0b1

            for i in range(gbox_max_2):
                gbox_intr[gbox_name + "_" +
                          str(gbox_max_1 + i)] = reg2 >> i & 0b1

            return gbox_intr
        except Exception as e:
            self.logger.error("get_gbox_intr failed, error: {}".format(e))

    def get_retimer_intr(self):
        retimer_name = "retimer"
        retimer_intr = {}
        retimer_max = 5

        try:
            reg = self.cpld.retimer_get_intr()

            for i in range(retimer_max):
                retimer_intr[retimer_name + "_" + str(i)] = reg >> i & 0b1

            return retimer_intr
        except Exception as e:
            self.logger.error("get_retimer_intr failed, error: {}".format(e))
 def __init__(self):
     log = Logger(__name__)
     self.logger = log.getLogger()
     self.ioexp = IOExpander()
     self.cpld = CPLD()
class SFPUtility:
    def __init__(self):
        log = Logger(__name__)
        self.logger = log.getLogger()
        self.ioexp = IOExpander()
        self.cpld = CPLD()

    def _check_sfp_port(self, port):
        if port not in range(SFP.MAX_PORT):
            raise ValueError("Port number({0}) is out of range (0-{1})".format(
                port, SFP.MAX_PORT - 1))

    def get_presence(self, port_num):
        try:
            #get hw_rev
            board_info = self.cpld.get_board_info()

            #not proto board
            if board_info["hw_rev"] != 0b00:
                ret_val = {"presence": "not supported"}
                return ret_val

            self._check_sfp_port(port_num)

            result = self.cpld.sfp_get_presence(port_num)

            if result == PortStatus.PORT_ABSENCE:
                ret_val = {"presence": "absence"}
            else:
                ret_val = {"presence": "presence"}

            return ret_val
        except Exception as e:
            self.logger.error(
                "get_presence failed, port_num={0}, error: {1}".format(
                    port_num, e))

    def get_rx_los(self, port_num):
        try:
            self._check_sfp_port(port_num)

            result = self.cpld.sfp_get_rx_los(port_num)

            if result == SFP.DETECTED:
                ret_val = {"rx_los": "detected"}
            else:
                ret_val = {"rx_los": "undetected"}

            return ret_val
        except Exception as e:
            self.logger.error(
                "get_rx_los failed, port_num={0}, error: {1}".format(
                    port_num, e))

    def get_tx_fault(self, port_num):
        try:
            self._check_sfp_port(port_num)

            result = self.cpld.sfp_get_tx_fault(port_num)

            if result == SFP.DETECTED:
                ret_val = {"tx_flt": "detected"}
            else:
                ret_val = {"tx_flt": "undetected"}

            return ret_val
        except Exception as e:
            self.logger.error(
                "get_tx_fault failed, port_num={0}, error: {1}".format(
                    port_num, e))

    def set_tx_disable(self, port_num, tx_disable):
        try:
            self._check_sfp_port(port_num)

            if tx_disable not in range(SFP.DISABLED + 1):
                raise ValueError(
                    "tx_disable ({0}) is out of range (0-{1})".format(
                        tx_disable, SFP.DISABLED))

            self.cpld.sfp_set_tx_disable(port_num, tx_disable)
        except Exception as e:
            self.logger.error(
                "set_tx_disable failed, port_num={0}, tx_disable={1}, error: {2}"
                .format(port_num, tx_disable, e))

    def get_tx_disable(self, port_num):
        try:
            self._check_sfp_port(port_num)

            result = self.cpld.sfp_get_tx_disable(port_num)

            if result == PortStatus.ENABLED:
                ret_val = {"tx_disable": "enabled"}
            else:
                ret_val = {"tx_disable": "disabled"}

            return ret_val
        except Exception as e:
            self.logger.error(
                "get_tx_disable failed, port_num={0}, error: {1}".format(
                    port_num, e))