score.cc 55.6 KB
Newer Older
Robert Ricci's avatar
Robert Ricci committed
1 2
/*
 * EMULAB-COPYRIGHT
3
 * Copyright (c) 2000-2006 University of Utah and the Flux Group.
Robert Ricci's avatar
Robert Ricci committed
4 5 6
 * All rights reserved.
 */

7

8
#include "port.h"
9

10
#include <iostream>
11 12
#include <float.h>

13 14 15 16
/*
 * We have to do these includes differently depending on which version of gcc
 * we're compiling with
 */
17
#ifdef NEW_GCC
18 19 20 21
#include <ext/hash_map>
#include <ext/hash_set>
using namespace __gnu_cxx;
#else
22 23
#include <hash_map>
#include <hash_set>
24
#endif
25 26 27 28 29 30 31 32

#include <boost/config.hpp>
#include <boost/utility.hpp>
#include <boost/property_map.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/adjacency_list.hpp>

using namespace boost;
33 34

#include "common.h"
35
#include "vclass.h"
36
#include "delay.h"
37
#include "physical.h"
38
#include "virtual.h"
39 40
#include "pclass.h"
#include "score.h"
41
#include "featuredesire.h"
42

43
#include "math.h"
44

45
extern switch_pred_map_map switch_preds;
46

47
extern bool disable_pclasses;
48

49
double score;			// The score of the current mapping
50 51 52 53 54
int violated;			// How many times the restrictions
				// have been violated.

violated_info vinfo;		// specific info on violations

55
extern tb_vgraph VG;		// virtual graph
56
extern tb_pgraph PG;		// physical grpaph
57
extern tb_sgraph SG;		// switch fabric
58

59 60
void score_link(pedge pe,vedge ve,tb_pnode *src_pnode,tb_pnode *dst_pnode);
void unscore_link(pedge pe,vedge ve,tb_pnode *src_pnode,tb_pnode *dst_pnode);
61 62
bool find_best_link(pvertex pv,pvertex switch_pv,tb_vlink *vlink,
                    pedge &out_edge);
63 64 65
int find_interswitch_path(pvertex src_pv,pvertex dest_pv,
			  int bandwidth,pedge_path &out_path,
			  pvertex_list &out_switches);
66 67
score_and_violations score_fds(tb_vnode *vnode, tb_pnode *pnode, bool add);

68 69 70 71
void score_link_info(vedge ve, tb_pnode *src_pnode, tb_pnode *dst_pnode,
	tb_vnode *src_vnode, tb_vnode *dst_vnode);
void unscore_link_info(vedge ve, tb_pnode *src_pnode, tb_pnode *dst_pnode,
	tb_vnode *src_vnode, tb_vnode *dst_vnode);
72 73 74 75

#ifdef FIX_PLINK_ENDPOINTS
void score_link_endpoints(pedge pe);
#endif
76 77

#ifdef SCORE_DEBUG_MORE
78 79
#define SADD(amount) cerr << "SADD: " << #amount << "=" << amount << " from " << score;score+=amount;cerr << " to " << score << endl
#define SSUB(amount)  cerr << "SSUB: " << #amount << "=" << amount << " from " << score;score-=amount;cerr << " to " << score << endl
80 81 82 83 84
#else
#define SADD(amount) score += amount
#define SSUB(amount) score -= amount
#endif

85 86 87 88
// For convenience, so we can easily turn on or off one statement
#define SDEBADD(amount) cerr << "SADD: " << #amount << "=" << amount << " from " << score;score+=amount;cerr << " to " << score << endl
#define SDEBSUB(amount)  cerr << "SSUB: " << #amount << "=" << amount << " from " << score;score-=amount;cerr << " to " << score << endl

89 90 91
#ifdef SCORE_DEBUG
#define SDEBUG(a) a
#else
92
#define SDEBUG(a) 
93 94
#endif

95 96 97
#define MIN(a,b) (((a) < (b))? (a) : (b))
#define MAX(a,b) (((a) > (b))? (a) : (b))

98 99 100 101
/*
 * score()
 * Returns the score.
 */
102
double get_score() {return score;}
103 104 105 106 107 108 109 110

/*
 * init_score()
 * This initialized the scoring system.  It also clears all
 * assignments.
 */
void init_score()
{
111
  SDEBUG(cerr << "SCORE: Initializing" << endl);
112 113 114
  score=0;
  violated=0;

115 116 117 118 119
  vvertex_iterator vvertex_it,end_vvertex_it;
  tie(vvertex_it,end_vvertex_it) = vertices(VG);
  for (;vvertex_it!=end_vvertex_it;++vvertex_it) {
    tb_vnode *vnode=get(vvertex_pmap,*vvertex_it);
    vnode->assigned = false;
120 121 122 123
    SADD(SCORE_UNASSIGNED);
    vinfo.unassigned++;
    violated++;
  }
124 125 126 127
  vedge_iterator vedge_it,end_vedge_it;
  tie(vedge_it,end_vedge_it) = edges(VG);
  for (;vedge_it!=end_vedge_it;++vedge_it) {
    tb_vlink *vlink=get(vedge_pmap,*vedge_it);
128
    vlink->link_info.type_used=tb_link_info::LINK_UNMAPPED;
129
    vlink->no_connection=false;
130
  }
131 132
  pvertex_iterator pvertex_it,end_pvertex_it;
  tie(pvertex_it,end_pvertex_it) = vertices(PG);
133
  /*
134 135 136 137 138 139
  for (;pvertex_it!=end_pvertex_it;++pvertex_it) {
    tb_pnode *pn=get(pvertex_pmap,*pvertex_it);
    pn->typed=false;
    pn->current_load=0;
    pn->pnodes_used=0;
    pn->switch_used_links=0;
140
  }
141
  */
142 143 144 145 146 147 148
  pedge_iterator pedge_it,end_pedge_it;
  tie(pedge_it,end_pedge_it) = edges(PG);
  for (;pedge_it!=end_pedge_it;++pedge_it) {
    tb_plink *plink=get(pedge_pmap,*pedge_it);
    plink->bw_used=0;
    plink->emulated=0;
    plink->nonemulated=0;
149 150
  }

151
  SDEBUG(cerr << "  score=" << score << " violated=" << violated << endl);
152
}
153

154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599
/*
 * Find all possbile resolutions for a link. The possible resolutions are placed
 * into the resolutions parameter, and the total weight of all resolutions are
 * returned.
 */
