<commit_before>/*
 *  nextpnr -- Next Generation Place and Route
 *
 *  Copyright (C) 2021  Symbiflow Authors
 *
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "log.h"
#include "nextpnr.h"
#include "util.h"

#include <queue>

NEXTPNR_NAMESPACE_BEGIN

namespace {
bool search_routing_for_placement(Arch *arch, WireId start_wire, CellInfo *cell, IdString cell_pin, bool downhill)
{
    std::queue<WireId> visit_queue;
    pool<WireId> already_visited;
    visit_queue.push(start_wire);
    already_visited.insert(start_wire);
    int iter = 0;
    while (!visit_queue.empty() && iter++ < 1000) {
        WireId next = visit_queue.front();
        visit_queue.pop();
        for (auto bp : arch->getWireBelPins(next)) {
            if (!arch->isValidBelForCellType(cell->type, bp.bel))
                continue;
            if (!arch->checkBelAvail(bp.bel))
                continue;
            // We need to do a test placement to update the bel pin map
            arch->bindBel(bp.bel, cell, STRENGTH_FIXED);
            for (IdString bel_pin : arch->getBelPinsForCellPin(cell, cell_pin)) {
                if (bel_pin == bp.pin)
                    return true;
            }
            // Bel pin doesn't match
            arch->unbindBel(bp.bel);
        }
        auto do_visit = [&](PipId pip) {
            WireId dst = downhill ? arch->getPipDstWire(pip) : arch->getPipSrcWire(pip);
            if (already_visited.count(dst))
                return;
            if (!arch->is_site_wire(dst) && arch->get_wire_category(dst) == WIRE_CAT_GENERAL)
                return; // this pass only considers dedicated routing
            visit_queue.push(dst);
            already_visited.insert(dst);
        };
        if (downhill) {
            for (auto pip : arch->getPipsDownhill(next))
                do_visit(pip);
        } else {
            for (auto pip : arch->getPipsUphill(next))
                do_visit(pip);
        }
    }
    return false;
}
} // namespace

void Arch::place_iobufs(WireId pad_wire, NetInfo *net,
                        const dict<CellInfo *, IdString, hash_ptr_ops> &tightly_attached_bels,
                        pool<CellInfo *, hash_ptr_ops> *placed_cells)
{
    Context *ctx = getCtx();
    for (auto cell_port : tightly_attached_bels) {
        bool downhill = (cell_port.first->ports.at(cell_port.second).type != PORT_OUT);
        if (search_routing_for_placement(this, pad_wire, cell_port.first, cell_port.second, downhill)) {
            if (ctx->verbose)
                log_info("Placed IO cell %s:%s at %s.\n", ctx->nameOf(cell_port.first),
                         ctx->nameOf(cell_port.first->type), ctx->nameOfBel(cell_port.first->bel));
        }
    }

    // Also try, on a best-effort basis, to preplace other cells in the macro based on downstream routing. This is
    // needed for the split INBUF+IBUFCTRL arrangement in the UltraScale+, as just placing the INBUF will result in an
    // unrouteable site and illegal placement.
    std::queue<CellInfo *> place_queue;
    for (auto pc : *placed_cells)
        place_queue.push(pc);
    while (!place_queue.empty()) {
        CellInfo *cursor = place_queue.front();
        place_queue.pop();
        // Ignore cells not part of a macro
        if (cursor->macro_parent == IdString())
            continue;
        for (auto &port : cursor->ports) {
            // Only consider routing downstream from outputs for now
            if (port.second.type != PORT_OUT || port.second.net == nullptr)
                continue;
            NetInfo *ni = port.second.net;
            WireId src_wire = ctx->getNetinfoSourceWire(ni);
            for (auto &usr : ni->users) {
                // Look for unplaced users in the same macro
                if (usr.cell->bel != BelId() || usr.cell->macro_parent != cursor->macro_parent)
                    continue;
                // Try and place using dedicated routing
                if (search_routing_for_placement(this, src_wire, usr.cell, usr.port, true)) {
                    // Successful
                    placed_cells->insert(usr.cell);
                    place_queue.push(usr.cell);
                    if (ctx->verbose)
                        log_info("Placed %s at %s based on dedicated IO macro routing.\n", ctx->nameOf(usr.cell),
                                 ctx->nameOfBel(usr.cell->bel));
                }
            }
        }
    }
    // TODO: for even more complex cases, if any future devices hit them, we probably should do a full validity check of
    // all placed cells here, and backtrack and try a different placement if the first one we choose isn't legal overall
}

void Arch::pack_ports()
{
    dict<IdString, const TileInstInfoPOD *> tile_type_prototypes;
    for (size_t i = 0; i < chip_info->tiles.size(); ++i) {
        const auto &tile = chip_info->tiles[i];
        const auto &tile_type = chip_info->tile_types[tile.type];
        IdString tile_type_name(tile_type.name);
        tile_type_prototypes.emplace(tile_type_name, &tile);
    }

    // set(site_types) for package pins
    pool<IdString> package_sites;
    // Package pin -> (Site type -> BelId)
    dict<IdString, std::vector<std::pair<IdString, BelId>>> package_pin_bels;
    for (const PackagePinPOD &package_pin : chip_info->packages[package_index].pins) {
        IdString pin(package_pin.package_pin);
        IdString bel(package_pin.bel);

        IdString site(package_pin.site);
        package_sites.emplace(site);

        for (size_t i = 0; i < chip_info->tiles.size(); ++i) {
            const auto &tile = chip_info->tiles[i];
            pool<uint32_t> package_pin_sites;
            for (size_t j = 0; j < tile.sites.size(); ++j) {
                auto &site_data = chip_info->sites[tile.sites[j]];
                if (site == id(site_data.site_name.get())) {
                    package_pin_sites.emplace(j);
                }
            }

            const auto &tile_type = chip_info->tile_types[tile.type];
            for (size_t j = 0; j < tile_type.bel_data.size(); ++j) {
                const BelInfoPOD &bel_data = tile_type.bel_data[j];
                if (bel == IdString(bel_data.name) && package_pin_sites.count(bel_data.site)) {
                    auto &site_data = chip_info->sites[tile.sites[bel_data.site]];
                    IdString site_type(site_data.site_type);
                    BelId bel;
                    bel.tile = i;
                    bel.index = j;
                    package_pin_bels[pin].push_back(std::make_pair(site_type, bel));
                }
            }
        }
    }

    // Determine for each package site type, which site types are possible.
    pool<IdString> package_pin_site_types;
    dict<IdString, pool<IdString>> possible_package_site_types;
    for (const TileInstInfoPOD &tile : chip_info->tiles) {
        for (size_t site_index : tile.sites) {
            const SiteInstInfoPOD &site = chip_info->sites[site_index];
            IdString site_name = getCtx()->id(site.site_name.get());
            if (package_sites.count(site_name) == 1) {
                possible_package_site_types[site_name].emplace(IdString(site.site_type));
                package_pin_site_types.emplace(IdString(site.site_type));
            }
        }
    }

    // IO sites are usually pretty weird, so see if we can define some
    // constraints between the port cell create by nextpnr and cells that are
    // immediately attached to that port cell.
    for (auto port_pair : port_cells) {
        IdString port_name = port_pair.first;
        CellInfo *port_cell = port_pair.second;
        dict<CellInfo *, IdString, hash_ptr_ops> tightly_attached_bels;

        for (auto port_pair : port_cell->ports) {
            const PortInfo &port_info = port_pair.second;
            const NetInfo *net = port_info.net;
            if (net->driver.cell) {
                tightly_attached_bels.emplace(net->driver.cell, net->driver.port);
            }

            for (const PortRef &port_ref : net->users) {
                if (port_ref.cell) {
                    tightly_attached_bels.emplace(port_ref.cell, port_ref.port);
                }
            }
        }

        if (getCtx()->verbose) {
            log_info("Tightly attached BELs for port %s\n", port_name.c_str(getCtx()));
            for (auto cell_port : tightly_attached_bels) {
                log_info(" - %s : %s\n", cell_port.first->name.c_str(getCtx()), cell_port.first->type.c_str(getCtx()));
            }
        }

        NPNR_ASSERT(tightly_attached_bels.erase(port_cell) == 1);
        pool<IdString> cell_types_in_io_group;
        for (auto cell_port : tightly_attached_bels) {
            NPNR_ASSERT(port_cells.find(cell_port.first->name) == port_cells.end());
            cell_types_in_io_group.emplace(cell_port.first->type);
        }

        // Get possible placement locations for tightly coupled BELs with
        // port.
        pool<IdString> possible_site_types;
        for (const TileTypeInfoPOD &tile_type : chip_info->tile_types) {
            IdString tile_type_name(tile_type.name);
            for (const BelInfoPOD &bel_info : tile_type.bel_data) {
                if (bel_info.category != BEL_CATEGORY_LOGIC) {
                    break;
                }

                for (IdString cell_type : cell_types_in_io_group) {
                    size_t cell_type_index = get_cell_type_index(cell_type);
                    if (bel_info.category == BEL_CATEGORY_LOGIC && bel_info.pin_map[cell_type_index] != -1) {
                        auto *tile = tile_type_prototypes.at(tile_type_name);
                        const SiteInstInfoPOD &site = chip_info->sites[tile->sites[bel_info.site]];

                        IdString site_type(site.site_type);
                        if (package_pin_site_types.count(site_type)) {
                            possible_site_types.emplace(site_type);
                        }
                    }
                }
            }
        }

        if (possible_site_types.empty()) {
            log_error("Port '%s' has no possible site types!\n", port_name.c_str(getCtx()));
        }

        if (getCtx()->verbose) {
            log_info("Possible site types for port %s\n", port_name.c_str(getCtx()));
            for (IdString site_type : possible_site_types) {
                log_info(" - %s\n", site_type.c_str(getCtx()));
            }
        }

        auto iter = port_cell->attrs.find(id("PACKAGE_PIN"));
        if (iter == port_cell->attrs.end()) {
            iter = port_cell->attrs.find(id("LOC"));
            if (iter == port_cell->attrs.end()) {
                log_error("Port '%s' is missing PACKAGE_PIN or LOC property\n", port_cell->name.c_str(getCtx()));
            }
        }

        // dict<IdString, dict<IdString, BelId>> package_pin_bels;
        IdString package_pin_id = id(iter->second.as_string());
        auto pin_iter = package_pin_bels.find(package_pin_id);
        if (pin_iter == package_pin_bels.end()) {
            log_error("Package pin '%s' not found in part %s\n", package_pin_id.c_str(getCtx()), get_part().c_str());
        }
        NPNR_ASSERT(pin_iter != package_pin_bels.end());

        // Select the first BEL from package_bel_pins that is a legal site
        // type.
        //
        // This is likely the most generic (versus specialized) site type.
        BelId package_bel;
        for (auto site_type_and_bel : pin_iter->second) {
            IdString legal_site_type = site_type_and_bel.first;
            BelId bel = site_type_and_bel.second;

            if (possible_site_types.count(legal_site_type)) {
                // FIXME: Need to handle case where a port can be in multiple
                // modes, but only one of the modes works.
                package_bel = bel;
                break;
            }
        }

        if (package_bel == BelId()) {
            log_info("Failed to find BEL for package pin '%s' in any possible site types:\n",
                     package_pin_id.c_str(getCtx()));
            for (IdString site_type : possible_site_types) {
                log_info(" - %s\n", site_type.c_str(getCtx()));
            }
            log_error("Failed to find BEL for package pin '%s'\n", package_pin_id.c_str(getCtx()));
        }

        if (getCtx()->verbose) {
            log_info("Binding port %s to BEL %s\n", port_name.c_str(getCtx()), getCtx()->nameOfBel(package_bel));
        }

        pool<CellInfo *, hash_ptr_ops> placed_cells;
        bindBel(package_bel, port_cell, STRENGTH_FIXED);
        placed_cells.emplace(port_cell);

        IdStringRange package_bel_pins = getBelPins(package_bel);
        IdString pad_pin = get_only_value(package_bel_pins);

        WireId pad_wire = getBelPinWire(package_bel, pad_pin);
        place_iobufs(pad_wire, ports[port_pair.first].net, tightly_attached_bels, &placed_cells);

        for (CellInfo *cell : placed_cells) {
            NPNR_ASSERT(cell->bel != BelId());
            if (!isBelLocationValid(cell->bel)) {
                log_error("Tightly bound BEL %s was not valid!\n", nameOfBel(cell->bel));
            }
        }
    }
}

NEXTPNR_NAMESPACE_END
<commit_msg>interchange: Place DIFFINBUF and IBUFCTRL for UltraScale+ IBUFDS<commit_after>/*
 *  nextpnr -- Next Generation Place and Route
 *
 *  Copyright (C) 2021  Symbiflow Authors
 *
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "log.h"
#include "nextpnr.h"
#include "util.h"

#include <queue>

NEXTPNR_NAMESPACE_BEGIN

namespace {
bool search_routing_for_placement(Arch *arch, WireId start_wire, CellInfo *cell, IdString cell_pin, bool downhill)
{
    std::queue<WireId> visit_queue;
    pool<WireId> already_visited;
    visit_queue.push(start_wire);
    already_visited.insert(start_wire);
    int iter = 0;
    while (!visit_queue.empty() && iter++ < 1000) {
        WireId next = visit_queue.front();
        visit_queue.pop();
        for (auto bp : arch->getWireBelPins(next)) {
            if (!arch->isValidBelForCellType(cell->type, bp.bel))
                continue;
            if (!arch->checkBelAvail(bp.bel))
                continue;
            // We need to do a test placement to update the bel pin map
            arch->bindBel(bp.bel, cell, STRENGTH_FIXED);
            for (IdString bel_pin : arch->getBelPinsForCellPin(cell, cell_pin)) {
                if (bel_pin == bp.pin)
                    return true;
            }
            // Bel pin doesn't match
            arch->unbindBel(bp.bel);
        }
        auto do_visit = [&](PipId pip) {
            WireId dst = downhill ? arch->getPipDstWire(pip) : arch->getPipSrcWire(pip);
            if (already_visited.count(dst))
                return;
            visit_queue.push(dst);
            already_visited.insert(dst);
        };
        if (downhill) {
            for (auto pip : arch->getPipsDownhill(next))
                do_visit(pip);
        } else {
            for (auto pip : arch->getPipsUphill(next))
                do_visit(pip);
        }
    }
    return false;
}
} // namespace

void Arch::place_iobufs(WireId pad_wire, NetInfo *net,
                        const dict<CellInfo *, IdString, hash_ptr_ops> &tightly_attached_bels,
                        pool<CellInfo *, hash_ptr_ops> *placed_cells)
{
    Context *ctx = getCtx();
    for (auto cell_port : tightly_attached_bels) {
        bool downhill = (cell_port.first->ports.at(cell_port.second).type != PORT_OUT);
        if (search_routing_for_placement(this, pad_wire, cell_port.first, cell_port.second, downhill)) {
            if (ctx->verbose)
                log_info("Placed IO cell %s:%s at %s.\n", ctx->nameOf(cell_port.first),
                         ctx->nameOf(cell_port.first->type), ctx->nameOfBel(cell_port.first->bel));
            placed_cells->insert(cell_port.first);
        }
    }

    // Also try, on a best-effort basis, to preplace other cells in the macro based on downstream routing. This is
    // needed for the split INBUF+IBUFCTRL arrangement in the UltraScale+, as just placing the INBUF will result in an
    // unrouteable site and illegal placement.
    std::queue<CellInfo *> place_queue;
    for (auto pc : *placed_cells)
        place_queue.push(pc);
    while (!place_queue.empty()) {
        CellInfo *cursor = place_queue.front();
        place_queue.pop();
        // Ignore cells not part of a macro
        if (cursor->macro_parent == IdString())
            continue;
        for (auto &port : cursor->ports) {
            // Only consider routing downstream from outputs for now
            if (port.second.type != PORT_OUT || port.second.net == nullptr)
                continue;
            NetInfo *ni = port.second.net;
            WireId src_wire = ctx->getNetinfoSourceWire(ni);
            for (auto &usr : ni->users) {
                // Look for unplaced users in the same macro
                if (usr.cell->bel != BelId() || usr.cell->macro_parent != cursor->macro_parent)
                    continue;
                // Try and place using dedicated routing
                if (search_routing_for_placement(this, src_wire, usr.cell, usr.port, true)) {
                    // Successful
                    placed_cells->insert(usr.cell);
                    place_queue.push(usr.cell);
                    if (ctx->verbose)
                        log_info("Placed %s at %s based on dedicated IO macro routing.\n", ctx->nameOf(usr.cell),
                                 ctx->nameOfBel(usr.cell->bel));
                }
            }
        }
    }
    // TODO: for even more complex cases, if any future devices hit them, we probably should do a full validity check of
    // all placed cells here, and backtrack and try a different placement if the first one we choose isn't legal overall
}

void Arch::pack_ports()
{
    dict<IdString, const TileInstInfoPOD *> tile_type_prototypes;
    for (size_t i = 0; i < chip_info->tiles.size(); ++i) {
        const auto &tile = chip_info->tiles[i];
        const auto &tile_type = chip_info->tile_types[tile.type];
        IdString tile_type_name(tile_type.name);
        tile_type_prototypes.emplace(tile_type_name, &tile);
    }

    // set(site_types) for package pins
    pool<IdString> package_sites;
    // Package pin -> (Site type -> BelId)
    dict<IdString, std::vector<std::pair<IdString, BelId>>> package_pin_bels;
    for (const PackagePinPOD &package_pin : chip_info->packages[package_index].pins) {
        IdString pin(package_pin.package_pin);
        IdString bel(package_pin.bel);

        IdString site(package_pin.site);
        package_sites.emplace(site);

        for (size_t i = 0; i < chip_info->tiles.size(); ++i) {
            const auto &tile = chip_info->tiles[i];
            pool<uint32_t> package_pin_sites;
            for (size_t j = 0; j < tile.sites.size(); ++j) {
                auto &site_data = chip_info->sites[tile.sites[j]];
                if (site == id(site_data.site_name.get())) {
                    package_pin_sites.emplace(j);
                }
            }

            const auto &tile_type = chip_info->tile_types[tile.type];
            for (size_t j = 0; j < tile_type.bel_data.size(); ++j) {
                const BelInfoPOD &bel_data = tile_type.bel_data[j];
                if (bel == IdString(bel_data.name) && package_pin_sites.count(bel_data.site)) {
                    auto &site_data = chip_info->sites[tile.sites[bel_data.site]];
                    IdString site_type(site_data.site_type);
                    BelId bel;
                    bel.tile = i;
                    bel.index = j;
                    package_pin_bels[pin].push_back(std::make_pair(site_type, bel));
                }
            }
        }
    }

    // Determine for each package site type, which site types are possible.
    pool<IdString> package_pin_site_types;
    dict<IdString, pool<IdString>> possible_package_site_types;
    for (const TileInstInfoPOD &tile : chip_info->tiles) {
        for (size_t site_index : tile.sites) {
            const SiteInstInfoPOD &site = chip_info->sites[site_index];
            IdString site_name = getCtx()->id(site.site_name.get());
            if (package_sites.count(site_name) == 1) {
                possible_package_site_types[site_name].emplace(IdString(site.site_type));
                package_pin_site_types.emplace(IdString(site.site_type));
            }
        }
    }

    // IO sites are usually pretty weird, so see if we can define some
    // constraints between the port cell create by nextpnr and cells that are
    // immediately attached to that port cell.
    for (auto port_pair : port_cells) {
        IdString port_name = port_pair.first;
        CellInfo *port_cell = port_pair.second;
        dict<CellInfo *, IdString, hash_ptr_ops> tightly_attached_bels;

        for (auto port_pair : port_cell->ports) {
            const PortInfo &port_info = port_pair.second;
            const NetInfo *net = port_info.net;
            if (net->driver.cell) {
                tightly_attached_bels.emplace(net->driver.cell, net->driver.port);
            }

            for (const PortRef &port_ref : net->users) {
                if (port_ref.cell) {
                    tightly_attached_bels.emplace(port_ref.cell, port_ref.port);
                }
            }
        }

        if (getCtx()->verbose) {
            log_info("Tightly attached BELs for port %s\n", port_name.c_str(getCtx()));
            for (auto cell_port : tightly_attached_bels) {
                log_info(" - %s : %s\n", cell_port.first->name.c_str(getCtx()), cell_port.first->type.c_str(getCtx()));
            }
        }

        NPNR_ASSERT(tightly_attached_bels.erase(port_cell) == 1);
        pool<IdString> cell_types_in_io_group;
        for (auto cell_port : tightly_attached_bels) {
            NPNR_ASSERT(port_cells.find(cell_port.first->name) == port_cells.end());
            cell_types_in_io_group.emplace(cell_port.first->type);
        }

        // Get possible placement locations for tightly coupled BELs with
        // port.
        pool<IdString> possible_site_types;
        for (const TileTypeInfoPOD &tile_type : chip_info->tile_types) {
            IdString tile_type_name(tile_type.name);
            for (const BelInfoPOD &bel_info : tile_type.bel_data) {
                if (bel_info.category != BEL_CATEGORY_LOGIC) {
                    break;
                }

                for (IdString cell_type : cell_types_in_io_group) {
                    size_t cell_type_index = get_cell_type_index(cell_type);
                    if (bel_info.category == BEL_CATEGORY_LOGIC && bel_info.pin_map[cell_type_index] != -1) {
                        auto *tile = tile_type_prototypes.at(tile_type_name);
                        const SiteInstInfoPOD &site = chip_info->sites[tile->sites[bel_info.site]];

                        IdString site_type(site.site_type);
                        if (package_pin_site_types.count(site_type)) {
                            possible_site_types.emplace(site_type);
                        }
                    }
                }
            }
        }

        if (possible_site_types.empty()) {
            if (getCtx()->verbose)
                log_info("Port '%s' has no possible site types, falling back to all types!\n", port_name.c_str(getCtx()));
            possible_site_types = package_pin_site_types;
        }

        if (getCtx()->verbose) {
            log_info("Possible site types for port %s\n", port_name.c_str(getCtx()));
            for (IdString site_type : possible_site_types) {
                log_info(" - %s\n", site_type.c_str(getCtx()));
            }
        }

        auto iter = port_cell->attrs.find(id("PACKAGE_PIN"));
        if (iter == port_cell->attrs.end()) {
            iter = port_cell->attrs.find(id("LOC"));
            if (iter == port_cell->attrs.end()) {
                log_error("Port '%s' is missing PACKAGE_PIN or LOC property\n", port_cell->name.c_str(getCtx()));
            }
        }

        // dict<IdString, dict<IdString, BelId>> package_pin_bels;
        IdString package_pin_id = id(iter->second.as_string());
        auto pin_iter = package_pin_bels.find(package_pin_id);
        if (pin_iter == package_pin_bels.end()) {
            log_error("Package pin '%s' not found in part %s\n", package_pin_id.c_str(getCtx()), get_part().c_str());
        }
        NPNR_ASSERT(pin_iter != package_pin_bels.end());

        // Select the first BEL from package_bel_pins that is a legal site
        // type.
        //
        // This is likely the most generic (versus specialized) site type.
        BelId package_bel;
        for (auto site_type_and_bel : pin_iter->second) {
            IdString legal_site_type = site_type_and_bel.first;
            BelId bel = site_type_and_bel.second;

            if (possible_site_types.count(legal_site_type)) {
                // FIXME: Need to handle case where a port can be in multiple
                // modes, but only one of the modes works.
                package_bel = bel;
                break;
            }
        }

        if (package_bel == BelId()) {
            log_info("Failed to find BEL for package pin '%s' in any possible site types:\n",
                     package_pin_id.c_str(getCtx()));
            for (IdString site_type : possible_site_types) {
                log_info(" - %s\n", site_type.c_str(getCtx()));
            }
            log_error("Failed to find BEL for package pin '%s'\n", package_pin_id.c_str(getCtx()));
        }

        if (getCtx()->verbose) {
            log_info("Binding port %s to BEL %s\n", port_name.c_str(getCtx()), getCtx()->nameOfBel(package_bel));
        }

        pool<CellInfo *, hash_ptr_ops> placed_cells;
        bindBel(package_bel, port_cell, STRENGTH_FIXED);
        placed_cells.emplace(port_cell);

        IdStringRange package_bel_pins = getBelPins(package_bel);
        IdString pad_pin = get_only_value(package_bel_pins);

        WireId pad_wire = getBelPinWire(package_bel, pad_pin);
        place_iobufs(pad_wire, ports[port_pair.first].net, tightly_attached_bels, &placed_cells);

        for (CellInfo *cell : placed_cells) {
            NPNR_ASSERT(cell->bel != BelId());
            if (!isBelLocationValid(cell->bel)) {
                log_error("Tightly bound BEL %s was not valid!\n", nameOfBel(cell->bel));
            }
        }
    }
}

NEXTPNR_NAMESPACE_END
<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2017, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */
#include "AuxiliaryCPUThreadPool.h"