float find_link_resolutions(resolution_vector &resolutions, pvertex pv,
    pvertex dest_pv, tb_vlink *vlink, tb_pnode *pnode, tb_pnode *dest_pnode,
    bool flipped) {
  SDEBUG(cerr << "   finding link resolutions" << endl);
  /* We need to calculate all possible link resolutions, stick
   * them in a nice datastructure along with their weights, and
   * then select one randomly.
   */
  typedef vector<pvertex_list> switchlist_vector;

  float total_weight = 0;

  // Trivial link
  if (dest_pv == pv) {
    SDEBUG(cerr << "  trivial link" << endl);

    /*
     * Sometimes, we might not want to let a vlink be resolved as a
     * trivial link
     */
    if (allow_trivial_links && vlink->allow_trivial) {
      tb_link_info info(tb_link_info::LINK_TRIVIAL);
      resolutions.push_back(info);
      total_weight += LINK_RESOLVE_TRIVIAL;
    }

    /*
     * This is to preserve some old behaviour - if we see a trivial link, that's
     * the only one we consider using. Need to revisit this to see if it's always
     * desirable.
     */
    return total_weight;
  }

  pedge pe;
  // Direct link
  if (find_best_link(dest_pv,pv,vlink,pe)) {
    tb_link_info info(tb_link_info::LINK_DIRECT);
    info.plinks.push_back(pe);
    resolutions.push_back(info);
    total_weight += LINK_RESOLVE_DIRECT;
    SDEBUG(cerr << "    direct_link " << pe << endl);
  }
  // Intraswitch link
  pedge first,second;
  for (pvertex_set::iterator switch_it = pnode->switches.begin();
      switch_it != pnode->switches.end();++switch_it) {
    if (dest_pnode->switches.find(*switch_it) !=
        dest_pnode->switches.end()) {
      bool first_link, second_link;
      /*
       * Check to see if either, or both, pnodes are actually
       * the switch we are looking for
       */
      if (pv == *switch_it) {
        first_link = false;
      } else {
        first_link = true;
      }
      if (dest_pv == *switch_it) {
        second_link = false;
      } else {
        second_link = true;
      }

      /*
       * Intraswitch links to switches are not allowed - they
       * will be caught as direct links above
       */
      if (pnode->is_switch || dest_pnode->is_switch) {
        SDEBUG(cerr << "    intraswitch failed - switch" << endl;)
          continue;
      }

      if (first_link) {
        if (!find_best_link(pv,*switch_it,vlink,first)) {
          SDEBUG(cerr << "    intraswitch failed - no link first" <<
              endl;)
            // No link to this switch
            continue;
        }
      }

      if (second_link) {
        if (!find_best_link(dest_pv,*switch_it,vlink,second)) {
          // No link to this switch
          SDEBUG(cerr << "    intraswitch failed - no link second" <<
              endl;)
            continue;
        }
      }

      tb_link_info info(tb_link_info::LINK_INTRASWITCH);
      /*
       * Order these need to go in depends on flipped bit
       */
      if (flipped) {
        if (second_link) {
          info.plinks.push_back(second);
        }
        if (first_link) {
          info.plinks.push_back(first);
        }
      } else {
        if (first_link) {
          info.plinks.push_back(first);
        }
        if (second_link) {
          info.plinks.push_back(second);
        }
      }
      info.switches.push_front(*switch_it);
      resolutions.push_back(info);
      
      total_weight += LINK_RESOLVE_INTRASWITCH;
      SDEBUG(cerr << "    intraswitch " << first << " and " << second
          <<                     endl);
    }
  }
  for (pvertex_set::iterator source_switch_it = pnode->switches.begin();
      source_switch_it != pnode->switches.end();
      ++source_switch_it) {
    int tmp = 0;
    for (pvertex_set::iterator dest_switch_it =
        dest_pnode->switches.begin();
        dest_switch_it != dest_pnode->switches.end();
        ++dest_switch_it) {
      if (*source_switch_it == *dest_switch_it) continue;
      tb_link_info info(tb_link_info::LINK_INTERSWITCH);
      if (find_interswitch_path(*source_switch_it,*dest_switch_it,vlink->delay_info.bandwidth,
            info.plinks, info.switches) != 0) {
        bool first_link, second_link;
        /*
         * Check to see if either, or both, pnodes are actually the
         * switches we are looking for
         */
        if ((pv == *source_switch_it) || (pv ==
              *dest_switch_it)) {
          first_link = false;
        } else {
          first_link = true;
        }
        if ((dest_pv == *source_switch_it) ||
            (dest_pv == *dest_switch_it)) {
          second_link = false;
        } else {
          second_link = true;
        }

        if (first_link) {
          if
            (!find_best_link(pv,*source_switch_it,vlink,first)) {
              // No link to this switch
              SDEBUG(cerr << "    interswitch failed - no first link"
                  << endl;)
                continue;
            }
        }

        if (second_link) {
          if (!find_best_link(dest_pv,*dest_switch_it,vlink,second)) {
            // No link to tshis switch
            SDEBUG(cerr << "    interswitch failed - no second link" <<                                          endl;)
              continue;
          }
        }

        if (flipped) { // Order these need to go in depends on flipped bit
          if (second_link) {
            info.plinks.push_front(second);
          }
          if (first_link) {
            info.plinks.push_back(first);
          }
        } else {
          if (first_link) {
           info.plinks.push_front(first);
          }
          if (second_link) {
            info.plinks.push_back(second);
          }
        }
        resolutions.push_back(info);
        total_weight += LINK_RESOLVE_INTERSWITCH;
        SDEBUG(cerr << "    interswitch " <<
            get(pvertex_pmap,*source_switch_it)->name
            << " and " <<
            get(pvertex_pmap,*dest_switch_it)->name <<
            endl);
      } else {
        SDEBUG(cerr << "    interswitch failed - no switch path";)
      }
    }
  }
      
  return total_weight;

}


/*
 * Return the cost of a resolution
 */
inline float resolution_cost(tb_link_info::linkType res_type) {
    switch (res_type) {
	case tb_link_info::LINK_DIRECT:
	    return LINK_RESOLVE_DIRECT; break;
	case tb_link_info::LINK_INTRASWITCH:
	    return LINK_RESOLVE_INTRASWITCH; break;
	case tb_link_info::LINK_INTERSWITCH:
	    return LINK_RESOLVE_INTERSWITCH; break;
	case tb_link_info::LINK_UNMAPPED:
	case tb_link_info::LINK_TRIVIAL:
	    cerr << "*** Internal error: Should not be here. (resolution_cost)" << endl;
   	    exit(EXIT_FATAL);
	break;
    }
}

/*
 * Mark a vlink as unassigned
 */
void mark_vlink_unassigned(tb_vlink *vlink) {
    SADD(SCORE_NO_CONNECTION);
    vlink->no_connection=true;
    vinfo.no_connection++;
    vlink->link_info.type_used = tb_link_info::LINK_UNMAPPED;
    violated++;
}

/*
 * Resolve an individual vlink
 */
void resolve_link(vvertex vv, pvertex pv, tb_vnode *vnode, tb_pnode *pnode,
    bool deterministic, vedge edge) {
  tb_vlink *vlink = get(vedge_pmap,edge);
  vvertex dest_vv = target(edge,VG);

  if (dest_vv == vv) {
    dest_vv = source(edge,VG);
  }

  /*
   * Indicates that we've assigned the nodes in reverse order compared to
   * what's in the vlink, so we need to reverse the ordering in the
   * pedge_path
   */
  bool flipped = false;
  if (vlink->src != vv) {
    flipped = true;
  }

  /*
   * Find the link's destination
   */
  tb_vnode *dest_vnode = get(vvertex_pmap,dest_vv);
  SDEBUG(cerr << "  edge to " << dest_vnode->name << endl);

  /*
   * If the other end of the link is assigned, we can go ahead and try to
   * find a mapping for the link
   */
  if (dest_vnode->assigned) {
    pvertex dest_pv = dest_vnode->assignment;
    tb_pnode *dest_pnode = get(pvertex_pmap,dest_pv);

    SDEBUG(cerr << "   goes to " << dest_pnode->name << endl);

    if (dest_pv == pv) {
      SDEBUG(cerr << "  trivial link" << endl);
      
      if (allow_trivial_links && vlink->allow_trivial) {
        vlink->link_info.type_used = tb_link_info::LINK_TRIVIAL;
        /*
         * XXX - okay, this is really bad, but score_link_info
         * doesn't usually get called for trivial links, and
         * letting them fall through into the 'normal' link code
         * below is disatrous!
         */
        score_link_info(edge,pnode,dest_pnode,vnode,dest_vnode);
      } else {
	  mark_vlink_unassigned(vlink);
      }
    } else {
      //assert(resolution_index <= 1)
      resolution_vector resolutions;
      float total_weight = find_link_resolutions(resolutions, pv, dest_pv,
          vlink,pnode,dest_pnode,flipped);
      
      /*
       * If they have asked for a specific interface, filter out any
       * resolutions that don't have it
       */
      if (vlink->fix_src_iface) {
	  resolution_vector::iterator rit;
	  for (rit = resolutions.begin(); rit != resolutions.end();) {
	      pedge link = (*rit).plinks.front();
	      tb_plink *plink = get(pedge_pmap,link);
	      if (plink->srciface != vlink->src_iface) {
		  // Doesn't match, remove it!
		   total_weight -= resolution_cost(rit->type_used);
		   rit = resolutions.erase(rit);
	       } else {
		   rit++;
	       }
	  }
      }
      
      if (vlink->fix_dst_iface) {
	  resolution_vector::iterator rit;
	  for (rit = resolutions.begin(); rit != resolutions.end();) {
	      pedge link = (*rit).plinks.back();
	      tb_plink *plink = get(pedge_pmap,link);
	      // Yes, this really is srciface
	      // XXX: This only works because we always have the node as the 'source'
	      // of a plink! Shouldn't depend on this!
	      if (plink->srciface != vlink->dst_iface) {
		  // Doesn't match, remove it!
		  total_weight -= resolution_cost(rit->type_used);
		  rit = resolutions.erase(rit);
	      } else {
		  rit++;
	      }
	  }
      }
      
      int n_resolutions = resolutions.size();
      //int resolution_index = n_resolutions - 1;
      int resolution_index = n_resolutions;
      
      /*
       * check for no link
       */
      if (resolution_index == 0) {
        SDEBUG(cerr << "  Could not find any resolutions" << endl;)
        mark_vlink_unassigned(vlink);
      } else {
        /*
         * Check to see if we are fixing a violation
         */
        if (vlink->no_connection) {
          SDEBUG(cerr << "  Fixing previous violations." << endl);
          SSUB(SCORE_NO_CONNECTION);
          vlink->no_connection=false;
          vinfo.no_connection--;
          violated--;
        }
        /*
         * Choose a link
         */
        int index;
        if (!deterministic && !greedy_link_assignment) {
          /*
           * Not deterministic - randomly pick between the possibilities
           * we've found.
           */
          float choice;
          choice = RANDOM()%(int)total_weight;
          for (index = 0;index < resolution_index;++index) {
            switch (resolutions[index].type_used) {
              case tb_link_info::LINK_DIRECT:
                choice -= LINK_RESOLVE_DIRECT; break;
              case tb_link_info::LINK_INTRASWITCH:
                choice -= LINK_RESOLVE_INTRASWITCH; break;
              case tb_link_info::LINK_INTERSWITCH:
                choice -= LINK_RESOLVE_INTERSWITCH; break;
              case tb_link_info::LINK_UNMAPPED:
              case tb_link_info::LINK_TRIVIAL:
                cerr << "*** Internal error: Should not be here." <<
                  endl;
                exit(EXIT_FATAL);
                break;
            }
            if (choice < 0) break;
          }
        } else {
          /*
           * Deterministic - try all possibilities, and go with the best one
           * (the one with the best score)
           */
          cerr << "Doing deterministic link resolution" << endl;
          cerr << "total_weight: " << total_weight << ", resolution_index: "
            << resolution_index << endl;
          int bestindex;
          int bestviolated = 10000;
          double bestscore=10000.0;
          int i;
          for (i=0;i<resolution_index;++i) {
            vlink->link_info = resolutions[i];
            score_link_info(edge,pnode,dest_pnode,vnode,dest_vnode);
            if ((score <= bestscore) &&
                (violated <= bestviolated)) {
              bestscore = score;
              bestviolated = violated;
              bestindex = i;
            }
            unscore_link_info(edge,pnode,dest_pnode,vnode,dest_vnode);
          }
          index = bestindex;
        }
#ifdef PENALIZE_UNUSED_INTERFACES
        pnode->used_interfaces++;
#endif
        vlink->link_info = resolutions[index];
        SDEBUG(cerr << "  choice:" << vlink->link_info);
        score_link_info(edge,pnode,dest_pnode,vnode,dest_vnode);
      }
    }
  }
}

/*
 * Assign any links on the vnode that can now be assigned (due to the other
 * end of the link also being assigned)
 */
void resolve_links(vvertex vv, pvertex pv, tb_vnode *vnode, tb_pnode *pnode,
    bool deterministic) {
  /*
   * Loop through all vlinks connected to this vnode
   */
  voedge_iterator vedge_it,end_vedge_it;
  tie(vedge_it,end_vedge_it) = out_edges(vv,VG);
  hash_set<const tb_vlink*, hashptr<const tb_vlink*> > seen_links;
  for (;vedge_it!=end_vedge_it;++vedge_it) {
    /*
     * We have to be careful, because we can see loopback links twice, since
     * both endpoints are on the same vnode and the same pnode. If we've seen
     * this link before, just go onto the next
     */
    // XXX: Seems silly to do this here, then again at the top of resolve_link
    tb_vlink *vlink = get(vedge_pmap,*vedge_it);
    if (seen_links.find(vlink) != seen_links.end()) {
      SDEBUG(cerr << "    seen before - skipping" << endl);
      continue;
    } else {
      seen_links.insert(vlink);      
      resolve_link(vv,pv,vnode,pnode,deterministic,*vedge_it);
    }
  }
}

600 601 602 603
/* unscore_link_info(vedge ve)
 * This routine is the highest level link scorer.  It handles all
 * scoring that depends on the link_info of vlink.
 */
604 605
void unscore_link_info(vedge ve,tb_pnode *src_pnode,tb_pnode *dst_pnode, tb_vnode *src_vnode,
	tb_vnode *dst_vnode)