namespace facebook {
namespace memcache {
namespace mcrouter {

// Number of CPU threads to run in CPU thread pool.
constexpr size_t kNumCPUThreads = 5;

namespace {
folly::Singleton<AuxiliaryCPUThreadPool> gAuxiliaryCPUThreadPool;
} // anonymous

wangle::CPUThreadPoolExecutor& AuxiliaryCPUThreadPool::getThreadPool() {
  folly::call_once(initFlag_, [&] {
    threadPool_ = std::make_unique<wangle::CPUThreadPoolExecutor>(
        kNumCPUThreads,
        std::make_shared<wangle::NamedThreadFactory>("mcr-cpuaux-"));
  });

  return *threadPool_;
}

} // mcrouter
} // memcache
} // facebook
<commit_msg>CodeMod: Replace uses of wangle::NamedThreadFactory<commit_after>/*
 *  Copyright (c) 2017, Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the BSD-style license found in the
 *  LICENSE file in the root directory of this source tree. An additional grant
 *  of patent rights can be found in the PATENTS file in the same directory.
 *
 */
#include "AuxiliaryCPUThreadPool.h"

namespace facebook {
namespace memcache {
namespace mcrouter {

// Number of CPU threads to run in CPU thread pool.
constexpr size_t kNumCPUThreads = 5;

namespace {
folly::Singleton<AuxiliaryCPUThreadPool> gAuxiliaryCPUThreadPool;
} // anonymous

wangle::CPUThreadPoolExecutor& AuxiliaryCPUThreadPool::getThreadPool() {
  folly::call_once(initFlag_, [&] {
    threadPool_ = std::make_unique<wangle::CPUThreadPoolExecutor>(
        kNumCPUThreads,
        std::make_shared<folly::NamedThreadFactory>("mcr-cpuaux-"));
  });

  return *threadPool_;
}

} // mcrouter
} // memcache
} // facebook
<|endoftext|>