606 607
{
  tb_vlink *vlink = get(vedge_pmap,ve);
608 609 610

  // Handle vnodes that are not allowed to have a mix of trivial and
  // non-trivial links
611
  if (vlink->link_info.type_used == tb_link_info::LINK_TRIVIAL) {
612 613 614 615 616 617
      src_vnode->trivial_links--;
      dst_vnode->trivial_links--;
      if (src_vnode->disallow_trivial_mix &&
	      (src_vnode->trivial_links == 0) &&
	      (src_vnode->nontrivial_links != 0)) {
	  // We just removed the last trivial link
618
	  SSUB(SCORE_TRIVIAL_MIX);
619 620 621 622 623 624 625
	  violated--;
	  vinfo.trivial_mix--;
      }
      if (dst_vnode->disallow_trivial_mix &&
	      (dst_vnode->trivial_links == 0) &&
	      (dst_vnode->nontrivial_links != 0)) {
	  // We just removed the last trivial link
626
	  SSUB(SCORE_TRIVIAL_MIX);
627 628 629
	  violated--;
	  vinfo.trivial_mix--;
      }
630
  } else if (vlink->link_info.type_used != tb_link_info::LINK_UNMAPPED) {
631 632 633 634 635 636
      src_vnode->nontrivial_links--;
      dst_vnode->nontrivial_links--;
      if (src_vnode->disallow_trivial_mix &&
	      (src_vnode->nontrivial_links == 0) &&
	      (src_vnode->trivial_links != 0)) {
	  // We just removed the last nontrivial link
637
	  SSUB(SCORE_TRIVIAL_MIX);
638 639 640 641 642 643 644
	  violated--;
	  vinfo.trivial_mix--;
      }
      if (dst_vnode->disallow_trivial_mix &&
	      (dst_vnode->nontrivial_links == 0) &&
	      (dst_vnode->trivial_links != 0)) {
	  // We just removed the last nontrivial link
645
	  SSUB(SCORE_TRIVIAL_MIX);
646 647 648 649 650 651
	  violated--;
	  vinfo.trivial_mix--;
      }
  }

  // Unscore the link itself
652
  if (vlink->link_info.type_used == tb_link_info::LINK_DIRECT) {
653 654
    // DIRECT LINK
    SDEBUG(cerr << "   direct link" << endl);
655 656 657
    src_pnode->nontrivial_bw_used -= vlink->delay_info.bandwidth;
    dst_pnode->nontrivial_bw_used -= vlink->delay_info.bandwidth;

658
    SSUB(SCORE_DIRECT_LINK);
659 660
    unscore_link(vlink->link_info.plinks.front(),ve,src_pnode,dst_pnode);
    vlink->link_info.plinks.clear();
661
  } else if (vlink->link_info.type_used == tb_link_info::LINK_INTERSWITCH) {
662 663
    // INTERSWITCH LINK
    SDEBUG(cerr << "  interswitch link" << endl);
664 665
    src_pnode->nontrivial_bw_used -= vlink->delay_info.bandwidth;
    dst_pnode->nontrivial_bw_used -= vlink->delay_info.bandwidth;
666 667 668 669
    
#ifndef INTERSWITCH_LENGTH
    SSUB(SCORE_INTERSWITCH_LINK);
#endif
670 671

    pedge_path &path = vlink->link_info.plinks;
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
    // XXX: Potentially bogus;
    int numinterlinks;
    numinterlinks = -2;
    for (pedge_path::iterator it=path.begin();
	 it != path.end();++it) {
      unscore_link(*it,ve,src_pnode,dst_pnode);
      numinterlinks++;
    }
#ifdef INTERSWITCH_LENGTH
    for (int i = 1; i <= numinterlinks; i++) {
      SSUB(SCORE_INTERSWITCH_LINK);
    }
#endif

    path.clear();
    for (pvertex_list::iterator it = vlink->link_info.switches.begin();
	 it != vlink->link_info.switches.end();++it) {
      tb_pnode *the_switch = get(pvertex_pmap,*it);
      if (--the_switch->switch_used_links == 0) {
	SDEBUG(cerr << "  releasing switch" << endl);
	SSUB(SCORE_SWITCH);
      }
694 695
      // We count the bandwidth into and out of the switch
      the_switch->nontrivial_bw_used -= vlink->delay_info.bandwidth * 2;
696 697
    }
    vlink->link_info.switches.clear();
698
  } else if (vlink->link_info.type_used == tb_link_info::LINK_INTRASWITCH) {
699 700
    // INTRASWITCH LINK
    SDEBUG(cerr << "   intraswitch link" << endl);
701 702 703
    src_pnode->nontrivial_bw_used -= vlink->delay_info.bandwidth;
    dst_pnode->nontrivial_bw_used -= vlink->delay_info.bandwidth;

704 705 706 707 708 709 710
    SSUB(SCORE_INTRASWITCH_LINK);
    
    unscore_link(vlink->link_info.plinks.front(),ve,src_pnode,dst_pnode);
    unscore_link(vlink->link_info.plinks.back(),ve,src_pnode,dst_pnode);
    vlink->link_info.plinks.clear();
    tb_pnode *the_switch = get(pvertex_pmap,
			       vlink->link_info.switches.front());
711 712
    // We count the bandwidth into and out of the switch
    the_switch->nontrivial_bw_used -= vlink->delay_info.bandwidth * 2;
713 714 715 716 717 718
    if (--the_switch->switch_used_links == 0) {
      SDEBUG(cerr << "  releasing switch" << endl);
      SSUB(SCORE_SWITCH);
    }
    vlink->link_info.switches.clear();
  }
719 720

#ifdef TRIVIAL_LINK_BW
721
  else if (vlink->link_info.type_used == tb_link_info::LINK_TRIVIAL) {
722
      // Trivial link - we may get to remove violations
Robert Ricci's avatar
Robert Ricci committed
723 724 725 726 727 728
      SDEBUG(cerr << "  trivial bandwidth used " <<
	      src_pnode->trivial_bw_used << " max is " <<
	      src_pnode->trivial_bw << " subtracting " <<
	      vlink->delay_info.bandwidth << endl);
      if (src_pnode->trivial_bw) {
	int old_over_bw;
729
	int old_bw = src_pnode->trivial_bw_used;
Robert Ricci's avatar
Robert Ricci committed
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745
	if (src_pnode->trivial_bw_used > src_pnode->trivial_bw) {
	  old_over_bw = src_pnode->trivial_bw_used - src_pnode->trivial_bw;
	} else {
	  old_over_bw = 0;
	}

	src_pnode->trivial_bw_used -= vlink->delay_info.bandwidth;

	int new_over_bw;
	if (src_pnode->trivial_bw_used > src_pnode->trivial_bw) {
	  new_over_bw = src_pnode->trivial_bw_used - src_pnode->trivial_bw;
	} else {
	  new_over_bw = 0;
	}

	if (old_over_bw) {
746
	  // Count how many multiples of the maximum bandwidth we're at
747 748 749 750
	  int num_violations = (int)(
	      floor((double)(old_bw -1)/src_pnode->trivial_bw)
	      - floor((double)(src_pnode->trivial_bw_used -1) /
		src_pnode->trivial_bw));
751 752
	  violated -= num_violations;
	  vinfo.bandwidth -= num_violations;
Robert Ricci's avatar
Robert Ricci committed
753 754 755 756
	  double removed_bandwidth_percent = (old_over_bw - new_over_bw) * 1.0 /
	    src_pnode->trivial_bw;
	  SSUB(SCORE_TRIVIAL_PENALTY * removed_bandwidth_percent);
	}
757
      }
Robert Ricci's avatar
Robert Ricci committed
758

759 760 761
      unscore_link(vlink->link_info.plinks.front(),ve,src_pnode,dst_pnode);
  }
#endif
762

763
}
764

765 766
/*
 * This removes a virtual node from the assignments, adjusting
767 768
 * the score appropriately.
 */