<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// File Monodomain.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// 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.
//
// Description: Monodomain cardiac electrophysiology homogenised model.
//
///////////////////////////////////////////////////////////////////////////////

#include <iostream>

#include <CardiacEPSolver/EquationSystems/Monodomain.h>
#include <CardiacEPSolver/Filters/FilterCheckpointCellModel.h>

namespace Nektar
{
    /**
     * @class Monodomain
     *
     * Base model of cardiac electrophysiology of the form
     * \f{align*}{
     *     \frac{\partial u}{\partial t} = \nabla^2 u + J_{ion},
     * \f}
     * where the reaction term, \f$J_{ion}\f$ is defined by a specific cell
     * model.
     *
     * This implementation, at present, treats the reaction terms explicitly
     * and the diffusive element implicitly.
     */

    /**
     * Registers the class with the Factory.
     */
    string Monodomain::className
            = GetEquationSystemFactory().RegisterCreatorFunction(
                "Monodomain",
                Monodomain::create,
                "Monodomain model of cardiac electrophysiology.");

    /**
     *
     */
    Monodomain::Monodomain(
            const LibUtilities::SessionReaderSharedPtr& pSession)
        : UnsteadySystem(pSession)
    {
    }

    /**
     *
     */
    void Monodomain::v_InitObject()
    {
        UnsteadySystem::v_InitObject();

        m_session->LoadParameter("Chi",        m_chi);
        m_session->LoadParameter("Cm",         m_capMembrane);

        std::string vCellModel;
        m_session->LoadSolverInfo("CELLMODEL", vCellModel, "");

        ASSERTL0(vCellModel != "", "Cell Model not specified.");

        m_cell = GetCellModelFactory().CreateInstance(
                                        vCellModel, m_session, m_fields[0]);

        m_intVariables.push_back(0);

        // Load variable coefficients
        StdRegions::VarCoeffType varCoeffEnum[6] = {
                StdRegions::eVarCoeffD00,
                StdRegions::eVarCoeffD01,
                StdRegions::eVarCoeffD11,
                StdRegions::eVarCoeffD02,
                StdRegions::eVarCoeffD12,
                StdRegions::eVarCoeffD22
        };
        std::string varCoeffString[6] = {"xx","xy","yy","xz","yz","zz"};
        std::string aniso_var[3] = {"fx", "fy", "fz"};

        const int nq            = m_fields[0]->GetNpoints();
        const int nVarDiffCmpts = m_spacedim * (m_spacedim + 1) / 2;

        // Allocate storage for variable coeffs and initialize to 1.
        for (int i = 0, k = 0; i < m_spacedim; ++i)
        {
            for (int j = 0; j < i+1; ++j)
            {
                if (i == j)
                {
                    m_vardiff[varCoeffEnum[k]] = Array<OneD, NekDouble>(nq, 1.0);
                }
                else
                {
                    m_vardiff[varCoeffEnum[k]] = Array<OneD, NekDouble>(nq, 0.0);
                }
                ++k;
            }
        }

        // Apply fibre map f \in [0,1], scale to conductivity range
        // [o_min,o_max], specified by the session parameters o_min and o_max
        if (m_session->DefinesFunction("AnisotropicConductivity"))
        {
            if (m_session->DefinesCmdLineArgument("verbose"))
            {
                cout << "Loading Anisotropic Fibre map." << endl;
            }

            NekDouble   o_min        = m_session->GetParameter("o_min");
            NekDouble   o_max        = m_session->GetParameter("o_max");
            int         k            = 0;

            Array<OneD, NekDouble> vTemp_i;
            Array<OneD, NekDouble> vTemp_j;

            /*
             * Diffusivity matrix D is upper triangular and defined as
             *    d_00   d_01  d_02
             *           d_11  d_12
             *                 d_22
             *
             * Given a principle fibre direction _f_ the diffusivity is given
             * by
             *    d_ij = { D_2 + (D_1 - D_2) f_i f_j   if i==j
             *           {       (D_1 - D_2) f_i f_j   if i!=j
             *
             * The vector _f_ is given in terms of the variables fx,fy,fz in the
             * function AnisotropicConductivity. The values of D_1 and D_2 are
             * the parameters o_max and o_min, respectively.
             */

            // Loop through columns of D
            for (int j = 0; j < m_spacedim; ++j)
            {
                ASSERTL0(m_session->DefinesFunction("AnisotropicConductivity",
                                                    aniso_var[j]),
                         "Function 'AnisotropicConductivity' not correctly "
                         "defined.");
                EvaluateFunction(aniso_var[j], vTemp_j,
                                 "AnisotropicConductivity");

                // Loop through rows of D
                for (int i = 0; i < j + 1; ++i)
                {
                    ASSERTL0(m_session->DefinesFunction(
                                        "AnisotropicConductivity",aniso_var[i]),
                             "Function 'AnisotropicConductivity' not correctly "
                             "defined.");
                    EvaluateFunction(aniso_var[i], vTemp_i,
                                     "AnisotropicConductivity");

                    Vmath::Vmul(nq, vTemp_i, 1, vTemp_j, 1,
                                    m_vardiff[varCoeffEnum[k]], 1);

                    Vmath::Smul(nq, o_max-o_min,
                                    m_vardiff[varCoeffEnum[k]], 1,
                                    m_vardiff[varCoeffEnum[k]], 1);

                    if (i == j)
                    {
                        Vmath::Sadd(nq, o_min,
                                        m_vardiff[varCoeffEnum[k]], 1,
                                        m_vardiff[varCoeffEnum[k]], 1);
                    }

                    ++k;
                }
            }
        }

        // Scale by scar map (range 0->1) derived from intensity map
        // (range d_min -> d_max)
        if (m_session->DefinesFunction("IsotropicConductivity"))
        {
            if (m_session->DefinesCmdLineArgument("verbose"))
            {
                cout << "Loading Isotropic Conductivity map." << endl;
            }

            const std::string varName  = "intensity";
            const NekDouble   f_min    = m_session->GetParameter("d_min");
            const NekDouble   f_max    = m_session->GetParameter("d_max");
            const NekDouble   scar_min = 0.0;
            const NekDouble   scar_max = 1.0;

            Array<OneD, NekDouble> vTemp;
            EvaluateFunction(varName, vTemp, "IsotropicConductivity");

            // Threshold based on d_min, d_max
            for (int j = 0; j < nq; ++j)
            {
                vTemp[j] = (vTemp[j] < f_min ? f_min : vTemp[j]);
                vTemp[j] = (vTemp[j] > f_max ? f_max : vTemp[j]);
            }

            // Rescale to s \in [0,1] (0 maps to d_max, 1 maps to d_min)
            Vmath::Sadd(nq, -f_min, vTemp, 1, vTemp, 1);
            Vmath::Smul(nq, -1.0/(f_max-f_min), vTemp, 1, vTemp, 1);
            Vmath::Sadd(nq, 1.0, vTemp, 1, vTemp, 1);
            Vmath::Smul(nq, scar_max - scar_min, vTemp, 1, vTemp, 1);
            Vmath::Sadd(nq, scar_min, vTemp, 1, vTemp, 1);

            // Scale anisotropic conductivity values
            for (int i = 0; i < nVarDiffCmpts; ++i)
            {
                Vmath::Vmul(nq, vTemp, 1,
                                m_vardiff[varCoeffEnum[i]], 1,
                                m_vardiff[varCoeffEnum[i]], 1);
            }
        }

        // Write out conductivity values
        for (int j = 0, k = 0; j < m_spacedim; ++j)
        {
            // Loop through rows of D
            for (int i = 0; i < j + 1; ++i)
            {
                // Transform variable coefficient and write out to file.
                m_fields[0]->FwdTrans_IterPerExp(m_vardiff[varCoeffEnum[k]],
                                                 m_fields[0]->UpdateCoeffs());
                std::stringstream filename;
                filename << "Conductivity_" << varCoeffString[k] << ".fld";
                WriteFld(filename.str());

                ++k;
            }
        }

        // Search through the loaded filters and pass the cell model to any
        // CheckpointCellModel filters loaded.
        int k = 0;
        const LibUtilities::FilterMap& f = m_session->GetFilters();
        LibUtilities::FilterMap::const_iterator x;
        for (x = f.begin(); x != f.end(); ++x, ++k)
        {
            if (x->first == "CheckpointCellModel")
            {
                boost::shared_ptr<FilterCheckpointCellModel> c
                    = boost::dynamic_pointer_cast<FilterCheckpointCellModel>(
                                                                m_filters[k]);
                c->SetCellModel(m_cell);
            }
        }

        // Load stimuli
        m_stimulus = Stimulus::LoadStimuli(m_session, m_fields[0]);

        if (!m_explicitDiffusion)
        {
            m_ode.DefineImplicitSolve (&Monodomain::DoImplicitSolve, this);
        }
        m_ode.DefineOdeRhs(&Monodomain::DoOdeRhs, this);
    }

    /**
     *
     */
    Monodomain::~Monodomain()
    {

    }

    /**
     * @param   inarray         Input array.
     * @param   outarray        Output array.
     * @param   time            Current simulation time.
     * @param   lambda          Timestep.
     */
    void Monodomain::DoImplicitSolve(
            const Array<OneD, const Array<OneD, NekDouble> >&inarray,
                  Array<OneD, Array<OneD, NekDouble> >&outarray,
            const NekDouble time,
            const NekDouble lambda)
    {
        int nvariables  = inarray.num_elements();
        int nq          = m_fields[0]->GetNpoints();
        StdRegions::ConstFactorMap factors;
        // lambda = \Delta t
        factors[StdRegions::eFactorLambda] = 1.0/lambda*m_chi*m_capMembrane;

        // We solve ( \nabla^2 - HHlambda ) Y[i] = rhs [i]
        // inarray = input: \hat{rhs} -> output: \hat{Y}
        // outarray = output: nabla^2 \hat{Y}
        // where \hat = modal coeffs
        for (int i = 0; i < nvariables; ++i)
        {
            // Multiply 1.0/timestep
            Vmath::Smul(nq, -factors[StdRegions::eFactorLambda], inarray[i], 1,
                                            m_fields[i]->UpdatePhys(), 1);

            // Solve a system of equations with Helmholtz solver and transform
            // back into physical space.
            m_fields[i]->HelmSolve(m_fields[i]->GetPhys(),
                                   m_fields[i]->UpdateCoeffs(), NullFlagList,
                                   factors, m_vardiff);

            m_fields[i]->BwdTrans( m_fields[i]->GetCoeffs(),
                                   m_fields[i]->UpdatePhys());
            m_fields[i]->SetPhysState(true);

            // Copy the solution vector (required as m_fields must be set).
            outarray[i] = m_fields[i]->GetPhys();
        }
    }

    /**
     *
     */
    void Monodomain::DoOdeRhs(
            const Array<OneD, const  Array<OneD, NekDouble> >&inarray,
                  Array<OneD,        Array<OneD, NekDouble> >&outarray,
            const NekDouble time)
    {
        // Compute I_ion
        m_cell->TimeIntegrate(inarray, outarray, time);

        // Compute I_stim
        for (unsigned int i = 0; i < m_stimulus.size(); ++i)
        {
            m_stimulus[i]->Update(outarray, time);
        }
    }

    /**
     *
     */
    void Monodomain::v_SetInitialConditions(NekDouble initialtime,
                        bool dumpInitialConditions)
    {
        EquationSystem::v_SetInitialConditions(initialtime,
                                               dumpInitialConditions);
        m_cell->Initialise();
    }

    /**
     *
     */
    void Monodomain::v_GenerateSummary(SummaryList& s)
    {
        UnsteadySystem::v_GenerateSummary(s);
        if (m_session->DefinesFunction("d00") &&
            m_session->GetFunctionType("d00", "intensity")
                    == LibUtilities::eFunctionTypeExpression)
        {
            AddSummaryItem(s, "Diffusivity-x",
                m_session->GetFunction("d00", "intensity")->GetExpression());
        }
        if (m_session->DefinesFunction("d11") &&
            m_session->GetFunctionType("d11", "intensity")
                    == LibUtilities::eFunctionTypeExpression)
        {
            AddSummaryItem(s, "Diffusivity-y",
                m_session->GetFunction("d11", "intensity")->GetExpression());
        }
        if (m_session->DefinesFunction("d22") &&
            m_session->GetFunctionType("d22", "intensity")
                    == LibUtilities::eFunctionTypeExpression)
        {
            AddSummaryItem(s, "Diffusivity-z",
                m_session->GetFunction("d22", "intensity")->GetExpression());
        }
        m_cell->GenerateSummary(s);
    }
}
<commit_msg>Fix to easily prescribe a uniform conductivity.<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// File Monodomain.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// 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.
//
// Description: Monodomain cardiac electrophysiology homogenised model.
//
///////////////////////////////////////////////////////////////////////////////

#include <iostream>

#include <CardiacEPSolver/EquationSystems/Monodomain.h>
#include <CardiacEPSolver/Filters/FilterCheckpointCellModel.h>

namespace Nektar
{
    /**
     * @class Monodomain
     *
     * Base model of cardiac electrophysiology of the form
     * \f{align*}{
     *     \frac{\partial u}{\partial t} = \nabla^2 u + J_{ion},
     * \f}
     * where the reaction term, \f$J_{ion}\f$ is defined by a specific cell
     * model.
     *
     * This implementation, at present, treats the reaction terms explicitly
     * and the diffusive element implicitly.
     */

    /**
     * Registers the class with the Factory.
     */
    string Monodomain::className
            = GetEquationSystemFactory().RegisterCreatorFunction(
                "Monodomain",
                Monodomain::create,
                "Monodomain model of cardiac electrophysiology.");

    /**
     *
     */
    Monodomain::Monodomain(
            const LibUtilities::SessionReaderSharedPtr& pSession)
        : UnsteadySystem(pSession)
    {
    }