769
void remove_node(vvertex vv)
770
{
771
  // Find the vnode associated with the vvertex, and the pnode it's assigned to
772 773 774 775 776 777 778 779 780 781
  tb_vnode *vnode = get(vvertex_pmap,vv);
  assert(vnode->assigned);
  pvertex pv = vnode->assignment;
  tb_pnode *pnode = get(pvertex_pmap,pv);

  SDEBUG(cerr <<  "SCORE: remove_node(" << vnode->name << ")" << endl);
  SDEBUG(cerr <<  "  assignment=" << pnode->name << endl);
#ifdef SCORE_DEBUG_LOTS
  cerr << *vnode;
  cerr << *pnode;
782 783 784 785
#endif

  assert(pnode != NULL);

786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804
  /* 
   * Find the type on the pnode that this vnode is associated with
   */
  tb_pnode::types_map::iterator mit = pnode->types.find(vnode->type);
  tb_pnode::type_record *tr;
  if (mit == pnode->types.end()) {
      // This is kind of a hack - if we don't find the type, then the vnode
      // must have a vtype. So, we assume it must have been assigned to this
      // node's dynamic type at some point.
      // A consequence of this hack is that vtypes can't map to static types,
      // for now.
      RDEBUG(cerr << "Failed to find type " << vnode->type << " (for vnode " <<
	  vnode->name << ") on pnode " << pnode->name << endl;)
      tr = pnode->current_type_record;
  } else {
      tr = mit->second;
  }
 

805 806 807
  /*
   * Clean up the pnode's state
   */
808 809 810 811
  if (!tr->is_static) {
    if (pnode->my_class) {
      pclass_unset(pnode);
    }
812
  }
813

814 815
#ifdef SMART_UNMAP
  pnode->assigned_nodes.erase(vnode);
816
#endif
817 818

  // pclass
819 820
  if ((!disable_pclasses) && !(tr->is_static) && pnode->my_class
	  && (pnode->my_class->used_members == 0)) {
821
    SDEBUG(cerr << "  freeing pclass" << endl);
822 823
    SSUB(SCORE_PCLASS);
  }
824 825

  // vclass
826 827 828
  if (vnode->vclass != NULL) {
    double score_delta = vnode->vclass->unassign_node(vnode->type);
    SDEBUG(cerr << "  vclass unassign " << score_delta << endl);
829 830 831 832 833 834 835
    
    if (score_delta <= -1) {
      violated--;
      vinfo.vclass--;
    }
    SSUB(-score_delta*SCORE_VCLASS);
  }
836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868

  /*
   * Handle subnodes
   */
  if (vnode->subnode_of) {
      // First handle our parent
      if (vnode->subnode_of->assigned) {
	  tb_pnode *assignment = get(pvertex_pmap,
		  vnode->subnode_of->assignment);
	  if ((!pnode->subnode_of) ||
		 (pnode->subnode_of != assignment)) {
	      SSUB(SCORE_SUBNODE);
	      violated--;
	      vinfo.subnodes--;
	  }
      }
  }
  if (!vnode->subnodes.empty()) {
      // Then any children we might have
      tb_vnode::subnode_list::iterator sit;
      for (sit = vnode->subnodes.begin(); sit != vnode->subnodes.end(); sit++) {
	  if ((*sit)->assigned) {
	      tb_pnode *assignment = get(pvertex_pmap,(*sit)->assignment);
	  if ((!assignment->subnode_of) ||
		 (assignment->subnode_of != pnode)) {
		  SSUB(SCORE_SUBNODE);
		  violated--;
		  vinfo.subnodes--;
	      }
	  }
      }
  }

869 870 871
  /*
   * Now, take care of the virtual links that are attached to the vnode
   */
872 873
  voedge_iterator vedge_it,end_vedge_it;
  tie(vedge_it,end_vedge_it) = out_edges(vv,VG);
874
  hash_set<const tb_vlink*, hashptr<const tb_vlink*> > seen_loopback_links;
875 876
  for (;vedge_it!=end_vedge_it;++vedge_it) {
    tb_vlink *vlink = get(vedge_pmap,*vedge_it);
877 878 879

    // Find the other end of the vlink - we might be either its source or
    // destination (target)
880 881 882 883 884 885
    vvertex dest_vv = target(*vedge_it,VG);
    if (dest_vv == vv)
      dest_vv = source(*vedge_it,VG);
    tb_vnode *dest_vnode = get(vvertex_pmap,dest_vv);
    SDEBUG(cerr << "  edge to " << dest_vnode->name << endl);

886 887 888 889 890 891 892 893 894 895 896
    if (dest_vv == vv) {
      // We have to be careful with 'loopback' links, because we can see them
      // twice - bail out if this is the second time
      if (seen_loopback_links.find(vlink) != seen_loopback_links.end()) {
	SDEBUG(cerr << "    seen before - skipping" << endl);
	continue;
      } else {
	seen_loopback_links.insert(vlink);
      }
    }

897 898
    // A 'not-connected' vlink only counts as a violation if both of its
    // endpoints are assigned
899 900 901 902 903 904
    if (vlink->no_connection) {
      SDEBUG(cerr << "  link no longer in violation.\n";)
      SSUB(SCORE_NO_CONNECTION);
      vlink->no_connection=false;
      vinfo.no_connection--;
      violated--;
905
    }
906
    
907 908
    // Only unscore the link if the vnode on the other end is assigned - this
    // way, only the first end to be unmapped causes unscoring
909 910 911
    if (! dest_vnode->assigned) {
      continue;
    }
912
    
913
    // Find the pnode on the ther end of the link, and unscore it!
914 915
    pvertex dest_pv = dest_vnode->assignment;
    tb_pnode *dest_pnode = get(pvertex_pmap,dest_pv);
916
    unscore_link_info(*vedge_it,pnode,dest_pnode,vnode,dest_vnode);
917
  }
918 919
 
#ifdef PENALIZE_UNUSED_INTERFACES
920
  // Keep track of the number of interfaces that the pnode is using
921 922 923 924
  SSUB((pnode->total_interfaces - pnode->used_interfaces) * SCORE_UNUSED_INTERFACE);
  pnode->used_interfaces = 0;
#endif
 
925 926 927
  /*
   * Adjust scores for the pnode
   */
928 929 930
  int old_load = tr->current_load;
  tr->current_load -= vnode->typecount;
  pnode->total_load -= vnode->typecount;
931
#ifdef LOAD_BALANCE
932 933
  // Use this tricky formula to score based on how 'full' the pnode is, so that
  // we prefer to equally fill the minimum number of pnodes
934 935
  SSUB(SCORE_PNODE * (powf(1+ ((pnode->current_load+1) * 1.0)/pnode->max_load,2)));
  SADD(SCORE_PNODE * (powf(1+ pnode->current_load * 1.0/pnode->max_load,2)));
936
#endif
937
  if (pnode->total_load == 0) {
938
    // If the pnode is now free, we need to do some cleanup
939
    SDEBUG(cerr << "  releasing pnode" << endl);
940
    SSUB(SCORE_PNODE);
941
    pnode->remove_current_type();
942 943 944 945 946 947 948 949 950 951 952
    // ptypes
    tb_pnode::types_list::iterator lit = pnode->type_list.begin();
    while (lit != pnode->type_list.end()) {
	int removed_violations = (*lit)->ptype->remove_users((*lit)->max_load);
	if (removed_violations) {
	    SSUB(SCORE_MAX_TYPES * removed_violations);
	    violated -= removed_violations;
	    vinfo.max_types -= removed_violations;
	}
	lit++;
    }
953 954 955 956 957 958 959 960 961 962 963
  } else if (old_load > tr->max_load) {
    // If the pnode was over its load, remove the penalties for the nodes we
    // just removed, down to the max_load.
    SDEBUG(cerr << "  reducing penalty, old load was " << old_load <<
	    ", new load = " << tr->current_load << ", max load = " <<
	    tr->max_load << endl);
    for (int i = old_load; i > MAX(tr->current_load,tr->max_load); i--) {
      SSUB(SCORE_PNODE_PENALTY);
      vinfo.pnode_load--;
      violated--;
    }
964
  }
965

966 967 968 969 970 971 972 973 974
  /*
   * Score the fact that we now have one more unassigned vnode
   */
  vnode->assigned = false;
  SADD(SCORE_UNASSIGNED);
  vinfo.unassigned++;
  violated++;
  

975 976 977
  /*
   * Scoring for features and desires
   */
978 979 980 981
  score_and_violations sv = score_fds(vnode,pnode,false);
  SSUB(sv.first);
  violated -= sv.second;
  vinfo.desires -= sv.second;
982 983

  SDEBUG(cerr << "  new score = " << score << " new violated = " << violated << endl);
984 985
}

986 987 988
/* score_link_info(vedge ve)
 * This routine is the highest level link scorer.  It handles all
 * scoring that depends on the link_info of vlink.
989
 */
990 991
void score_link_info(vedge ve, tb_pnode *src_pnode, tb_pnode *dst_pnode, tb_vnode *src_vnode,
	tb_vnode *dst_vnode)