    /**
     *
     */
    void Monodomain::v_InitObject()
    {
        UnsteadySystem::v_InitObject();

        m_session->LoadParameter("Chi",        m_chi);
        m_session->LoadParameter("Cm",         m_capMembrane);

        std::string vCellModel;
        m_session->LoadSolverInfo("CELLMODEL", vCellModel, "");

        ASSERTL0(vCellModel != "", "Cell Model not specified.");

        m_cell = GetCellModelFactory().CreateInstance(
                                        vCellModel, m_session, m_fields[0]);

        m_intVariables.push_back(0);

        // Load variable coefficients
        StdRegions::VarCoeffType varCoeffEnum[6] = {
                StdRegions::eVarCoeffD00,
                StdRegions::eVarCoeffD01,
                StdRegions::eVarCoeffD11,
                StdRegions::eVarCoeffD02,
                StdRegions::eVarCoeffD12,
                StdRegions::eVarCoeffD22
        };
        std::string varCoeffString[6] = {"xx","xy","yy","xz","yz","zz"};
        std::string aniso_var[3] = {"fx", "fy", "fz"};

        const int nq            = m_fields[0]->GetNpoints();
        const int nVarDiffCmpts = m_spacedim * (m_spacedim + 1) / 2;

        // Allocate storage for variable coeffs and initialize to 1.
        for (int i = 0, k = 0; i < m_spacedim; ++i)
        {
            for (int j = 0; j < i+1; ++j)
            {
                if (i == j)
                {
                    m_vardiff[varCoeffEnum[k]] = Array<OneD, NekDouble>(nq, 1.0);
                }
                else
                {
                    m_vardiff[varCoeffEnum[k]] = Array<OneD, NekDouble>(nq, 0.0);
                }
                ++k;
            }
        }

        // Apply fibre map f \in [0,1], scale to conductivity range
        // [o_min,o_max], specified by the session parameters o_min and o_max
        if (m_session->DefinesFunction("AnisotropicConductivity"))
        {
            if (m_session->DefinesCmdLineArgument("verbose"))
            {
                cout << "Loading Anisotropic Fibre map." << endl;
            }

            NekDouble   o_min        = m_session->GetParameter("o_min");
            NekDouble   o_max        = m_session->GetParameter("o_max");
            int         k            = 0;

            Array<OneD, NekDouble> vTemp_i;
            Array<OneD, NekDouble> vTemp_j;

            /*
             * Diffusivity matrix D is upper triangular and defined as
             *    d_00   d_01  d_02
             *           d_11  d_12
             *                 d_22
             *
             * Given a principle fibre direction _f_ the diffusivity is given
             * by
             *    d_ij = { D_2 + (D_1 - D_2) f_i f_j   if i==j
             *           {       (D_1 - D_2) f_i f_j   if i!=j
             *
             * The vector _f_ is given in terms of the variables fx,fy,fz in the
             * function AnisotropicConductivity. The values of D_1 and D_2 are
             * the parameters o_max and o_min, respectively.
             */

            // Loop through columns of D
            for (int j = 0; j < m_spacedim; ++j)
            {
                ASSERTL0(m_session->DefinesFunction("AnisotropicConductivity",
                                                    aniso_var[j]),
                         "Function 'AnisotropicConductivity' not correctly "
                         "defined.");
                EvaluateFunction(aniso_var[j], vTemp_j,
                                 "AnisotropicConductivity");

                // Loop through rows of D
                for (int i = 0; i < j + 1; ++i)
                {
                    ASSERTL0(m_session->DefinesFunction(
                                        "AnisotropicConductivity",aniso_var[i]),
                             "Function 'AnisotropicConductivity' not correctly "
                             "defined.");
                    EvaluateFunction(aniso_var[i], vTemp_i,
                                     "AnisotropicConductivity");

                    Vmath::Vmul(nq, vTemp_i, 1, vTemp_j, 1,
                                    m_vardiff[varCoeffEnum[k]], 1);

                    Vmath::Smul(nq, o_max-o_min,
                                    m_vardiff[varCoeffEnum[k]], 1,
                                    m_vardiff[varCoeffEnum[k]], 1);

                    if (i == j)
                    {
                        Vmath::Sadd(nq, o_min,
                                        m_vardiff[varCoeffEnum[k]], 1,
                                        m_vardiff[varCoeffEnum[k]], 1);
                    }

                    ++k;
                }
            }
        }

        // Scale by scar map (range 0->1) derived from intensity map
        // (range d_min -> d_max)
        if (m_session->DefinesFunction("IsotropicConductivity"))
        {
            if (m_session->DefinesCmdLineArgument("verbose"))
            {
                cout << "Loading Isotropic Conductivity map." << endl;
            }

            const std::string varName  = "intensity";
            Array<OneD, NekDouble> vTemp;
            EvaluateFunction(varName, vTemp, "IsotropicConductivity");

            // If the d_min and d_max parameters are defined, then we need to
            // rescale the isotropic conductivity to convert from the source
            // domain (e.g. late-gad intensity) to conductivity
            if (m_session->DefinesParameter("d_min")) {
                const NekDouble   f_min    = m_session->GetParameter("d_min");
                const NekDouble   f_max    = m_session->GetParameter("d_max");
                const NekDouble   scar_min = 0.0;
                const NekDouble   scar_max = 1.0;

                // Threshold based on d_min, d_max
                for (int j = 0; j < nq; ++j)
                {
                    vTemp[j] = (vTemp[j] < f_min ? f_min : vTemp[j]);
                    vTemp[j] = (vTemp[j] > f_max ? f_max : vTemp[j]);
                }

                // Rescale to s \in [0,1] (0 maps to d_max, 1 maps to d_min)
                Vmath::Sadd(nq, -f_min, vTemp, 1, vTemp, 1);
                Vmath::Smul(nq, -1.0/(f_max-f_min), vTemp, 1, vTemp, 1);
                Vmath::Sadd(nq, 1.0, vTemp, 1, vTemp, 1);
                Vmath::Smul(nq, scar_max - scar_min, vTemp, 1, vTemp, 1);
                Vmath::Sadd(nq, scar_min, vTemp, 1, vTemp, 1);
            }

            // Scale anisotropic conductivity values
            for (int i = 0; i < nVarDiffCmpts; ++i)
            {
                Vmath::Vmul(nq, vTemp, 1,
                                m_vardiff[varCoeffEnum[i]], 1,
                                m_vardiff[varCoeffEnum[i]], 1);
            }
        }

        // Write out conductivity values
        for (int j = 0, k = 0; j < m_spacedim; ++j)
        {
            // Loop through rows of D
            for (int i = 0; i < j + 1; ++i)
            {
                // Transform variable coefficient and write out to file.
                m_fields[0]->FwdTrans_IterPerExp(m_vardiff[varCoeffEnum[k]],
                                                 m_fields[0]->UpdateCoeffs());
                std::stringstream filename;
                filename << "Conductivity_" << varCoeffString[k] << ".fld";
                WriteFld(filename.str());

                ++k;
            }
        }

        // Search through the loaded filters and pass the cell model to any
        // CheckpointCellModel filters loaded.
        int k = 0;
        const LibUtilities::FilterMap& f = m_session->GetFilters();
        LibUtilities::FilterMap::const_iterator x;
        for (x = f.begin(); x != f.end(); ++x, ++k)
        {
            if (x->first == "CheckpointCellModel")
            {
                boost::shared_ptr<FilterCheckpointCellModel> c
                    = boost::dynamic_pointer_cast<FilterCheckpointCellModel>(
                                                                m_filters[k]);
                c->SetCellModel(m_cell);
            }
        }

        // Load stimuli
        m_stimulus = Stimulus::LoadStimuli(m_session, m_fields[0]);

        if (!m_explicitDiffusion)
        {
            m_ode.DefineImplicitSolve (&Monodomain::DoImplicitSolve, this);
        }
        m_ode.DefineOdeRhs(&Monodomain::DoOdeRhs, this);
    }

    /**
     *
     */
    Monodomain::~Monodomain()
    {

    }

    /**
     * @param   inarray         Input array.
     * @param   outarray        Output array.
     * @param   time            Current simulation time.
     * @param   lambda          Timestep.
     */
    void Monodomain::DoImplicitSolve(
            const Array<OneD, const Array<OneD, NekDouble> >&inarray,
                  Array<OneD, Array<OneD, NekDouble> >&outarray,
            const NekDouble time,
            const NekDouble lambda)
    {
        int nvariables  = inarray.num_elements();
        int nq          = m_fields[0]->GetNpoints();
        StdRegions::ConstFactorMap factors;
        // lambda = \Delta t
        factors[StdRegions::eFactorLambda] = 1.0/lambda*m_chi*m_capMembrane;

        // We solve ( \nabla^2 - HHlambda ) Y[i] = rhs [i]
        // inarray = input: \hat{rhs} -> output: \hat{Y}
        // outarray = output: nabla^2 \hat{Y}
        // where \hat = modal coeffs
        for (int i = 0; i < nvariables; ++i)
        {
            // Multiply 1.0/timestep
            Vmath::Smul(nq, -factors[StdRegions::eFactorLambda], inarray[i], 1,
                                            m_fields[i]->UpdatePhys(), 1);

            // Solve a system of equations with Helmholtz solver and transform
            // back into physical space.
            m_fields[i]->HelmSolve(m_fields[i]->GetPhys(),
                                   m_fields[i]->UpdateCoeffs(), NullFlagList,
                                   factors, m_vardiff);

            m_fields[i]->BwdTrans( m_fields[i]->GetCoeffs(),
                                   m_fields[i]->UpdatePhys());
            m_fields[i]->SetPhysState(true);

            // Copy the solution vector (required as m_fields must be set).
            outarray[i] = m_fields[i]->GetPhys();
        }
    }

    /**
     *
     */
    void Monodomain::DoOdeRhs(
            const Array<OneD, const  Array<OneD, NekDouble> >&inarray,
                  Array<OneD,        Array<OneD, NekDouble> >&outarray,
            const NekDouble time)
    {
        // Compute I_ion
        m_cell->TimeIntegrate(inarray, outarray, time);

        // Compute I_stim
        for (unsigned int i = 0; i < m_stimulus.size(); ++i)
        {
            m_stimulus[i]->Update(outarray, time);
        }
    }

    /**
     *
     */
    void Monodomain::v_SetInitialConditions(NekDouble initialtime,
                        bool dumpInitialConditions)
    {
        EquationSystem::v_SetInitialConditions(initialtime,
                                               dumpInitialConditions);
        m_cell->Initialise();
    }

    /**
     *
     */
    void Monodomain::v_GenerateSummary(SummaryList& s)
    {
        UnsteadySystem::v_GenerateSummary(s);
        if (m_session->DefinesFunction("d00") &&
            m_session->GetFunctionType("d00", "intensity")
                    == LibUtilities::eFunctionTypeExpression)
        {
            AddSummaryItem(s, "Diffusivity-x",
                m_session->GetFunction("d00", "intensity")->GetExpression());
        }
        if (m_session->DefinesFunction("d11") &&
            m_session->GetFunctionType("d11", "intensity")
                    == LibUtilities::eFunctionTypeExpression)
        {
            AddSummaryItem(s, "Diffusivity-y",
                m_session->GetFunction("d11", "intensity")->GetExpression());
        }
        if (m_session->DefinesFunction("d22") &&
            m_session->GetFunctionType("d22", "intensity")
                    == LibUtilities::eFunctionTypeExpression)
        {
            AddSummaryItem(s, "Diffusivity-z",
                m_session->GetFunction("d22", "intensity")->GetExpression());
        }
        m_cell->GenerateSummary(s);
    }
}
<|endoftext|>


<commit_before>/*
 *  nextpnr -- Next Generation Place and Route
 *
 *  Copyright (C) 2018  David Shah <david@symbioticeda.com>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include <algorithm>
#include <iomanip>
#include <queue>
#include "nextpnr.h"
#include "cells.h"
#include "globals.h"
#include "log.h"

#define fmt_str(x) (static_cast<const std::ostringstream &>(std::ostringstream() << x).str())

NEXTPNR_NAMESPACE_BEGIN

static std::string get_quad_name(GlobalQuadrant quad)
{
    switch (quad) {
    case QUAD_UL:
        return "UL";
    case QUAD_UR:
        return "UR";
    case QUAD_LL:
        return "LL";
    case QUAD_LR:
        return "LR";
    }
    return "";
}

class Ecp5GlobalRouter
{
  public:
    Ecp5GlobalRouter(Context *ctx) : ctx(ctx){};

  private:
    bool is_clock_port(const PortRef &user)
    {
        if (user.cell->type == id_TRELLIS_SLICE && user.port == id_CLK)
            return true;
        return false;
    }

    std::vector<NetInfo *> get_clocks()
    {
        std::unordered_map<IdString, int> clockCount;
        for (auto &net : ctx->nets) {
            NetInfo *ni = net.second.get();
            clockCount[ni->name] = 0;
            for (const auto &user : ni->users) {
                if (is_clock_port(user))
                    clockCount[ni->name]++;
            }
            //log_info("clkcount %s: %d\n", ni->name.c_str(ctx),clockCount[ni->name]);
        }
        std::vector<NetInfo *> clocks;
        while (clocks.size() < 16) {
            auto max = std::max_element(clockCount.begin(), clockCount.end(),
                                        [](const decltype(clockCount)::value_type &a,
                                           const decltype(clockCount)::value_type &b) { return a.second < b.second; });
            if (max == clockCount.end() || max->second < 5)
                break;
            clocks.push_back(ctx->nets.at(max->first).get());
            clockCount.erase(max->first);
        }
        return clocks;
    }

    PipId find_tap_pip(WireId tile_glb)
    {
        std::string wireName = ctx->getWireBasename(tile_glb).str(ctx);
        std::string glbName = wireName.substr(2);
        TapDirection td = ctx->globalInfoAtLoc(tile_glb.location).tap_dir;
        WireId tap_wire;
        Location tap_loc;
        tap_loc.x = ctx->globalInfoAtLoc(tile_glb.location).tap_col;
        tap_loc.y = tile_glb.location.y;
        if (td == TAP_DIR_LEFT) {
            tap_wire = ctx->getWireByLocAndBasename(tap_loc, "L_" + glbName);
        } else {
            tap_wire = ctx->getWireByLocAndBasename(tap_loc, "R_" + glbName);
        }
        NPNR_ASSERT(tap_wire != WireId());
        return *(ctx->getPipsUphill(tap_wire).begin());
    }

    PipId find_spine_pip(WireId tap_wire)
    {
        std::string wireName = ctx->getWireBasename(tap_wire).str(ctx);
        Location spine_loc;
        spine_loc.x = ctx->globalInfoAtLoc(tap_wire.location).spine_col;
        spine_loc.y = ctx->globalInfoAtLoc(tap_wire.location).spine_row;
        WireId spine_wire = ctx->getWireByLocAndBasename(spine_loc, wireName);
        return *(ctx->getPipsUphill(spine_wire).begin());
    }

    void route_logic_tile_global(NetInfo *net, int global_index, PortRef user)
    {
        WireId userWire = ctx->getBelPinWire(user.cell->bel, user.port);
        WireId globalWire;
        IdString global_name = ctx->id(fmt_str("G_HPBX" << std::setw(2) << std::setfill('0') << global_index << "00"));
        std::queue<WireId> upstream;
        std::unordered_map<WireId, PipId> backtrace;
        upstream.push(userWire);
        bool already_routed = false;
        WireId next;
        // Search back from the pin until we reach the global network
        while (true) {
            next = upstream.front();
            upstream.pop();

            if (ctx->getBoundWireNet(next) == net) {
                already_routed = true;
                globalWire = next;
                break;
            }

            if (ctx->getWireBasename(next) == global_name) {
                globalWire = next;
                break;
            }
            if (ctx->checkWireAvail(next)) {
                for (auto pip : ctx->getPipsUphill(next)) {
                    WireId src = ctx->getPipSrcWire(pip);
                    backtrace[src] = pip;
                    upstream.push(src);
                }
            }
            if (upstream.size() > 3000) {
                log_error("failed to route HPBX%02d00 to %s.%s\n", global_index,
                          ctx->getBelName(user.cell->bel).c_str(ctx), user.port.c_str(ctx));
            }
        }
        // Set all the pips we found along the way
        WireId cursor = next;
        while (true) {
            auto fnd = backtrace.find(cursor);
            if (fnd == backtrace.end())
                break;
            ctx->bindPip(fnd->second, net, STRENGTH_LOCKED);
            cursor = ctx->getPipDstWire(fnd->second);

        }
        // If the global network inside the tile isn't already set up,
        // we also need to bind the buffers along the way
        if (!already_routed) {
            ctx->bindWire(next, net, STRENGTH_LOCKED);
            PipId tap_pip = find_tap_pip(next);
            NetInfo *tap_net = ctx->getBoundPipNet(tap_pip);
            if (tap_net == nullptr) {
                ctx->bindPip(tap_pip, net, STRENGTH_LOCKED);
                PipId spine_pip = find_spine_pip(ctx->getPipSrcWire(tap_pip));
                NetInfo *spine_net = ctx->getBoundPipNet(spine_pip);
                if (spine_net == nullptr) {
                    ctx->bindPip(spine_pip, net, STRENGTH_LOCKED);
                } else {
                    NPNR_ASSERT(spine_net == net);
                }
            } else {
                NPNR_ASSERT(tap_net == net);
            }
        }
    }

    bool is_global_io(CellInfo *io, std::string &glb_name)
    {
        std::string func_name = ctx->getPioFunctionName(io->bel);
        if (func_name.substr(0, 5) == "PCLKT") {
            func_name.erase(func_name.find('_'), 1);
            glb_name = "G_" + func_name;
            return true;
        }
        return false;
    }

    WireId get_global_wire(GlobalQuadrant quad, int network)
    {
        return ctx->getWireByLocAndBasename(Location(0, 0), "G_" + get_quad_name(quad) + "PCLK" + std::to_string(network));
    }

    bool simple_router(NetInfo *net, WireId src, WireId dst, bool allow_fail = false)
    {
        std::queue<WireId> visit;
        std::unordered_map<WireId, PipId> backtrace;
        visit.push(src);
        WireId cursor;
        while (true) {

            if (visit.empty() || visit.size() > 50000) {
                if (allow_fail)
                    return false;
                log_error("cannot route global from %s to %s.\n", ctx->getWireName(src).c_str(ctx),
                          ctx->getWireName(dst).c_str(ctx));
            }
            cursor = visit.front();
            visit.pop();
            NetInfo *bound = ctx->getBoundWireNet(cursor);
            if (bound == net) {
            } else if (bound != nullptr) {
                continue;
            }
            if (cursor == dst)
                break;
            for (auto dh : ctx->getPipsDownhill(cursor)) {
                WireId pipDst = ctx->getPipDstWire(dh);
                if (backtrace.count(pipDst))
                    continue;
                backtrace[pipDst] = dh;
                visit.push(pipDst);
            }
        }
        while (true) {
            auto fnd = backtrace.find(cursor);
            if (fnd == backtrace.end())
                break;
            NetInfo * bound = ctx->getBoundWireNet(cursor);
            if (bound != nullptr) {
                NPNR_ASSERT(bound == net);
                break;
            }
            ctx->bindPip(fnd->second, net, STRENGTH_LOCKED);
            cursor = ctx->getPipSrcWire(fnd->second);
        }\
        if (ctx->getBoundWireNet(src) == nullptr)
            ctx->bindWire(src, net, STRENGTH_LOCKED);
        return true;
    }

    bool route_onto_global(NetInfo *net, int network)
    {
        WireId glb_src;
        NPNR_ASSERT(net->driver.cell->type == id_DCCA);
        glb_src = ctx->getNetinfoSourceWire(net);
        for (int quad = QUAD_UL; quad < QUAD_LR + 1; quad++) {
            WireId glb_dst = get_global_wire(GlobalQuadrant(quad), network);
            NPNR_ASSERT(glb_dst != WireId());
            bool routed = simple_router(net, glb_src, glb_dst);
            if (!routed)
                return false;
        }
        return true;
    }

    // Attempt to place a DCC
    void place_dcc(CellInfo *dcc) {
        for (auto bel : ctx->getBels()) {
            if (ctx->getBelType(bel) == id_DCCA && ctx->checkBelAvail(bel)) {
                if (ctx->isValidBelForCell(dcc, bel)) {
                    ctx->bindBel(bel, dcc, STRENGTH_LOCKED);
                    return;
                }
            }
        }
        NPNR_ASSERT_FALSE("failed to place dcca");
    }

    // Insert a DCC into a net to promote it to a global
    NetInfo *insert_dcc(NetInfo *net)
    {
        auto dcc = create_ecp5_cell(ctx, id_DCCA, "$gbuf$" + net->name.str(ctx));

        std::unique_ptr<NetInfo> glbnet = std::unique_ptr<NetInfo>(new NetInfo);
        glbnet->name = ctx->id("$glbnet$" + net->name.str(ctx));
        glbnet->driver.cell = dcc.get();
        glbnet->driver.port = id_CLKO;
        glbnet->users = net->users;
        for (auto user : net->users) {
            user.cell->ports.at(user.port).net = glbnet.get();
        }
        net->users.clear();

        dcc->ports[id_CLKI].net = net;
        PortRef clki_pr;
        clki_pr.port = id_CLKI;
        clki_pr.cell = dcc.get();
        net->users.push_back(clki_pr);

        place_dcc(dcc.get());

        ctx->cells[dcc->name] = std::move(dcc);
        NetInfo *glbptr = glbnet.get();
        ctx->nets[glbnet->name] = std::move(glbnet);
        return glbptr;
    }
    Context *ctx;

public:
    void promote_and_route_globals() {
        log_info("Promoting and routing globals...\n");
        auto clocks = get_clocks();
        int glbid = 0;
        for (auto clock : clocks) {
            log_info("    promoting clock net %s to global %d\n", clock->name.c_str(ctx), glbid);
            auto old_users = clock->users;
            NetInfo *global = insert_dcc(clock);
            bool routed = route_onto_global(global, glbid);
            NPNR_ASSERT(routed);
            for (const auto &user : global->users) {
                route_logic_tile_global(global, glbid, user);
            }
            glbid++;
        }
    }

};

void route_ecp5_globals(Context *ctx) {
    Ecp5GlobalRouter(ctx).promote_and_route_globals();
}

NEXTPNR_NAMESPACE_END
<commit_msg>ecp5: Fix handling of global to fabric connections<commit_after>/*
 *  nextpnr -- Next Generation Place and Route
 *
 *  Copyright (C) 2018  David Shah <david@symbioticeda.com>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include <algorithm>
#include <iomanip>
#include <queue>
#include "nextpnr.h"
#include "cells.h"
#include "globals.h"
#include "log.h"

#define fmt_str(x) (static_cast<const std::ostringstream &>(std::ostringstream() << x).str())

NEXTPNR_NAMESPACE_BEGIN

static std::string get_quad_name(GlobalQuadrant quad)
{
    switch (quad) {
    case QUAD_UL:
        return "UL";
    case QUAD_UR:
        return "UR";
    case QUAD_LL:
        return "LL";
    case QUAD_LR:
        return "LR";
    }
    return "";
}

class Ecp5GlobalRouter
{
  public:
    Ecp5GlobalRouter(Context *ctx) : ctx(ctx){};

  private:
    bool is_clock_port(const PortRef &user)
    {
        if (user.cell->type == id_TRELLIS_SLICE && user.port == id_CLK)
            return true;
        return false;
    }

    std::vector<NetInfo *> get_clocks()
    {
        std::unordered_map<IdString, int> clockCount;
        for (auto &net : ctx->nets) {
            NetInfo *ni = net.second.get();
            clockCount[ni->name] = 0;
            for (const auto &user : ni->users) {
                if (is_clock_port(user))
                    clockCount[ni->name]++;
            }
            //log_info("clkcount %s: %d\n", ni->name.c_str(ctx),clockCount[ni->name]);
        }
        std::vector<NetInfo *> clocks;
        while (clocks.size() < 16) {
            auto max = std::max_element(clockCount.begin(), clockCount.end(),
                                        [](const decltype(clockCount)::value_type &a,
                                           const decltype(clockCount)::value_type &b) { return a.second < b.second; });
            if (max == clockCount.end() || max->second < 5)
                break;
            clocks.push_back(ctx->nets.at(max->first).get());
            clockCount.erase(max->first);
        }
        return clocks;
    }

    PipId find_tap_pip(WireId tile_glb)
    {
        std::string wireName = ctx->getWireBasename(tile_glb).str(ctx);
        std::string glbName = wireName.substr(2);
        TapDirection td = ctx->globalInfoAtLoc(tile_glb.location).tap_dir;
        WireId tap_wire;
        Location tap_loc;
        tap_loc.x = ctx->globalInfoAtLoc(tile_glb.location).tap_col;
        tap_loc.y = tile_glb.location.y;
        if (td == TAP_DIR_LEFT) {
            tap_wire = ctx->getWireByLocAndBasename(tap_loc, "L_" + glbName);
        } else {
            tap_wire = ctx->getWireByLocAndBasename(tap_loc, "R_" + glbName);
        }
        NPNR_ASSERT(tap_wire != WireId());
        return *(ctx->getPipsUphill(tap_wire).begin());
    }

    PipId find_spine_pip(WireId tap_wire)
    {
        std::string wireName = ctx->getWireBasename(tap_wire).str(ctx);
        Location spine_loc;
        spine_loc.x = ctx->globalInfoAtLoc(tap_wire.location).spine_col;
        spine_loc.y = ctx->globalInfoAtLoc(tap_wire.location).spine_row;
        WireId spine_wire = ctx->getWireByLocAndBasename(spine_loc, wireName);
        return *(ctx->getPipsUphill(spine_wire).begin());
    }

    void route_logic_tile_global(NetInfo *net, int global_index, PortRef user)
    {
        WireId userWire = ctx->getBelPinWire(user.cell->bel, user.port);
        WireId globalWire;
        IdString global_name = ctx->id(fmt_str("G_HPBX" << std::setw(2) << std::setfill('0') << global_index << "00"));
        std::queue<WireId> upstream;
        std::unordered_map<WireId, PipId> backtrace;
        upstream.push(userWire);
        bool already_routed = false;
        WireId next;
        // Search back from the pin until we reach the global network
        while (true) {
            next = upstream.front();
            upstream.pop();

            if (ctx->getBoundWireNet(next) == net) {
                already_routed = true;
                globalWire = next;
                break;
            }

            if (ctx->getWireBasename(next) == global_name) {
                globalWire = next;
                break;
            }
            if (ctx->checkWireAvail(next)) {
                for (auto pip : ctx->getPipsUphill(next)) {
                    WireId src = ctx->getPipSrcWire(pip);
                    backtrace[src] = pip;
                    upstream.push(src);
                }
            }
            if (upstream.size() > 30000) {
                log_error("failed to route HPBX%02d00 to %s.%s\n", global_index,
                          ctx->getBelName(user.cell->bel).c_str(ctx), user.port.c_str(ctx));
            }
        }
        // Set all the pips we found along the way
        WireId cursor = next;
        while (true) {
            auto fnd = backtrace.find(cursor);
            if (fnd == backtrace.end())
                break;
            ctx->bindPip(fnd->second, net, STRENGTH_LOCKED);
            cursor = ctx->getPipDstWire(fnd->second);

        }
        // If the global network inside the tile isn't already set up,
        // we also need to bind the buffers along the way
        if (!already_routed) {
            ctx->bindWire(next, net, STRENGTH_LOCKED);
            PipId tap_pip = find_tap_pip(next);
            NetInfo *tap_net = ctx->getBoundPipNet(tap_pip);
            if (tap_net == nullptr) {
                ctx->bindPip(tap_pip, net, STRENGTH_LOCKED);
                PipId spine_pip = find_spine_pip(ctx->getPipSrcWire(tap_pip));
                NetInfo *spine_net = ctx->getBoundPipNet(spine_pip);
                if (spine_net == nullptr) {
                    ctx->bindPip(spine_pip, net, STRENGTH_LOCKED);
                } else {
                    NPNR_ASSERT(spine_net == net);
                }
            } else {
                NPNR_ASSERT(tap_net == net);
            }
        }
    }

    bool is_global_io(CellInfo *io, std::string &glb_name)
    {
        std::string func_name = ctx->getPioFunctionName(io->bel);
        if (func_name.substr(0, 5) == "PCLKT") {
            func_name.erase(func_name.find('_'), 1);
            glb_name = "G_" + func_name;
            return true;
        }
        return false;
    }

    WireId get_global_wire(GlobalQuadrant quad, int network)
    {
        return ctx->getWireByLocAndBasename(Location(0, 0), "G_" + get_quad_name(quad) + "PCLK" + std::to_string(network));
    }

    bool simple_router(NetInfo *net, WireId src, WireId dst, bool allow_fail = false)
    {
        std::queue<WireId> visit;
        std::unordered_map<WireId, PipId> backtrace;
        visit.push(src);
        WireId cursor;
        while (true) {

            if (visit.empty() || visit.size() > 50000) {
                if (allow_fail)
                    return false;
                log_error("cannot route global from %s to %s.\n", ctx->getWireName(src).c_str(ctx),
                          ctx->getWireName(dst).c_str(ctx));
            }
            cursor = visit.front();
            visit.pop();
            NetInfo *bound = ctx->getBoundWireNet(cursor);
            if (bound == net) {
            } else if (bound != nullptr) {
                continue;
            }
            if (cursor == dst)
                break;
            for (auto dh : ctx->getPipsDownhill(cursor)) {
                WireId pipDst = ctx->getPipDstWire(dh);
                if (backtrace.count(pipDst))
                    continue;
                backtrace[pipDst] = dh;
                visit.push(pipDst);
            }
        }
        while (true) {
            auto fnd = backtrace.find(cursor);
            if (fnd == backtrace.end())
                break;
            NetInfo * bound = ctx->getBoundWireNet(cursor);
            if (bound != nullptr) {
                NPNR_ASSERT(bound == net);
                break;
            }
            ctx->bindPip(fnd->second, net, STRENGTH_LOCKED);
            cursor = ctx->getPipSrcWire(fnd->second);
        }\
        if (ctx->getBoundWireNet(src) == nullptr)
            ctx->bindWire(src, net, STRENGTH_LOCKED);
        return true;
    }

    bool route_onto_global(NetInfo *net, int network)
    {
        WireId glb_src;
        NPNR_ASSERT(net->driver.cell->type == id_DCCA);
        glb_src = ctx->getNetinfoSourceWire(net);
        for (int quad = QUAD_UL; quad < QUAD_LR + 1; quad++) {
            WireId glb_dst = get_global_wire(GlobalQuadrant(quad), network);
            NPNR_ASSERT(glb_dst != WireId());
            bool routed = simple_router(net, glb_src, glb_dst);
            if (!routed)
                return false;
        }
        return true;
    }

    // Attempt to place a DCC
    void place_dcc(CellInfo *dcc) {
        for (auto bel : ctx->getBels()) {
            if (ctx->getBelType(bel) == id_DCCA && ctx->checkBelAvail(bel)) {
                if (ctx->isValidBelForCell(dcc, bel)) {
                    ctx->bindBel(bel, dcc, STRENGTH_LOCKED);
                    return;
                }
            }
        }
        NPNR_ASSERT_FALSE("failed to place dcca");
    }

    // Insert a DCC into a net to promote it to a global
    NetInfo *insert_dcc(NetInfo *net)
    {
        auto dcc = create_ecp5_cell(ctx, id_DCCA, "$gbuf$" + net->name.str(ctx));

        std::unique_ptr<NetInfo> glbnet = std::unique_ptr<NetInfo>(new NetInfo);
        glbnet->name = ctx->id("$glbnet$" + net->name.str(ctx));
        glbnet->driver.cell = dcc.get();
        glbnet->driver.port = id_CLKO;
        glbnet->users = net->users;
        for (auto user : net->users) {
            user.cell->ports.at(user.port).net = glbnet.get();
        }
        net->users.clear();

        dcc->ports[id_CLKI].net = net;
        PortRef clki_pr;
        clki_pr.port = id_CLKI;
        clki_pr.cell = dcc.get();
        net->users.push_back(clki_pr);

        place_dcc(dcc.get());

        ctx->cells[dcc->name] = std::move(dcc);
        NetInfo *glbptr = glbnet.get();
        ctx->nets[glbnet->name] = std::move(glbnet);
        return glbptr;
    }
    Context *ctx;

public:
    void promote_and_route_globals() {
        log_info("Promoting and routing globals...\n");
        auto clocks = get_clocks();
        std::set<int> all_globals, fab_globals;
        for (int i = 0; i < 16; i++) {
            all_globals.insert(i);
            if (i < 8)
                fab_globals.insert(i);
        }
        for (auto clock : clocks) {
            bool drives_fabric = std::any_of(clock->users.begin(), clock->users.end(), [this](const PortRef &port) {
                return !is_clock_port(port);
            });
            int glbid;
            if (drives_fabric) {
                if (fab_globals.empty())
                    continue;
                glbid = *(fab_globals.begin());
            } else {
                glbid = *(all_globals.begin());
            }
            all_globals.erase(glbid);
            fab_globals.erase(glbid);
            log_info("    promoting clock net %s to global %d\n", clock->name.c_str(ctx), glbid);
            auto old_users = clock->users;
            NetInfo *global = insert_dcc(clock);
            bool routed = route_onto_global(global, glbid);
            NPNR_ASSERT(routed);
            for (const auto &user : global->users) {
                route_logic_tile_global(global, glbid, user);
            }
        }
    }

};

void route_ecp5_globals(Context *ctx) {
    Ecp5GlobalRouter(ctx).promote_and_route_globals();
}

NEXTPNR_NAMESPACE_END
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2018, Arm Limited and affiliates.
 * SPDX-License-Identifier: Apache-2.0
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "QUECTEL_BG96_CellularContext.h"
#include "QUECTEL_BG96_CellularStack.h"
#include "QUECTEL_BG96_ControlPlane_netif.h"
#include "CellularLog.h"

#include "Semaphore.h"

namespace mbed {

// Non-IP context supported only for context id 1
#define NIDD_PDP_CONTEXT_ID 1
// Timeout to wait for URC indicating NIDD connection opening
#define NIDD_OPEN_URC_TIMEOUT 3000

QUECTEL_BG96_CellularContext::QUECTEL_BG96_CellularContext(ATHandler &at, CellularDevice *device, const char *apn, bool cp_req, bool nonip_req) :
    AT_CellularContext(at, device, apn, cp_req, nonip_req)
{
    if (_nonip_req) {
        _at.set_urc_handler("+QIND:", mbed::Callback<void()>(this, &QUECTEL_BG96_CellularContext::urc_nidd));
    }
}

QUECTEL_BG96_CellularContext::~QUECTEL_BG96_CellularContext()
{
    if (_nonip_req) {
        _at.set_urc_handler("+QIND:", 0);
    }
}

#if !NSAPI_PPP_AVAILABLE
NetworkStack *QUECTEL_BG96_CellularContext::get_stack()
{
    if (_pdp_type == NON_IP_PDP_TYPE || (_nonip_req && _pdp_type != DEFAULT_PDP_TYPE)) {
        tr_error("Requesting stack for NON-IP context! Should request control plane netif: get_cp_netif()");
        return NULL;
    }

    if (!_stack) {
        _stack = new QUECTEL_BG96_CellularStack(_at, _cid, (nsapi_ip_stack_t)_pdp_type, *get_device());
    }

    return _stack;
}
#endif // #if !NSAPI_PPP_AVAILABLE

ControlPlane_netif *QUECTEL_BG96_CellularContext::get_cp_netif()
{
    if (!_cp_netif) {
        _cp_netif = new QUECTEL_BG96_ControlPlane_netif(_at, _cid, *get_device());
    }
    return _cp_netif;
}

nsapi_error_t QUECTEL_BG96_CellularContext::do_user_authentication()
{
    uint8_t type = 1;
    if ((uint8_t)_pdp_type > 1) {
        type = 2;
    }
    if (_pwd && _uname) {
        if (_at.at_cmd_discard("+QICSGP", "=", "%d%d%s%s%s%d", _cid, type,
                               _apn, _uname, _pwd, _authentication_type) != NSAPI_ERROR_OK) {
            return NSAPI_ERROR_AUTH_FAILURE;
        }
    } else {
        if (_at.at_cmd_discard("+QICSGP", "=", "%d%d%s", _cid, type,
                               _apn) != NSAPI_ERROR_OK) {
            return NSAPI_ERROR_AUTH_FAILURE;
        }
    }

    return NSAPI_ERROR_OK;
}

nsapi_error_t QUECTEL_BG96_CellularContext::activate_non_ip_context()
{

    // Open the NIDD connection
    nsapi_size_or_error_t ret = _at.at_cmd_discard("+QCFGEXT", "=\"nipd\",1");
    if (ret == NSAPI_ERROR_OK) {
        _at.lock();
        _at.set_at_timeout(NIDD_OPEN_URC_TIMEOUT);
        _at.resp_start("+QIND:");
        urc_nidd();
        _at.restore_at_timeout();
        _at.unlock();
        if (_cid == -1) {
            return NSAPI_ERROR_NO_CONNECTION;
        }
    }

    return (ret == NSAPI_ERROR_OK) ? NSAPI_ERROR_OK : NSAPI_ERROR_NO_CONNECTION;
}

void QUECTEL_BG96_CellularContext::activate_context()
{
    tr_info("Activate PDP context %d", _cid);

    if (_at.at_cmd_discard("+QIACT", "=", "%d", _cid) == NSAPI_ERROR_OK) {
        _is_context_activated = true;
    }
}

void QUECTEL_BG96_CellularContext::deactivate_context()
{
    _at.at_cmd_discard("+QIDEACT", "=", "%d", _cid);
}

void QUECTEL_BG96_CellularContext::deactivate_non_ip_context()
{
    // Close the NIDD connection
    _at.at_cmd_discard("+QCFGEXT", "=\"nipd\",0");
}

void QUECTEL_BG96_CellularContext::urc_nidd()
{
    char nipd_string[6];

    // skip "nipd"
    _at.skip_param();
    _at.read_string(nipd_string, sizeof(nipd_string));

    if (!strcmp(nipd_string, "recv")) {
        cp_data_received();
    } else if (!strcmp(nipd_string, "open")) {
        urc_nidd_open();
    } else if (!strcmp(nipd_string, "close")) {
        urc_nidd_close();
    }
}

void QUECTEL_BG96_CellularContext::urc_nidd_open()
{
    int err = _at.read_int();
    if (!err) {
        _is_context_active = true;
        _is_context_activated = true;
        _cid = NIDD_PDP_CONTEXT_ID;
    } else {
        tr_error("NIDD connection open failed with error: %d", err);
    }
}

void QUECTEL_BG96_CellularContext::urc_nidd_close()
{
    set_disconnect();
}

nsapi_error_t QUECTEL_BG96_CellularContext::setup_control_plane_opt()
{
    _at.lock();

    _at.at_cmd_discard("+QCFGEXT", "=\"pdp_type\",", "%d%s%s", NIDD_PDP_CONTEXT_ID, "Non-IP", _apn);

    _at.at_cmd_discard("+CFUN", "=0");

    _at.at_cmd_discard("+CFUN", "=1");

    // Configure Non-IP outgoing data type - 0 for no exception data
    nsapi_error_t err = _at.at_cmd_discard("+QCFGEXT", "=\"nipdcfg\",0,", "%s", _apn);

    if (err == NSAPI_ERROR_OK) {
        _cp_in_use = true;
        if (_nonip_req) {
            _pdp_type = NON_IP_PDP_TYPE;
        }
    }

    return _at.unlock_return_error();
}

} /* namespace mbed */
<commit_msg>Fixed PDP type handling<commit_after>/*
 * Copyright (c) 2018, Arm Limited and affiliates.
 * SPDX-License-Identifier: Apache-2.0
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "QUECTEL_BG96_CellularContext.h"
#include "QUECTEL_BG96_CellularStack.h"
#include "QUECTEL_BG96_ControlPlane_netif.h"
#include "CellularLog.h"

#include "Semaphore.h"

namespace mbed {

// Non-IP context supported only for context id 1
#define NIDD_PDP_CONTEXT_ID 1
// Timeout to wait for URC indicating NIDD connection opening
#define NIDD_OPEN_URC_TIMEOUT 3000

QUECTEL_BG96_CellularContext::QUECTEL_BG96_CellularContext(ATHandler &at, CellularDevice *device, const char *apn, bool cp_req, bool nonip_req) :
    AT_CellularContext(at, device, apn, cp_req, nonip_req)
{
    if (_nonip_req) {
        _at.set_urc_handler("+QIND:", mbed::Callback<void()>(this, &QUECTEL_BG96_CellularContext::urc_nidd));
    }
}

QUECTEL_BG96_CellularContext::~QUECTEL_BG96_CellularContext()
{
    if (_nonip_req) {
        _at.set_urc_handler("+QIND:", 0);
    }
}

#if !NSAPI_PPP_AVAILABLE
NetworkStack *QUECTEL_BG96_CellularContext::get_stack()
{
    if (_pdp_type == NON_IP_PDP_TYPE || (_nonip_req && _pdp_type != DEFAULT_PDP_TYPE)) {
        tr_error("Requesting stack for NON-IP context! Should request control plane netif: get_cp_netif()");
        return NULL;
    }

    if (!_stack) {
        _stack = new QUECTEL_BG96_CellularStack(_at, _cid, (nsapi_ip_stack_t)_pdp_type, *get_device());
    }

    return _stack;
}
#endif // #if !NSAPI_PPP_AVAILABLE

ControlPlane_netif *QUECTEL_BG96_CellularContext::get_cp_netif()
{
    if (!_cp_netif) {
        _cp_netif = new QUECTEL_BG96_ControlPlane_netif(_at, _cid, *get_device());
    }
    return _cp_netif;
}

nsapi_error_t QUECTEL_BG96_CellularContext::do_user_authentication()
{
    uint8_t type = (uint8_t)_pdp_type;
    if ((uint8_t)_pdp_type < 1) {
        type = 1;
    }

    if (_pwd && _uname) {
        if (_at.at_cmd_discard("+QICSGP", "=", "%d%d%s%s%s%d", _cid, type,
                               _apn, _uname, _pwd, _authentication_type) != NSAPI_ERROR_OK) {
            return NSAPI_ERROR_AUTH_FAILURE;
        }
    } else {
        if (_at.at_cmd_discard("+QICSGP", "=", "%d%d%s", _cid, type,
                               _apn) != NSAPI_ERROR_OK) {
            return NSAPI_ERROR_AUTH_FAILURE;
        }
    }

    return NSAPI_ERROR_OK;
}

nsapi_error_t QUECTEL_BG96_CellularContext::activate_non_ip_context()
{

    // Open the NIDD connection
    nsapi_size_or_error_t ret = _at.at_cmd_discard("+QCFGEXT", "=\"nipd\",1");
    if (ret == NSAPI_ERROR_OK) {
        _at.lock();
        _at.set_at_timeout(NIDD_OPEN_URC_TIMEOUT);
        _at.resp_start("+QIND:");
        urc_nidd();
        _at.restore_at_timeout();
        _at.unlock();
        if (_cid == -1) {
            return NSAPI_ERROR_NO_CONNECTION;
        }
    }

    return (ret == NSAPI_ERROR_OK) ? NSAPI_ERROR_OK : NSAPI_ERROR_NO_CONNECTION;
}

void QUECTEL_BG96_CellularContext::activate_context()
{
    tr_info("Activate PDP context %d", _cid);

    if (_at.at_cmd_discard("+QIACT", "=", "%d", _cid) == NSAPI_ERROR_OK) {
        _is_context_activated = true;
    }
}

void QUECTEL_BG96_CellularContext::deactivate_context()
{
    _at.at_cmd_discard("+QIDEACT", "=", "%d", _cid);
}

void QUECTEL_BG96_CellularContext::deactivate_non_ip_context()
{
    // Close the NIDD connection
    _at.at_cmd_discard("+QCFGEXT", "=\"nipd\",0");
}

void QUECTEL_BG96_CellularContext::urc_nidd()
{
    char nipd_string[6];

    // skip "nipd"
    _at.skip_param();
    _at.read_string(nipd_string, sizeof(nipd_string));

    if (!strcmp(nipd_string, "recv")) {
        cp_data_received();
    } else if (!strcmp(nipd_string, "open")) {
        urc_nidd_open();
    } else if (!strcmp(nipd_string, "close")) {
        urc_nidd_close();
    }
}

void QUECTEL_BG96_CellularContext::urc_nidd_open()
{
    int err = _at.read_int();
    if (!err) {
        _is_context_active = true;
        _is_context_activated = true;
        _cid = NIDD_PDP_CONTEXT_ID;
    } else {
        tr_error("NIDD connection open failed with error: %d", err);
    }
}

void QUECTEL_BG96_CellularContext::urc_nidd_close()
{
    set_disconnect();
}

nsapi_error_t QUECTEL_BG96_CellularContext::setup_control_plane_opt()
{
    _at.lock();

    _at.at_cmd_discard("+QCFGEXT", "=\"pdp_type\",", "%d%s%s", NIDD_PDP_CONTEXT_ID, "Non-IP", _apn);

    _at.at_cmd_discard("+CFUN", "=0");

    _at.at_cmd_discard("+CFUN", "=1");

    // Configure Non-IP outgoing data type - 0 for no exception data
    nsapi_error_t err = _at.at_cmd_discard("+QCFGEXT", "=\"nipdcfg\",0,", "%s", _apn);

    if (err == NSAPI_ERROR_OK) {
        _cp_in_use = true;
        if (_nonip_req) {
            _pdp_type = NON_IP_PDP_TYPE;
        }
    }

    return _at.unlock_return_error();
}

} /* namespace mbed */
<|endoftext|>