992
{
993 994
  tb_vlink *vlink = get(vedge_pmap,ve);
  tb_pnode *the_switch;
995
  switch (vlink->link_info.type_used) {
996 997
  case tb_link_info::LINK_DIRECT:
    SADD(SCORE_DIRECT_LINK);
998 999
    src_pnode->nontrivial_bw_used += vlink->delay_info.bandwidth;
    dst_pnode->nontrivial_bw_used += vlink->delay_info.bandwidth;
1000 1001 1002 1003
    score_link(vlink->link_info.plinks.front(),ve,src_pnode,dst_pnode);
    break;
  case tb_link_info::LINK_INTRASWITCH:
    SADD(SCORE_INTRASWITCH_LINK);
1004 1005
    src_pnode->nontrivial_bw_used += vlink->delay_info.bandwidth;
    dst_pnode->nontrivial_bw_used += vlink->delay_info.bandwidth;
1006 1007 1008 1009 1010 1011 1012 1013
    score_link(vlink->link_info.plinks.front(),ve,src_pnode,dst_pnode);
    score_link(vlink->link_info.plinks.back(),ve,src_pnode,dst_pnode);
    the_switch = get(pvertex_pmap,
		     vlink->link_info.switches.front());
    if (++the_switch->switch_used_links == 1) {
      SDEBUG(cerr << "  new switch" << endl);
      SADD(SCORE_SWITCH);
    }
1014 1015
    // We count the bandwidth into and out of the switch
    the_switch->nontrivial_bw_used += vlink->delay_info.bandwidth * 2;
1016 1017
    break;
  case tb_link_info::LINK_INTERSWITCH:
1018 1019
    src_pnode->nontrivial_bw_used += vlink->delay_info.bandwidth;
    dst_pnode->nontrivial_bw_used += vlink->delay_info.bandwidth;
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
#ifndef INTERSWITCH_LENGTH
    SADD(SCORE_INTERSWITCH_LINK);
#endif
    // XXX: Potentially bogus!
    int numinterlinks;
    numinterlinks = -2;
    for (pedge_path::iterator plink_It = vlink->link_info.plinks.begin();
	 plink_It != vlink->link_info.plinks.end();
	 ++plink_It) {
	score_link(*plink_It,ve,src_pnode,dst_pnode);
	numinterlinks++;
    }
#ifdef INTERSWITCH_LENGTH
    for (int i = 1; i <= numinterlinks; i++) {
	SADD(SCORE_INTERSWITCH_LINK);
    }
#endif
1037

1038 1039 1040 1041 1042 1043 1044
    for (pvertex_list::iterator switch_it = vlink->link_info.switches.begin();
	 switch_it != vlink->link_info.switches.end();++switch_it) {
      the_switch = get(pvertex_pmap,*switch_it);
      if (++the_switch->switch_used_links == 1) {
	SDEBUG(cerr << "  new switch" << endl);
	SADD(SCORE_SWITCH);
      }
1045 1046
      // We count the bandwidth into and out of the switch
      the_switch->nontrivial_bw_used += vlink->delay_info.bandwidth * 2;
1047 1048 1049
    }
    break;
  case tb_link_info::LINK_TRIVIAL:
1050
  #ifdef TRIVIAL_LINK_BW
Robert Ricci's avatar
Robert Ricci committed
1051 1052 1053 1054 1055 1056
    SDEBUG(cerr << "  trivial bandwidth used " <<
	    src_pnode->trivial_bw_used << " max is " <<
	    src_pnode->trivial_bw << " adding " << vlink->delay_info.bandwidth
	    << endl);
    if (src_pnode->trivial_bw) {
      int old_over_bw;
1057
      int old_bw = src_pnode->trivial_bw_used;
Robert Ricci's avatar
Robert Ricci committed
1058 1059 1060 1061 1062 1063
      if (src_pnode->trivial_bw_used > src_pnode->trivial_bw) {
	old_over_bw = src_pnode->trivial_bw_used - src_pnode->trivial_bw;
      } else {
	old_over_bw = 0;
      }

1064
      dst_pnode->trivial_bw_used += vlink->delay_info.bandwidth;
Robert Ricci's avatar
Robert Ricci committed
1065 1066 1067 1068 1069 1070 1071 1072 1073

      int new_over_bw;
      if (src_pnode->trivial_bw_used > src_pnode->trivial_bw) {
	new_over_bw = src_pnode->trivial_bw_used - src_pnode->trivial_bw;
      } else {
	new_over_bw = 0;
      }
	
      if (new_over_bw) {
1074 1075
	// Count how many multiples of the maximum bandwidth we're at
	int num_violations =
1076 1077 1078
	  (int)(floor((double)((src_pnode->trivial_bw_used -1)
			       / src_pnode->trivial_bw))
		- floor((double)((old_bw -1)/src_pnode->trivial_bw)));
1079 1080 1081
	violated += num_violations;
	vinfo.bandwidth += num_violations;

Robert Ricci's avatar
Robert Ricci committed
1082 1083 1084
	double added_bandwidth_percent = (new_over_bw - old_over_bw) * 1.0 /
	  src_pnode->trivial_bw;
	SADD(SCORE_TRIVIAL_PENALTY * added_bandwidth_percent);
1085 1086 1087 1088
      }
    }
    break;
#endif
1089
  case tb_link_info::LINK_UNMAPPED:
1090
    cout << "*** Internal error: Should not be here either." << endl;
1091
    exit(EXIT_FATAL);
1092
    break;
1093
  }
1094 1095 1096

  // Handle vnodes that are not allowed to have a mix of trivial and
  // non-trivial links
1097
  if (vlink->link_info.type_used == tb_link_info::LINK_TRIVIAL) {
1098 1099 1100 1101 1102 1103
      src_vnode->trivial_links++;
      dst_vnode->trivial_links++;
      if (src_vnode->disallow_trivial_mix &&
	      (src_vnode->trivial_links == 1) &&
	      (src_vnode->nontrivial_links != 0)) {
	  // We just added the first trivial link
1104
	  SADD(SCORE_TRIVIAL_MIX);
1105 1106 1107 1108 1109 1110 1111
	  violated++;
	  vinfo.trivial_mix++;
      }
      if (dst_vnode->disallow_trivial_mix &&
	      (dst_vnode->trivial_links == 1) &&
	      (dst_vnode->nontrivial_links != 0)) {
	  // We just added the first trivial link
1112
	  SADD(SCORE_TRIVIAL_MIX);
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
	  violated++;
	  vinfo.trivial_mix++;
      }
  } else {
      src_vnode->nontrivial_links++;
      dst_vnode->nontrivial_links++;
      if (src_vnode->disallow_trivial_mix &&
	      (src_vnode->nontrivial_links == 1) &&
	      (src_vnode->trivial_links != 0)) {
	  // We just added the first trivial link
1123
	  SADD(SCORE_TRIVIAL_MIX);
1124 1125 1126 1127 1128 1129 1130
	  violated++;
	  vinfo.trivial_mix++;
      }
      if (dst_vnode->disallow_trivial_mix &&
	      (dst_vnode->nontrivial_links == 1) &&
	      (dst_vnode->trivial_links != 0)) {
	  // We just added the first trivial link
1131
	  SADD(SCORE_TRIVIAL_MIX);
1132 1133 1134 1135 1136
	  violated++;
	  vinfo.trivial_mix++;
      }
  }

1137 1138 1139 1140 1141 1142 1143 1144 1145
}

/*
 * int add_node(vvertex vv,pvertex pv,bool deterministic)
 * Add a mapping of vv to pv and adjust score appropriately.
 * Returns 1 in the case of an incompatible mapping.  If determinisitic
 * is true then it deterministically solves the link problem for best
 * score.  Note: deterministic takes considerably longer.
 */
1146
int add_node(vvertex vv,pvertex pv, bool deterministic, bool is_fixed, bool skip_links)
1147
{
1148
  // Get the vnode and pnode associated with the passed vertices
1149 1150
  tb_vnode *vnode = get(vvertex_pmap,vv);
  tb_pnode *pnode = get(pvertex_pmap,pv);
1151

1152 1153 1154 1155 1156 1157 1158
  assert(!vnode->assigned);

  SDEBUG(cerr << "SCORE: add_node(" << vnode->name << "," <<
	 pnode->name << ")" << endl);
#ifdef SCORE_DEBUG_LOTS
  cerr << *vnode;
  cerr << *pnode;
1159
#endif
1160
  SDEBUG(cerr << "  vnode type = " << vnode->type << endl);
1161
  
1162
  /*
1163 1164 1165 1166
   * Handle types - first, check to see if the node is capable of taking on the
   * vnode's type. If it can with a static type, just do the bookkeeping for
   * that static type. Otherwise convert the node to the correct dynamic type,
   * failing if we can't for some reason (ie. it already has another type.
1167
   */
1168 1169
  tb_pnode::type_record *tr;
  tb_pnode::types_map::iterator mit = pnode->types.find(vnode->type);
1170

1171 1172 1173 1174 1175 1176
  if (mit == pnode->types.end()) {
    // This pnode can't take on the vnode's type - we normally shouldn't get
    // here, due to the way we pick pnodes
    return 1;
  }

1177 1178 1179
  /*
   * Handle types
   */
1180 1181 1182 1183 1184
  tr = mit->second;
  if (tr->is_static) {
    // XXX: Scoring???
    if (tr->current_load < tr->max_load) {
    } else {
1185 1186 1187
      return 1;
    }
  } else {
1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
    // Figure out the pnode's type
    if (!pnode->typed) {
      // If this pnode has no type yet, give it one
      SDEBUG(cerr << "  virgin pnode" << endl);
      SDEBUG(cerr << "    vtype = " << vnode->type << endl);

      // Remove check assuming at higher level?
      // Remove higher level checks?
      if (!pnode->set_current_type(vnode->type)) {
	// didn't find a type
	SDEBUG(cerr << "  no matching type" << endl);
	//cerr << "Failed due to bad type!" << endl;
1200 1201
	return 1;
      }
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214

      SDEBUG(cerr << "  matching type found (" << pnode->current_type <<
	  ", max = " << pnode->current_type_record->max_load << ")" << endl);
      } else {
	// The pnode already has a type, let's just make sure it's compatible
	SDEBUG(cerr << "  pnode already has type" << endl);
	if (pnode->current_type != vnode->type) {
	  SDEBUG(cerr << "  incompatible types" << endl);
	  return 1;
	} else {
	  SDEBUG(cerr << "  compatible types" << endl);
	}
      }
1215 1216
    }

1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248
  /*
   * Handle subnodes
   */
  if (vnode->subnode_of) {
      // First handle our parent
      if (vnode->subnode_of->assigned) {
	  tb_pnode *assignment = get(pvertex_pmap,
		  vnode->subnode_of->assignment);
	  if ((!pnode->subnode_of) ||
		 (pnode->subnode_of != assignment)) {
	      SADD(SCORE_SUBNODE);
	      violated++;
	      vinfo.subnodes++;
	  }
      }
  }
  if (!vnode->subnodes.empty()) {
      // Then any children we might have
      tb_vnode::subnode_list::iterator sit;
      for (sit = vnode->subnodes.begin(); sit != vnode->subnodes.end(); sit++) {
	  if ((*sit)->assigned) {
	      tb_pnode *assignment = get(pvertex_pmap,(*sit)->assignment);
	  if ((!assignment->subnode_of) ||
		 (assignment->subnode_of != pnode)) {
		  SADD(SCORE_SUBNODE);
		  violated++;
		  vinfo.subnodes++;
	      }
	  }
      }
  }

1249 1250 1251 1252 1253 1254 1255
#ifdef PENALIZE_UNUSED_INTERFACES
  pnode->used_interfaces = 0;
#endif
 
#ifdef SMART_UNMAP
  pnode->assigned_nodes.insert(vnode);
#endif
1256 1257 1258 1259 1260 1261 1262

  /*
   * Record the node's assignment. Need to do this now so that 'loopback' links
   * work below.
   */
  vnode->assignment = pv;
  vnode->assigned = true;
1263

1264 1265 1266
  /* Links */
  if (!skip_links) {
      resolve_links(vv,pv,vnode,pnode,deterministic);
1267
  }
1268
  
1269 1270 1271
  int old_load = tr->current_load;
  int old_total_load = pnode->total_load;

1272
  // finish setting up pnode
1273 1274
  tr->current_load += vnode->typecount;
  pnode->total_load += vnode->typecount;
1275 1276

#ifdef PENALIZE_UNUSED_INTERFACES
1277
  // XXX
1278 1279
  assert(pnode->used_interfaces <= pnode->total_interfaces);
  SADD((pnode->total_interfaces - pnode->used_interfaces) * SCORE_UNUSED_INTERFACE);
1280
#endif
1281

1282 1283 1284
  if (tr->current_load > tr->max_load) {
    SDEBUG(cerr << "  load too high - penalty (" <<
	pnode->current_type_record->current_load << ")" << endl);
1285 1286 1287 1288 1289
    for (int i = MAX(old_load,tr->max_load); i < tr->current_load; i++) {
      SADD(SCORE_PNODE_PENALTY);
      vinfo.pnode_load++;
      violated++;
    }
1290
  } else {
1291
    SDEBUG(cerr << "  load is fine" << endl);
1292
  }
1293
  if (old_total_load == 0) {
1294
    SDEBUG(cerr << "  new pnode" << endl);
1295
    SADD(SCORE_PNODE);
1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306
    // ptypes
    tb_pnode::types_list::iterator lit = pnode->type_list.begin();
    while (lit != pnode->type_list.end()) {
	int new_violations = (*lit)->ptype->add_users((*lit)->max_load);
	if (new_violations) {
	    SADD(SCORE_MAX_TYPES * new_violations);
	    violated += new_violations;
	    vinfo.max_types += new_violations;
	}
	lit++;
    }
1307
  }
1308 1309 1310 1311
#ifdef LOAD_BALANCE
  SSUB(SCORE_PNODE * (powf(1 + ((pnode->current_load-1) * 1.0)/pnode->max_load,2)));
  SADD(SCORE_PNODE * (powf(1 + ((pnode->current_load) * 1.0)/pnode->max_load,2)));
#endif
1312 1313 1314 1315 1316 1317

  // node no longer unassigned
  SSUB(SCORE_UNASSIGNED);
  vinfo.unassigned--;
  violated--;

1318
  // features/desires
1319 1320 1321 1322 1323 1324
  score_and_violations sv = score_fds(vnode,pnode,true);
  SADD(sv.first);
  if (!is_fixed) {
      violated += sv.second;
      vinfo.desires += sv.second;
  }
1325 1326

  // pclass
1327 1328
  if ((!disable_pclasses) && (!tr->is_static) && pnode->my_class &&
	  (pnode->my_class->used_members == 0)) {
1329
    SDEBUG(cerr << "  new pclass" << endl);
1330
    SADD(SCORE_PCLASS);
1331
  }
1332 1333

  // vclass
1334 1335 1336
  if (vnode->vclass != NULL) {
    double score_delta = vnode->vclass->assign_node(vnode->type);
    SDEBUG(cerr << "  vclass assign " << score_delta << endl);
1337 1338 1339 1340 1341 1342 1343
    SADD(score_delta*SCORE_VCLASS);
    if (score_delta >= 1) {
      violated++;
      vinfo.vclass++;
    }
  }

1344 1345
  SDEBUG(cerr << "  assignment=" << vnode->assignment << endl);
  SDEBUG(cerr << "  new score=" << score << " new violated=" << violated << endl);
1346

1347 1348 1349 1350
  if (!tr->is_static) {
    if (pnode->my_class) {
      pclass_set(vnode,pnode);
    }
1351
  }
1352
  
1353 1354 1355
  return 0;
}

1356
bool find_best_link(pvertex pv,pvertex switch_pv,tb_vlink *vlink,
1357
			 pedge &out_edge)
1358
{
1359 1360
  pvertex dest_pv;
  double best_distance = 1000.0;
1361
  int best_users = 1000;
1362
  double best_avail_bandwidth = 0;
1363 1364 1365 1366
  pedge best_pedge;
  bool found_best=false;
  poedge_iterator pedge_it,end_pedge_it;
  tie(pedge_it,end_pedge_it) = out_edges(pv,PG);
1367 1368 1369

  tb_pnode *pnode = get(pvertex_pmap,pv);

1370 1371 1372 1373 1374 1375
  for (;pedge_it!=end_pedge_it;++pedge_it) {
    dest_pv = target(*pedge_it,PG);
    if (dest_pv == pv)
      dest_pv = source(*pedge_it,PG);
    if (dest_pv == switch_pv) {
      tb_plink *plink = get(pedge_pmap,*pedge_it);
1376

1377 1378 1379 1380 1381
      // Skip any links whose type is wrong (ie. doesn't match the vlink)
      if (plink->types.find(vlink->type) == plink->types.end()) {
	  continue;
      }

1382 1383
      // Get delay characteristics - NOTE: Currently does not actually do
      // anything
1384 1385 1386 1387 1388
      tb_delay_info physical_delay;
      physical_delay.bandwidth = plink->delay_info.bandwidth - plink->bw_used;
      physical_delay.delay = plink->delay_info.delay;
      physical_delay.loss = plink->delay_info.loss;
      double distance = vlink->delay_info.distance(physical_delay);
1389 1390

      double available_bandwidth =  plink->delay_info.bandwidth - plink->bw_used;
1391

Robert Ricci's avatar
Robert Ricci committed
1392 1393
      // For sticking emulated links in emulated links we care about the
      // distance, and whether or not we've gone over bandwidth
1394
      int users;
1395 1396 1397 1398
      users = plink->nonemulated;
      if (! vlink->emulated) {
	users += plink->emulated;
      }
Robert Ricci's avatar
Robert Ricci committed
1399

1400 1401 1402 1403
      if (distance == -1) {
	// -1 == infinity
	distance = DBL_MAX;
      }
1404
      if (vlink->emulated) {
1405 1406
	// For emulated links, we need to do bin packing. Right now, we use the
	// first-fit approximation; there may be a better one
1407 1408 1409 1410 1411
	
	// Skip any links that already have non-emulated links assigned to them
	if (plink->nonemulated > 0) {
	    continue;
	}
1412
	if (available_bandwidth >= vlink->delay_info.bandwidth) {
1413 1414
	  best_pedge = *pedge_it;
	  found_best = true;
1415
	  break;
1416 1417 1418
	}
      } else {
	// For non-emulated links, we're just looking for links with few (0,
1419 1420 1421
	// actually) users, and enough bandwidth
	if ((users < best_users) &&
		(plink->delay_info.bandwidth >= vlink->delay_info.bandwidth)) {
1422 1423 1424 1425 1426
	  best_pedge = *pedge_it;
	  best_distance = distance;
	  found_best = true;
	  best_users = plink->emulated+plink->nonemulated;
	}
1427 1428 1429
      }
    }
  }
1430

1431 1432 1433 1434 1435 1436 1437 1438 1439
  if ((!vlink->emulated) && found_best && (best_users > 0)) {
      return false;
  }
  if (found_best) {
    out_edge = best_pedge;
    return true;
  } else {
    return false;
  }
1440 1441
}

1442 1443 1444 1445
// this uses the shortest paths calculated over the switch graph to
// find a path between src and dst.  It passes out list<edge>, a list
// of the edges used. (assumed to be empty to begin with).
// Returns 0 if no path exists and 1 otherwise.
1446 1447 1448
int find_interswitch_path(pvertex src_pv,pvertex dest_pv,
			  int bandwidth,pedge_path &out_path,
			  pvertex_list &out_switches)
1449
{
1450 1451 1452 1453 1454 1455
  // We know the shortest path from src to node already.  It's stored
  // in switch_preds[src] and is a node_array<edge>.  Let P be this
  // array.  We can trace our shortest path by starting at the end and
  // following the pred edges back until we reach src.  We need to be
  // careful though because the switch_preds deals with elements of SG
  // and we have elements of PG.
1456 1457 1458 1459 1460 1461 1462

  svertex src_sv = get(pvertex_pmap,src_pv)->sgraph_switch;
  svertex dest_sv = get(pvertex_pmap,dest_pv)->sgraph_switch;

  sedge current_se;
  svertex current_sv = dest_sv;
  switch_pred_map &preds = *switch_preds[src_sv];
1463
  
1464
  if (preds[dest_sv] == dest_sv) {
1465
    // unreachable
1466 1467
    return 0;
  }
1468 1469 1470 1471 1472
  while (current_sv != src_sv) {
    out_switches.push_front(get(svertex_pmap,current_sv)->mate);
    current_se = edge(current_sv,preds[current_sv],SG).first;
    out_path.push_back(get(sedge_pmap,current_se)->mate);
    current_sv = preds[current_sv];
1473
  }
1474
  out_switches.push_front(get(svertex_pmap,current_sv)->mate);
1475
  return 1;
1476 1477 1478
}

// this does scoring for over users and over bandwidth on edges.
1479
void score_link(pedge pe,vedge ve,tb_pnode *src_pnode, tb_pnode *dst_pnode)
1480
{
1481 1482
  tb_plink *plink = get(pedge_pmap,pe);
  tb_vlink *vlink = get(vedge_pmap,ve);
1483

1484 1485
  SDEBUG(cerr << "  score_link(" << pe << ") - " << plink->name << " / " <<
	 vlink->name << endl);
1486

1487 1488 1489 1490 1491
#ifdef SCORE_DEBUG_LOTS
  cerr << *plink;
  cerr << *vlink;
#endif
  
1492
  if (plink->is_type == tb_plink::PLINK_NORMAL) {
1493
    // need to account for three things here, the possiblity of a new plink
1494
    // the user of a new emulated link, and a possible violation.
1495 1496
    if (vlink->emulated) {
      plink->emulated++;
1497 1498
      SADD(SCORE_EMULATED_LINK);
    }
1499 1500
    else plink->nonemulated++;
    if (plink->nonemulated+plink->emulated == 1) {
1501
      // new link
1502
      SDEBUG(cerr << "    first user" << endl);
1503
      SADD(SCORE_DIRECT_LINK);
1504
    } else {
1505 1506
      // check for violation, basically if this is the first of it's
      // type to be added.
1507 1508 1509 1510 1511 1512 1513 1514
      if (((! vlink->emulated) && (plink->nonemulated == 1)) ||
	  ((vlink->emulated) && (plink->emulated == 1))) {
	SDEBUG(cerr << "    link user - penalty" << endl);
	SADD(SCORE_DIRECT_LINK_PENALTY);
	vinfo.link_users++;
	violated++;
      }
      if ((! vlink->emulated) && (plink->nonemulated > 1)) {
1515 1516 1517
	  SADD(SCORE_DIRECT_LINK_PENALTY);
	  vinfo.link_users++;
	  violated++;
1518
      }
1519
    }
1520
  }
1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555

#ifdef FIX_PLINK_ENDPOINTS
  if (plink->fixends) {
      // Add this to the list of endpoints used by this plink
      nodepair p;
      if (src_pnode->name < dst_pnode->name) {
	  p.first = src_pnode->name;
	  p.second = dst_pnode->name;
      } else {
	  p.first = dst_pnode->name;
	  p.second = src_pnode->name;
      }
      if (plink->vedge_counts.find(p) == plink->vedge_counts.end()) {
	  plink->vedge_counts[p] = 1;
      } else {
	  plink->vedge_counts[p]++;
      }
      // Figure out if we need to add a violation
      if (p == plink->current_endpoints) {
	  plink->current_count++;
      } else {
	  // Nope, we just passed the old leader
	  if (plink->vedge_counts[p] > plink->current_count) {
	      plink->current_endpoints = p;
	      plink->current_count++;
	  } else {
	      // Yup, it's a new violation
	      SADD(5 * SCORE_DIRECT_LINK_PENALTY);
	      vinfo.incorrect_endpoints++;
	      violated++;
	  }
      }
  }
#endif

1556
  if (plink->is_type != tb_plink::PLINK_LAN) {
1557

1558
    // Handle being over bandwidth
1559 1560 1561 1562 1563 1564 1565 1566 1567 1568
    // NOTE - this will have to change substantially when we can handle
    // asymmetric bandwidths on links.
    int old_over_bw;
    int old_bw = plink->bw_used;
    if (plink->bw_used > plink->delay_info.bandwidth) {
      old_over_bw = plink->bw_used - plink->delay_info.bandwidth;
    } else {
      old_over_bw = 0;
    }

1569
    plink->bw_used += vlink->delay_info.bandwidth;
1570 1571 1572 1573 1574 1575

    int new_over_bw;
    if (plink->bw_used > plink->delay_info.bandwidth) {
      new_over_bw = plink->bw_used - plink->delay_info.bandwidth;
    } else {
      new_over_bw = 0;
1576
    }
1577 1578 1579 1580
    
    if (new_over_bw) {
      // Count how many multiples of the maximum bandwidth we're at
      int num_violations =
1581 1582
	(int)(floor((double)((plink->bw_used -1) / plink->delay_info.bandwidth))
	      - floor((double)((old_bw -1)/plink->delay_info.bandwidth)));
1583 1584 1585 1586 1587 1588
      violated += num_violations;
      vinfo.bandwidth += num_violations;

      double added_bandwidth_percent = (new_over_bw - old_over_bw) * 1.0 /
	plink->delay_info.bandwidth;
      SADD(SCORE_OUTSIDE_DELAY * added_bandwidth_percent);
1589
    }
1590

1591 1592
#ifdef PENALIZE_BANDWIDTH
    SADD(plink->penalty * (vlink->delay_info.bandwidth * 1.0) / (plink->delay_info.bandwidth));
1593
#endif
1594

1595 1596 1597
  }
}

1598 1599 1600 1601
/*
 * Remove the score incurred by a link. This should be the inverse of
 * score_link()
 */
1602
void unscore_link(pedge pe,vedge ve, tb_pnode *src_pnode, tb_pnode *dst_pnode)
1603
{
1604
  // Get the vlink from the passed in edges
1605
  tb_vlink *vlink = get(vedge_pmap,ve);
1606

1607 1608 1609
  // This is not in the slightest bit graceful! This function was not designed
  // for use with trivial links (which have no plink,) but I would like to call
  // it for symmetry
1610
  if (vlink->link_info.type_used == tb_link_info::LINK_TRIVIAL) {
1611 1612 1613 1614 1615 1616
    goto UNSCORE_TRIVIAL;
  }

  tb_plink *plink;
  plink = get(pedge_pmap,pe);

1617 1618 1619 1620 1621 1622
  SDEBUG(cerr << "  unscore_link(" << pe << ") - " << plink->name << " / " <<
	 vlink->name << endl);

#ifdef SCORE_DEBUG_LOTS
  cerr << *plink;
  cerr << *vlink;
1623 1624
#endif

1625
  if (plink->is_type == tb_plink::PLINK_NORMAL) {
1626 1627
    if (vlink->emulated) {
      plink->emulated--;
1628 1629
      SSUB(SCORE_EMULATED_LINK);
    } else {
1630 1631 1632 1633 1634 1635 1636
      plink->nonemulated--;
      if (plink->nonemulated >= 1) {
	  //cerr << "Freeing overused link" << endl;
	  SSUB(SCORE_DIRECT_LINK_PENALTY);
	  vinfo.link_users--;
	  violated--;
      }
1637
    }
1638
    if (plink->nonemulated+plink->emulated == 0) {