Search is not available for this dataset
repo
stringlengths
2
152
file
stringlengths
15
239
code
stringlengths
0
58.4M
file_length
int64
0
58.4M
avg_line_length
float64
0
1.81M
max_line_length
int64
0
12.7M
extension_type
stringclasses
364 values
null
ParMETIS-main/libparmetis/ametis.c
/* * Copyright 1997, Regents of the University of Minnesota * * ametis.c * * This is the entry point of parallel difussive repartitioning routines * * Started 10/19/96 * George * * $Id: ametis.c 10757 2011-09-15 22:07:47Z karypis $ * */ #include <parmetislib.h> /*********************************************************************************** * This function is the entry point of the parallel multilevel local diffusion * algorithm. It uses parallel undirected diffusion followed by adaptive k-way * refinement. This function utilizes local coarsening. ************************************************************************************/ int ParMETIS_V3_AdaptiveRepart(idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *vwgt, idx_t *vsize, idx_t *adjwgt, idx_t *wgtflag, idx_t *numflag, idx_t *ncon, idx_t *nparts, real_t *tpwgts, real_t *ubvec, real_t *ipc2redist, idx_t *options, idx_t *edgecut, idx_t *part, MPI_Comm *comm) { idx_t i, npes, mype, status; ctrl_t *ctrl=NULL; graph_t *graph=NULL; size_t curmem; /* Check the input parameters and return if an error */ status = CheckInputsAdaptiveRepart(vtxdist, xadj, adjncy, vwgt, vsize, adjwgt, wgtflag, numflag, ncon, nparts, tpwgts, ubvec, ipc2redist, options, edgecut, part, comm); if (GlobalSEMinComm(*comm, status) == 0) return METIS_ERROR; status = METIS_OK; gk_malloc_init(); curmem = gk_GetCurMemoryUsed(); /* Setup the ctrl */ ctrl = SetupCtrl(PARMETIS_OP_AMETIS, options, *ncon, *nparts, tpwgts, ubvec, *comm); npes = ctrl->npes; mype = ctrl->mype; /* Take care the nparts == 1 case */ if (*nparts == 1) { iset(vtxdist[mype+1]-vtxdist[mype], (*numflag == 0 ? 0 : 1), part); *edgecut = 0; goto DONE; } /* Setup the graph */ if (*numflag > 0) ChangeNumbering(vtxdist, xadj, adjncy, part, npes, mype, 1); graph = SetupGraph(ctrl, *ncon, vtxdist, xadj, vwgt, vsize, adjncy, adjwgt, *wgtflag); if (ctrl->ps_relation == PARMETIS_PSR_COUPLED) iset(graph->nvtxs, mype, graph->home); else { /* Downgrade the partition numbers if part[] has more partitions that nparts */ for (i=0; i<graph->nvtxs; i++) part[i] = (part[i] >= ctrl->nparts ? 0 : part[i]); icopy(graph->nvtxs, part, graph->home); } /* Allocate the workspace */ AllocateWSpace(ctrl, 10*graph->nvtxs); /* Partition and Remap */ STARTTIMER(ctrl, ctrl->TotalTmr); ctrl->ipc_factor = *ipc2redist; ctrl->CoarsenTo = gk_min(graph->gnvtxs+1, (gk_max(npes, *nparts) > 256 ? 20 : 50)*(*ncon)*gk_max(npes, *nparts)); Adaptive_Partition(ctrl, graph); ParallelReMapGraph(ctrl, graph); icopy(graph->nvtxs, graph->where, part); *edgecut = graph->mincut; STOPTIMER(ctrl, ctrl->TotalTmr); /* Take care of output */ IFSET(ctrl->dbglvl, DBG_TIME, PrintTimingInfo(ctrl)); IFSET(ctrl->dbglvl, DBG_TIME, gkMPI_Barrier(ctrl->gcomm)); IFSET(ctrl->dbglvl, DBG_INFO, PrintPostPartInfo(ctrl, graph, 1)); FreeInitialGraphAndRemap(graph); if (*numflag > 0) ChangeNumbering(vtxdist, xadj, adjncy, part, npes, mype, 0); DONE: FreeCtrl(&ctrl); if (gk_GetCurMemoryUsed() - curmem > 0) { printf("ParMETIS appears to have a memory leak of %zdbytes. Report this.\n", (ssize_t)(gk_GetCurMemoryUsed() - curmem)); } gk_malloc_cleanup(0); return (int)status; } /*************************************************************************/ /*! This function is the driver for the adaptive refinement mode of ParMETIS */ /*************************************************************************/ void Adaptive_Partition(ctrl_t *ctrl, graph_t *graph) { idx_t i; idx_t tewgt, tvsize; real_t gtewgt, gtvsize; real_t ubavg, lbavg, *lbvec; WCOREPUSH; lbvec = rwspacemalloc(ctrl, graph->ncon); /************************************/ /* Set up important data structures */ /************************************/ CommSetup(ctrl, graph); ubavg = ravg(graph->ncon, ctrl->ubvec); tewgt = isum(graph->nedges, graph->adjwgt, 1); tvsize = isum(graph->nvtxs, graph->vsize, 1); gtewgt = (real_t) GlobalSESum(ctrl, tewgt) + 1.0/graph->gnvtxs; /* The +1/graph->gnvtxs were added to remove any FPE */ gtvsize = (real_t) GlobalSESum(ctrl, tvsize) + 1.0/graph->gnvtxs; ctrl->redist_factor = ctrl->redist_base * ((gtewgt/gtvsize)/ ctrl->edge_size_ratio); IFSET(ctrl->dbglvl, DBG_PROGRESS, rprintf(ctrl, "[%6"PRIDX" %8"PRIDX" %5"PRIDX" %5"PRIDX"][%"PRIDX"]\n", graph->gnvtxs, GlobalSESum(ctrl, graph->nedges), GlobalSEMin(ctrl, graph->nvtxs), GlobalSEMax(ctrl, graph->nvtxs), ctrl->CoarsenTo)); if (graph->gnvtxs < 1.3*ctrl->CoarsenTo || (graph->finer != NULL && graph->gnvtxs > graph->finer->gnvtxs*COARSEN_FRACTION)) { AllocateRefinementWorkSpace(ctrl, 2*graph->nedges); /***********************************************/ /* Balance the partition on the coarsest graph */ /***********************************************/ graph->where = ismalloc(graph->nvtxs+graph->nrecv, -1, "graph->where"); icopy(graph->nvtxs, graph->home, graph->where); ComputeParallelBalance(ctrl, graph, graph->where, lbvec); lbavg = ravg(graph->ncon, lbvec); if (lbavg > ubavg + 0.035 && ctrl->partType != REFINE_PARTITION) Balance_Partition(ctrl, graph); if (ctrl->dbglvl&DBG_PROGRESS) { ComputePartitionParams(ctrl, graph); ComputeParallelBalance(ctrl, graph, graph->where, lbvec); rprintf(ctrl, "nvtxs: %10"PRIDX", cut: %8"PRIDX", balance: ", graph->gnvtxs, graph->mincut); for (i=0; i<graph->ncon; i++) rprintf(ctrl, "%.3"PRREAL" ", lbvec[i]); rprintf(ctrl, "\n"); /* free memory allocated by ComputePartitionParams */ gk_free((void **)&graph->ckrinfo, &graph->lnpwgts, &graph->gnpwgts, LTERM); } /* check if no coarsening took place */ if (graph->finer == NULL) { ComputePartitionParams(ctrl, graph); KWayBalance(ctrl, graph, graph->ncon); KWayAdaptiveRefine(ctrl, graph, NGR_PASSES); } } else { /*******************************/ /* Coarsen it and partition it */ /*******************************/ switch (ctrl->ps_relation) { case PARMETIS_PSR_COUPLED: Match_Local(ctrl, graph); break; case PARMETIS_PSR_UNCOUPLED: default: Match_Global(ctrl, graph); break; } graph_WriteToDisk(ctrl, graph); Adaptive_Partition(ctrl, graph->coarser); graph_ReadFromDisk(ctrl, graph); /********************************/ /* project partition and refine */ /********************************/ ProjectPartition(ctrl, graph); ComputePartitionParams(ctrl, graph); if (graph->ncon > 1 && graph->level < 4) { ComputeParallelBalance(ctrl, graph, graph->where, lbvec); lbavg = ravg(graph->ncon, lbvec); if (lbavg > ubavg + 0.025) { KWayBalance(ctrl, graph, graph->ncon); } } KWayAdaptiveRefine(ctrl, graph, NGR_PASSES); if (ctrl->dbglvl&DBG_PROGRESS) { ComputeParallelBalance(ctrl, graph, graph->where, lbvec); rprintf(ctrl, "nvtxs: %10"PRIDX", cut: %8"PRIDX", balance: ", graph->gnvtxs, graph->mincut); for (i=0; i<graph->ncon; i++) rprintf(ctrl, "%.3"PRREAL" ", lbvec[i]); rprintf(ctrl, "\n"); } } WCOREPOP; }
7,412
30.411017
141
c
null
ParMETIS-main/libparmetis/csrmatch.c
/* * Copyright 1997, Regents of the University of Minnesota * * csrmatch.c * * This file contains the code that computes matchings * * Started 7/23/97 * George * * $Id: csrmatch.c 10057 2011-06-02 13:44:44Z karypis $ * */ #include <parmetislib.h> /************************************************************************* * This function finds a matching using the HEM heuristic **************************************************************************/ void CSR_Match_SHEM(matrix_t *matrix, idx_t *match, idx_t *mlist, idx_t *skip, idx_t ncon) { idx_t h, i, ii, j; idx_t nrows, edge, maxidx, count; real_t maxwgt; idx_t *rowptr, *colind; real_t *transfer; rkv_t *links; nrows = matrix->nrows; rowptr = matrix->rowptr; colind = matrix->colind; transfer = matrix->transfer; iset(nrows, UNMATCHED, match); links = rkvmalloc(nrows, "links"); for (i=0; i<nrows; i++) { links[i].key = 0.0; links[i].val = i; for (j=rowptr[i]; j<rowptr[i+1]; j++) { for (h=0; h<ncon; h++) { if (links[i].key < fabs(transfer[j*ncon+h])) links[i].key = fabs(transfer[j*ncon+h]); } } } rkvsortd(nrows, links); for (count=0, ii=0; ii<nrows; ii++) { i = links[ii].val; if (match[i] == UNMATCHED) { maxidx = i; maxwgt = 0.0; /* Find a heavy-edge matching */ for (j=rowptr[i]; j<rowptr[i+1]; j++) { edge = colind[j]; if (match[edge] == UNMATCHED && edge != i && skip[j] == 0) { for (h=0; h<ncon; h++) if (maxwgt < fabs(transfer[j*ncon+h])) break; if (h != ncon) { maxwgt = fabs(transfer[j*ncon+h]); maxidx = edge; } } } if (maxidx != i) { match[i] = maxidx; match[maxidx] = i; mlist[count++] = gk_max(i, maxidx); mlist[count++] = gk_min(i, maxidx); } } } gk_free((void **)&links, LTERM); }
1,976
21.988372
75
c
null
ParMETIS-main/libparmetis/wave.c
/* * Copyright 1997, Regents of the University of Minnesota * * wave.c * * This file contains code for directed diffusion at the coarsest graph * * Started 5/19/97, Kirk, George * * $Id: wave.c 13946 2013-03-30 15:51:45Z karypis $ * */ #include <parmetislib.h> /************************************************************************* * This function performs a k-way directed diffusion **************************************************************************/ real_t WavefrontDiffusion(ctrl_t *ctrl, graph_t *graph, idx_t *home) { idx_t ii, i, j, k, l, nvtxs, nedges, nparts; idx_t from, to, edge, done, nswaps, noswaps, totalv, wsize; idx_t npasses, first, second, third, mind, maxd; idx_t *xadj, *adjncy, *adjwgt, *where, *perm; idx_t *rowptr, *colind, *ed, *psize; real_t *transfer, *tmpvec; real_t balance = -1.0, *load, *solution, *workspace; real_t *nvwgt, *npwgts, flowFactor, cost, ubfactor; matrix_t matrix; ikv_t *cand; idx_t ndirty, nclean, dptr, clean; nvtxs = graph->nvtxs; nedges = graph->nedges; xadj = graph->xadj; nvwgt = graph->nvwgt; adjncy = graph->adjncy; adjwgt = graph->adjwgt; where = graph->where; nparts = ctrl->nparts; ubfactor = ctrl->ubvec[0]; matrix.nrows = nparts; flowFactor = 0.35; flowFactor = (ctrl->mype == 2) ? 0.50 : flowFactor; flowFactor = (ctrl->mype == 3) ? 0.75 : flowFactor; flowFactor = (ctrl->mype == 4) ? 1.00 : flowFactor; /* allocate memory */ solution = rmalloc(6*nparts+2*nedges, "WavefrontDiffusion: solution"); tmpvec = solution + nparts; /* nparts */ npwgts = solution + 2*nparts; /* nparts */ load = solution + 3*nparts; /* nparts */ matrix.values = solution + 4*nparts; /* nparts+nedges */ transfer = matrix.transfer = solution + 5*nparts + nedges /* nparts+nedges */; perm = imalloc(2*nvtxs+3*nparts+nedges+1, "WavefrontDiffusion: perm"); ed = perm + nvtxs; /* nvtxs */ psize = perm + 2*nvtxs; /* nparts */ rowptr = matrix.rowptr = perm + 2*nvtxs + nparts; /* nparts+1 */ colind = matrix.colind = perm + 2*nvtxs + 2*nparts + 1; /* nparts+nedges */ /*GKTODO - Potential problem with this malloc */ wsize = gk_max(sizeof(real_t)*6*nparts, sizeof(idx_t)*(nvtxs+2*nparts+1)); workspace = (real_t *)gk_malloc(wsize, "WavefrontDiffusion: workspace"); cand = ikvmalloc(nvtxs, "WavefrontDiffusion: cand"); /* Populate empty subdomains */ iset(nparts, 0, psize); for (i=0; i<nvtxs; i++) psize[where[i]]++; for (l=0; l<nparts; l++) { if (psize[l] == 0) break; } if (l < nparts) { /* there is at least an empty subdomain */ FastRandomPermute(nvtxs, perm, 1); for (mind=0; mind<nparts; mind++) { if (psize[mind] > 0) continue; maxd = iargmax(nparts, psize, 1); if (psize[maxd] == 1) break; /* we cannot do anything if the heaviest subdomain contains one vertex! */ for (i=0; i<nvtxs; i++) { k = perm[i]; if (where[k] == maxd) { where[k] = mind; psize[mind]++; psize[maxd]--; break; } } } } /* compute the external degrees of the vertices */ iset(nvtxs, 0, ed); rset(nparts, 0.0, npwgts); for (i=0; i<nvtxs; i++) { npwgts[where[i]] += nvwgt[i]; for (j=xadj[i]; j<xadj[i+1]; j++) ed[i] += (where[i] != where[adjncy[j]] ? adjwgt[j] : 0); } ComputeLoad(graph, nparts, load, ctrl->tpwgts, 0); /* zero out the tmpvec array */ rset(nparts, 0.0, tmpvec); npasses = gk_min(nparts/2, NGD_PASSES); for (done=0, l=0; l<npasses; l++) { /* Set-up and solve the diffusion equation */ nswaps = 0; /* Solve flow equations */ SetUpConnectGraph(graph, &matrix, (idx_t *)workspace); /* check for disconnected subdomains */ for(i=0; i<matrix.nrows; i++) { if (matrix.rowptr[i]+1 == matrix.rowptr[i+1]) { cost = (real_t)(ctrl->mype); break; } } if (i == matrix.nrows) { /* if connected, proceed */ ConjGrad2(&matrix, load, solution, 0.001, workspace); ComputeTransferVector(1, &matrix, solution, transfer, 0); GetThreeMax(nparts, load, &first, &second, &third); if (l%3 == 0) { FastRandomPermute(nvtxs, perm, 1); } else { /*****************************/ /* move dirty vertices first */ /*****************************/ ndirty = 0; for (i=0; i<nvtxs; i++) { if (where[i] != home[i]) ndirty++; } dptr = 0; for (i=0; i<nvtxs; i++) { if (where[i] != home[i]) perm[dptr++] = i; else perm[ndirty++] = i; } PASSERT(ctrl, ndirty == nvtxs); ndirty = dptr; nclean = nvtxs-dptr; FastRandomPermute(ndirty, perm, 0); FastRandomPermute(nclean, perm+ndirty, 0); } if (ctrl->mype == 0) { for (j=nvtxs, k=0, ii=0; ii<nvtxs; ii++) { i = perm[ii]; if (ed[i] != 0) { cand[k].key = -ed[i]; cand[k++].val = i; } else { cand[--j].key = 0; cand[j].val = i; } } ikvsorti(k, cand); } for (ii=0; ii<nvtxs/3; ii++) { i = (ctrl->mype == 0) ? cand[ii].val : perm[ii]; from = where[i]; /* don't move out the last vertex in a subdomain */ if (psize[from] == 1) continue; clean = (from == home[i]) ? 1 : 0; /* only move from top three or dirty vertices */ if (from != first && from != second && from != third && clean) continue; /* Scatter the sparse transfer row into the dense tmpvec row */ for (j=rowptr[from]+1; j<rowptr[from+1]; j++) tmpvec[colind[j]] = transfer[j]; for (j=xadj[i]; j<xadj[i+1]; j++) { to = where[adjncy[j]]; if (from != to) { if (tmpvec[to] > (flowFactor * nvwgt[i])) { tmpvec[to] -= nvwgt[i]; INC_DEC(psize[to], psize[from], 1); INC_DEC(npwgts[to], npwgts[from], nvwgt[i]); INC_DEC(load[to], load[from], nvwgt[i]); where[i] = to; nswaps++; /* Update external degrees */ ed[i] = 0; for (k=xadj[i]; k<xadj[i+1]; k++) { edge = adjncy[k]; ed[i] += (to != where[edge] ? adjwgt[k] : 0); if (where[edge] == from) ed[edge] += adjwgt[k]; if (where[edge] == to) ed[edge] -= adjwgt[k]; } break; } } } /* Gather the dense tmpvec row into the sparse transfer row */ for (j=rowptr[from]+1; j<rowptr[from+1]; j++) { transfer[j] = tmpvec[colind[j]]; tmpvec[colind[j]] = 0.0; } } } if (l % 2 == 1) { balance = rmax(nparts, npwgts, 1)*nparts; if (balance < ubfactor + 0.035) done = 1; if (GlobalSESum(ctrl, done) > 0) break; noswaps = (nswaps > 0 ? 0 : 1); if (GlobalSESum(ctrl, noswaps) > ctrl->npes/2) break; } } graph->mincut = ComputeSerialEdgeCut(graph); totalv = Mc_ComputeSerialTotalV(graph, home); cost = ctrl->ipc_factor * (real_t)graph->mincut + ctrl->redist_factor * (real_t)totalv; CleanUpAndExit: gk_free((void **)&solution, (void **)&perm, (void **)&workspace, (void **)&cand, LTERM); return cost; }
7,851
29.316602
98
c
null
ParMETIS-main/libparmetis/redomylink.c
/* * Copyright 1997, Regents of the University of Minnesota * * redomylink.c * * This file contains code that implements the edge-based FM refinement * * Started 7/23/97 * George * * $Id: redomylink.c 10542 2011-07-11 16:56:22Z karypis $ */ #include <parmetislib.h> #define PE 0 /************************************************************************* * This function performs an edge-based FM refinement **************************************************************************/ void RedoMyLink(ctrl_t *ctrl, graph_t *graph, idx_t *home, idx_t me, idx_t you, real_t *flows, real_t *sr_cost, real_t *sr_lbavg) { idx_t h, i, r; idx_t nvtxs, nedges, ncon; idx_t pass, lastseed, totalv; idx_t *xadj, *adjncy, *adjwgt, *where, *vsize; idx_t *costwhere, *lbwhere, *selectwhere; idx_t *ed, *id, *bndptr, *bndind, *perm; real_t *nvwgt, mycost; real_t lbavg, *lbvec; real_t best_lbavg, other_lbavg = -1.0, bestcost, othercost = -1.0; real_t *npwgts, *pwgts, *tpwgts; real_t ipc_factor, redist_factor, ftmp; idx_t mype; gkMPI_Comm_rank(MPI_COMM_WORLD, &mype); WCOREPUSH; nvtxs = graph->nvtxs; nedges = graph->nedges; ncon = graph->ncon; xadj = graph->xadj; nvwgt = graph->nvwgt; vsize = graph->vsize; adjncy = graph->adjncy; adjwgt = graph->adjwgt; where = graph->where; ipc_factor = ctrl->ipc_factor; redist_factor = ctrl->redist_factor; /* set up data structures */ id = graph->sendind = iwspacemalloc(ctrl, nvtxs); ed = graph->recvind = iwspacemalloc(ctrl, nvtxs); bndptr = graph->sendptr = iwspacemalloc(ctrl, nvtxs); bndind = graph->recvptr = iwspacemalloc(ctrl, nvtxs); costwhere = iwspacemalloc(ctrl, nvtxs); lbwhere = iwspacemalloc(ctrl, nvtxs); perm = iwspacemalloc(ctrl, nvtxs); lbvec = rwspacemalloc(ctrl, ncon); pwgts = rset(2*ncon, 0.0, rwspacemalloc(ctrl, 2*ncon)); npwgts = rwspacemalloc(ctrl, 2*ncon); tpwgts = rwspacemalloc(ctrl, 2*ncon); graph->gnpwgts = npwgts; RandomPermute(nvtxs, perm, 1); icopy(nvtxs, where, costwhere); icopy(nvtxs, where, lbwhere); /* compute target pwgts */ for (h=0; h<ncon; h++) { tpwgts[h] = -1.0*flows[h]; tpwgts[ncon+h] = flows[h]; } for (i=0; i<nvtxs; i++) { if (where[i] == me) { for (h=0; h<ncon; h++) { tpwgts[h] += nvwgt[i*ncon+h]; pwgts[h] += nvwgt[i*ncon+h]; } } else { ASSERT(where[i] == you); for (h=0; h<ncon; h++) { tpwgts[ncon+h] += nvwgt[i*ncon+h]; pwgts[ncon+h] += nvwgt[i*ncon+h]; } } } /* we don't want any weights to be less than zero */ for (h=0; h<ncon; h++) { if (tpwgts[h] < 0.0) { tpwgts[ncon+h] += tpwgts[h]; tpwgts[h] = 0.0; } if (tpwgts[ncon+h] < 0.0) { tpwgts[h] += tpwgts[ncon+h]; tpwgts[ncon+h] = 0.0; } } /* now compute new bisection */ bestcost = (real_t)isum(nedges, adjwgt, 1)*ipc_factor + (real_t)isum(nvtxs, vsize, 1)*redist_factor; best_lbavg = 10.0; lastseed = 0; for (pass=N_MOC_REDO_PASSES; pass>0; pass--) { iset(nvtxs, 1, where); /* find seed vertices */ r = perm[lastseed] % nvtxs; lastseed = (lastseed+1) % nvtxs; where[r] = 0; Mc_Serial_Compute2WayPartitionParams(ctrl, graph); Mc_Serial_Init2WayBalance(ctrl, graph, tpwgts); Mc_Serial_FM_2WayRefine(ctrl, graph, tpwgts, 4); Mc_Serial_Balance2Way(ctrl, graph, tpwgts, 1.02); Mc_Serial_FM_2WayRefine(ctrl, graph, tpwgts, 4); for (i=0; i<nvtxs; i++) where[i] = (where[i] == 0) ? me : you; for (i=0; i<ncon; i++) { ftmp = (pwgts[i]+pwgts[ncon+i])/2.0; if (ftmp != 0.0) lbvec[i] = fabs(npwgts[i]-tpwgts[i])/ftmp; else lbvec[i] = 0.0; } lbavg = ravg(ncon, lbvec); totalv = 0; for (i=0; i<nvtxs; i++) if (where[i] != home[i]) totalv += vsize[i]; mycost = (real_t)(graph->mincut)*ipc_factor + (real_t)totalv*redist_factor; if (bestcost >= mycost) { bestcost = mycost; other_lbavg = lbavg; icopy(nvtxs, where, costwhere); } if (best_lbavg >= lbavg) { best_lbavg = lbavg; othercost = mycost; icopy(nvtxs, where, lbwhere); } } if (other_lbavg <= .05) { selectwhere = costwhere; *sr_cost = bestcost; *sr_lbavg = other_lbavg; } else { selectwhere = lbwhere; *sr_cost = othercost; *sr_lbavg = best_lbavg; } icopy(nvtxs, selectwhere, where); WCOREPOP; }
4,522
24.410112
79
c
null
ParMETIS-main/libparmetis/frename.c
/* * frename.c * * This file contains some renaming routines to deal with different * Fortran compilers. * * Started 6/1/98 * George * * $Id: frename.c 13945 2013-03-30 14:38:24Z karypis $ * */ #include <parmetislib.h> /************************************************************************* * Renaming macro (at least to save some typing :)) **************************************************************************/ #define FRENAME(name0, name1, name2, name3, name4, dargs, cargs) \ int name1 dargs {MPI_Comm comm = MPI_Comm_f2c(*icomm); return name0 cargs; }\ int name2 dargs {MPI_Comm comm = MPI_Comm_f2c(*icomm); return name0 cargs; }\ int name3 dargs {MPI_Comm comm = MPI_Comm_f2c(*icomm); return name0 cargs; }\ int name4 dargs {MPI_Comm comm = MPI_Comm_f2c(*icomm); return name0 cargs; } /************************************************************************* * Renames for Release 3.0 API **************************************************************************/ FRENAME(ParMETIS_V3_AdaptiveRepart, PARMETIS_V3_ADAPTIVEREPART, parmetis_v3_adaptiverepart, parmetis_v3_adaptiverepart_, parmetis_v3_adaptiverepart__, (idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *vwgt, idx_t *vsize, idx_t *adjwgt, idx_t *wgtflag, idx_t *numflag, idx_t *ncon, idx_t *nparts, real_t *tpwgts, real_t *ubvec, real_t *ipc2redist, idx_t *options, idx_t *edgecut, idx_t *part, MPI_Fint *icomm), (vtxdist, xadj, adjncy, vwgt, vsize, adjwgt, wgtflag, numflag, ncon, nparts, tpwgts, ubvec, ipc2redist, options, edgecut, part, &comm) ) FRENAME(ParMETIS_V3_PartGeomKway, PARMETIS_V3_PARTGEOMKWAY, parmetis_v3_partgeomkway, parmetis_v3_partgeomkway_, parmetis_v3_partgeomkway__, (idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *vwgt, idx_t *adjwgt, idx_t *wgtflag, idx_t *numflag, idx_t *ndims, real_t *xyz, idx_t *ncon, idx_t *nparts, real_t *tpwgts, real_t *ubvec, idx_t *options, idx_t *edgecut, idx_t *part, MPI_Fint *icomm), (vtxdist, xadj, adjncy, vwgt, adjwgt, wgtflag, numflag, ndims, xyz, ncon, nparts, tpwgts, ubvec, options, edgecut, part, &comm) ) FRENAME(ParMETIS_V3_PartGeom, PARMETIS_V3_PARTGEOM, parmetis_v3_partgeom, parmetis_v3_partgeom_, parmetis_v3_partgeom__, (idx_t *vtxdist, idx_t *ndims, real_t *xyz, idx_t *part, MPI_Fint *icomm), (vtxdist, ndims, xyz, part, &comm) ) FRENAME(ParMETIS_V3_PartKway, PARMETIS_V3_PARTKWAY, parmetis_v3_partkway, parmetis_v3_partkway_, parmetis_v3_partkway__, (idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *vwgt, idx_t *adjwgt, idx_t *wgtflag, idx_t *numflag, idx_t *ncon, idx_t *nparts, real_t *tpwgts, real_t *ubvec, idx_t *options, idx_t *edgecut, idx_t *part, MPI_Fint *icomm), (vtxdist, xadj, adjncy, vwgt, adjwgt, wgtflag, numflag, ncon, nparts, tpwgts, ubvec, options, edgecut, part, &comm) ) FRENAME(ParMETIS_V3_Mesh2Dual, PARMETIS_V3_MESH2DUAL, parmetis_v3_mesh2dual, parmetis_v3_mesh2dual_, parmetis_v3_mesh2dual__, (idx_t *elmdist, idx_t *eptr, idx_t *eind, idx_t *numflag, idx_t *ncommonnodes, idx_t **xadj, idx_t **adjncy, MPI_Fint *icomm), (elmdist, eptr, eind, numflag, ncommonnodes, xadj, adjncy, &comm) ) FRENAME(ParMETIS_V3_PartMeshKway, PARMETIS_V3_PARTMESHKWAY, parmetis_v3_partmeshkway, parmetis_v3_partmeshkway_, parmetis_v3_partmeshkway__, (idx_t *elmdist, idx_t *eptr, idx_t *eind, idx_t *elmwgt, idx_t *wgtflag, idx_t *numflag, idx_t *ncon, idx_t *ncommonnodes, idx_t *nparts, real_t *tpwgts, real_t *ubvec, idx_t *options, idx_t *edgecut, idx_t *part, MPI_Fint *icomm), (elmdist, eptr, eind, elmwgt, wgtflag, numflag, ncon, ncommonnodes, nparts, tpwgts, ubvec, options, edgecut, part, &comm) ) FRENAME(ParMETIS_V3_NodeND, PARMETIS_V3_NODEND, parmetis_v3_nodend, parmetis_v3_nodend_, parmetis_v3_nodend__, (idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *numflag, idx_t *options, idx_t *order, idx_t *sizes, MPI_Fint *icomm), (vtxdist, xadj, adjncy, numflag, options, order, sizes, &comm) ) FRENAME(ParMETIS_V3_RefineKway, PARMETIS_V3_REFINEKWAY, parmetis_v3_refinekway, parmetis_v3_refinekway_, parmetis_v3_refinekway__, (idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *vwgt, idx_t *adjwgt, idx_t *wgtflag, idx_t *numflag, idx_t *ncon, idx_t *nparts, real_t *tpwgts, real_t *ubvec, idx_t *options, idx_t *edgecut, idx_t *part, MPI_Fint *icomm), (vtxdist, xadj, adjncy, vwgt, adjwgt, wgtflag, numflag, ncon, nparts, tpwgts, ubvec, options, edgecut, part, &comm) )
4,633
36.674797
93
c
null
ParMETIS-main/libparmetis/selectq.c
/* * Copyright 1997, Regents of the University of Minnesota * * selectq.c * * This file contains the driving routines for multilevel k-way refinement * * Started 7/28/97 * George * * $Id: selectq.c 10542 2011-07-11 16:56:22Z karypis $ */ #include <parmetislib.h> /*************************************************************************/ /*! This stuff is hardcoded for up to four constraints */ /*************************************************************************/ void Mc_DynamicSelectQueue(ctrl_t *ctrl, idx_t nqueues, idx_t ncon, idx_t subdomain1, idx_t subdomain2, idx_t *currentq, real_t *flows, idx_t *from, idx_t *qnum, idx_t minval, real_t avgvwgt, real_t maxdiff) { idx_t i, j; idx_t hash, index = -1, current; idx_t *cand, *rank, *dont_cares; idx_t nperms, perm[24][5]; real_t sign = 0.0; rkv_t *array; idx_t mype; gkMPI_Comm_rank(MPI_COMM_WORLD, &mype); WCOREPUSH; *qnum = -1; /* allocate memory */ cand = iwspacemalloc(ctrl, ncon); rank = iwspacemalloc(ctrl, ncon); dont_cares = iwspacemalloc(ctrl, ncon); array = rkvwspacemalloc(ctrl, ncon); if (*from == -1) { for (i=0; i<ncon; i++) { array[i].key = fabs(flows[i]); array[i].val = i; } /* GKTODO - Need to check the correct direction of the sort */ rkvsorti(ncon, array); /* GKTODO - The following assert was disabled as it was failing. Need to check if it is a valid assert */ /*ASSERT(array[ncon-1].key - array[0].key <= maxdiff) */ if (flows[array[ncon-1].val] > avgvwgt*MOC_GD_GRANULARITY_FACTOR) { *from = subdomain1; sign = 1.0; index = 0; } if (flows[array[ncon-1].val] < -1.0*avgvwgt*MOC_GD_GRANULARITY_FACTOR) { *from = subdomain2; sign = -1.0; index = nqueues; } if (*from == -1) goto DONE; } else { ASSERT(*from == subdomain1 || *from == subdomain2); if (*from == subdomain1) { sign = 1.0; index = 0; } else { sign = -1.0; index = nqueues; } } for (i=0; i<ncon; i++) { array[i].key = flows[i] * sign; array[i].val = i; } /* GKTODO Need to check the direction of those sorts */ rkvsorti(ncon, array); iset(ncon, 1, dont_cares); for (current=0, i=0; i<ncon-1; i++) { if (array[i+1].key - array[i].key < maxdiff * MC_FLOW_BALANCE_THRESHOLD && dont_cares[current] < ncon-1) { dont_cares[current]++; dont_cares[i+1] = 0; } else current = i+1; } switch (ncon) { /***********************/ case 2: nperms = 1; perm[0][0] = 0; perm[0][1] = 1; break; /***********************/ case 3: /* if the first and second flows are close */ if (dont_cares[0] == 2 && dont_cares[1] == 0 && dont_cares[2] == 1) { nperms = 4; perm[0][0] = 0; perm[0][1] = 1; perm[0][2] = 2; perm[1][0] = 1; perm[1][1] = 0; perm[1][2] = 2; perm[2][0] = 0; perm[2][1] = 2; perm[2][2] = 1; perm[3][0] = 1; perm[3][1] = 2; perm[3][2] = 0; break; } /* if the second and third flows are close */ if (dont_cares[0] == 1 && dont_cares[1] == 2 && dont_cares[2] == 0) { nperms = 4; perm[0][0] = 0; perm[0][1] = 1; perm[0][2] = 2; perm[1][0] = 0; perm[1][1] = 2; perm[1][2] = 1; perm[2][0] = 1; perm[2][1] = 0; perm[2][2] = 2; perm[3][0] = 2; perm[3][1] = 0; perm[3][2] = 1; break; } /* all or none of the flows are close */ nperms = 3; perm[0][0] = 0; perm[0][1] = 1; perm[0][2] = 2; perm[1][0] = 1; perm[1][1] = 0; perm[1][2] = 2; perm[2][0] = 0; perm[2][1] = 2; perm[2][2] = 1; break; /***********************/ case 4: if (dont_cares[0] == 2 && dont_cares[1] == 0 && dont_cares[2] == 1 && dont_cares[3] == 1) { nperms = 14; perm[0][0] = 0; perm[0][1] = 1; perm[0][2] = 2; perm[0][3] = 3; perm[1][0] = 1; perm[1][1] = 0; perm[1][2] = 2; perm[1][3] = 3; perm[2][0] = 0; perm[2][1] = 2; perm[2][2] = 1; perm[2][3] = 3; perm[3][0] = 1; perm[3][1] = 2; perm[3][2] = 0; perm[3][3] = 3; perm[4][0] = 0; perm[4][1] = 1; perm[4][2] = 3; perm[4][3] = 2; perm[5][0] = 1; perm[5][1] = 0; perm[5][2] = 3; perm[5][3] = 2; perm[6][0] = 0; perm[6][1] = 3; perm[6][2] = 1; perm[6][3] = 2; perm[7][0] = 1; perm[7][1] = 3; perm[7][2] = 0; perm[7][3] = 2; perm[8][0] = 0; perm[8][1] = 2; perm[8][2] = 3; perm[8][3] = 1; perm[9][0] = 1; perm[9][1] = 2; perm[9][2] = 3; perm[9][3] = 0; perm[10][0] = 2; perm[10][1] = 0; perm[10][2] = 1; perm[10][3] = 3; perm[11][0] = 2; perm[11][1] = 1; perm[11][2] = 0; perm[11][3] = 3; perm[12][0] = 0; perm[12][1] = 3; perm[12][2] = 2; perm[12][3] = 1; perm[13][0] = 1; perm[13][1] = 3; perm[13][2] = 2; perm[13][3] = 0; break; } if (dont_cares[0] == 1 && dont_cares[1] == 1 && dont_cares[2] == 2 && dont_cares[3] == 0) { nperms = 14; perm[0][0] = 0; perm[0][1] = 1; perm[0][2] = 2; perm[0][3] = 3; perm[1][0] = 0; perm[1][1] = 1; perm[1][2] = 3; perm[1][3] = 2; perm[2][0] = 0; perm[2][1] = 2; perm[2][2] = 1; perm[2][3] = 3; perm[3][0] = 0; perm[3][1] = 3; perm[3][2] = 1; perm[3][3] = 2; perm[4][0] = 1; perm[4][1] = 0; perm[4][2] = 2; perm[4][3] = 3; perm[5][0] = 1; perm[5][1] = 0; perm[5][2] = 3; perm[5][3] = 2; perm[6][0] = 1; perm[6][1] = 2; perm[6][2] = 0; perm[6][3] = 3; perm[7][0] = 1; perm[7][1] = 3; perm[7][2] = 0; perm[7][3] = 2; perm[8][0] = 2; perm[8][1] = 0; perm[8][2] = 1; perm[8][3] = 3; perm[9][0] = 3; perm[9][1] = 0; perm[9][2] = 1; perm[9][3] = 2; perm[10][0] = 0; perm[10][1] = 2; perm[10][2] = 3; perm[10][3] = 1; perm[11][0] = 0; perm[11][1] = 3; perm[11][2] = 2; perm[11][3] = 1; perm[12][0] = 2; perm[12][1] = 1; perm[12][2] = 0; perm[12][3] = 3; perm[13][0] = 3; perm[13][1] = 1; perm[13][2] = 0; perm[13][3] = 2; break; } if (dont_cares[0] == 2 && dont_cares[1] == 0 && dont_cares[2] == 2 && dont_cares[3] == 0) { nperms = 14; perm[0][0] = 0; perm[0][1] = 1; perm[0][2] = 2; perm[0][3] = 3; perm[1][0] = 1; perm[1][1] = 0; perm[1][2] = 2; perm[1][3] = 3; perm[2][0] = 0; perm[2][1] = 1; perm[2][2] = 3; perm[2][3] = 2; perm[3][0] = 1; perm[3][1] = 0; perm[3][2] = 3; perm[3][3] = 2; perm[4][0] = 0; perm[4][1] = 2; perm[4][2] = 1; perm[4][3] = 3; perm[5][0] = 1; perm[5][1] = 2; perm[5][2] = 0; perm[5][3] = 3; perm[6][0] = 0; perm[6][1] = 3; perm[6][2] = 1; perm[6][3] = 2; perm[7][0] = 1; perm[7][1] = 3; perm[7][2] = 0; perm[7][3] = 2; perm[8][0] = 2; perm[8][1] = 0; perm[8][2] = 1; perm[8][3] = 3; perm[9][0] = 0; perm[9][1] = 2; perm[9][2] = 3; perm[9][3] = 1; perm[10][0] = 2; perm[10][1] = 1; perm[10][2] = 0; perm[10][3] = 3; perm[11][0] = 0; perm[11][1] = 3; perm[11][2] = 2; perm[11][3] = 1; perm[12][0] = 3; perm[12][1] = 0; perm[12][2] = 1; perm[12][3] = 2; perm[13][0] = 1; perm[13][1] = 2; perm[13][2] = 3; perm[13][3] = 0; break; } if (dont_cares[0] == 3 && dont_cares[1] == 0 && dont_cares[2] == 0 && dont_cares[3] == 1) { nperms = 14; perm[0][0] = 0; perm[0][1] = 1; perm[0][2] = 2; perm[0][3] = 3; perm[1][0] = 0; perm[1][1] = 2; perm[1][2] = 1; perm[1][3] = 3; perm[2][0] = 1; perm[2][1] = 0; perm[2][2] = 2; perm[2][3] = 3; perm[3][0] = 2; perm[3][1] = 0; perm[3][2] = 1; perm[3][3] = 3; perm[4][0] = 1; perm[4][1] = 2; perm[4][2] = 0; perm[4][3] = 3; perm[5][0] = 2; perm[5][1] = 1; perm[5][2] = 0; perm[5][3] = 3; perm[6][0] = 0; perm[6][1] = 1; perm[6][2] = 3; perm[6][3] = 2; perm[7][0] = 1; perm[7][1] = 0; perm[7][2] = 3; perm[7][3] = 2; perm[8][0] = 0; perm[8][1] = 2; perm[8][2] = 3; perm[8][3] = 1; perm[9][0] = 2; perm[9][1] = 0; perm[9][2] = 3; perm[9][3] = 1; perm[10][0] = 1; perm[10][1] = 2; perm[10][2] = 3; perm[10][3] = 0; perm[11][0] = 2; perm[11][1] = 1; perm[11][2] = 3; perm[11][3] = 0; perm[12][0] = 0; perm[12][1] = 3; perm[12][2] = 1; perm[12][3] = 2; perm[13][0] = 0; perm[13][1] = 3; perm[13][2] = 2; perm[13][3] = 1; break; } if (dont_cares[0] == 1 && dont_cares[1] == 3 && dont_cares[2] == 0 && dont_cares[3] == 0) { nperms = 14; perm[0][0] = 0; perm[0][1] = 1; perm[0][2] = 2; perm[0][3] = 3; perm[1][0] = 0; perm[1][1] = 2; perm[1][2] = 1; perm[1][3] = 3; perm[2][0] = 0; perm[2][1] = 1; perm[2][2] = 3; perm[2][3] = 2; perm[3][0] = 0; perm[3][1] = 2; perm[3][2] = 3; perm[3][3] = 1; perm[4][0] = 0; perm[4][1] = 3; perm[4][2] = 1; perm[4][3] = 2; perm[5][0] = 0; perm[5][1] = 3; perm[5][2] = 2; perm[5][3] = 1; perm[6][0] = 1; perm[6][1] = 0; perm[6][2] = 2; perm[6][3] = 3; perm[7][0] = 1; perm[7][1] = 0; perm[7][2] = 3; perm[7][3] = 2; perm[8][0] = 2; perm[8][1] = 0; perm[8][2] = 1; perm[8][3] = 3; perm[9][0] = 2; perm[9][1] = 0; perm[9][2] = 3; perm[9][3] = 1; perm[10][0] = 3; perm[10][1] = 0; perm[10][2] = 1; perm[10][3] = 2; perm[11][0] = 3; perm[11][1] = 0; perm[11][2] = 2; perm[11][3] = 1; perm[12][0] = 1; perm[12][1] = 2; perm[12][2] = 0; perm[12][3] = 3; perm[13][0] = 2; perm[13][1] = 1; perm[13][2] = 0; perm[13][3] = 3; break; } nperms = 14; perm[0][0] = 0; perm[0][1] = 1; perm[0][2] = 2; perm[0][3] = 3; perm[1][0] = 1; perm[1][1] = 0; perm[1][2] = 2; perm[1][3] = 3; perm[2][0] = 0; perm[2][1] = 2; perm[2][2] = 1; perm[2][3] = 3; perm[3][0] = 0; perm[3][1] = 1; perm[3][2] = 3; perm[3][3] = 2; perm[4][0] = 1; perm[4][1] = 0; perm[4][2] = 3; perm[4][3] = 2; perm[5][0] = 2; perm[5][1] = 0; perm[5][2] = 1; perm[5][3] = 3; perm[6][0] = 0; perm[6][1] = 2; perm[6][2] = 3; perm[6][3] = 1; perm[7][0] = 1; perm[7][1] = 2; perm[7][2] = 0; perm[7][3] = 3; perm[8][0] = 0; perm[8][1] = 3; perm[8][2] = 1; perm[8][3] = 2; perm[9][0] = 2; perm[9][1] = 1; perm[9][2] = 0; perm[9][3] = 3; perm[10][0] = 0; perm[10][1] = 3; perm[10][2] = 2; perm[10][3] = 1; perm[11][0] = 2; perm[11][1] = 0; perm[11][2] = 3; perm[11][3] = 1; perm[12][0] = 3; perm[12][1] = 0; perm[12][2] = 1; perm[12][3] = 2; perm[13][0] = 1; perm[13][1] = 2; perm[13][2] = 3; perm[13][3] = 0; break; /***********************/ default: goto DONE; } for (i=0; i<nperms; i++) { for (j=0; j<ncon; j++) cand[j] = array[perm[i][j]].val; for (j=0; j<ncon; j++) rank[cand[j]] = j; hash = Mc_HashVRank(ncon, rank) - minval; if (currentq[hash+index] > 0) { *qnum = hash; goto DONE; } } DONE: WCOREPOP; } /*************************************************************************/ /*! This function sorts the nvwgts of a vertex and returns a hashed value */ /*************************************************************************/ idx_t Mc_HashVwgts(ctrl_t *ctrl, idx_t ncon, real_t *nvwgt) { idx_t i; idx_t multiplier, retval; idx_t *rank; rkv_t *array; WCOREPUSH; rank = iwspacemalloc(ctrl, ncon); array = rkvwspacemalloc(ctrl, ncon); for (i=0; i<ncon; i++) { array[i].key = nvwgt[i]; array[i].val = i; } rkvsorti(ncon, array); for (i=0; i<ncon; i++) rank[array[i].val] = i; multiplier = 1; retval = 0; for (i=0; i<ncon; i++) { multiplier *= (i+1); retval += rank[ncon-i-1] * multiplier; } WCOREPOP; return retval; } /*************************************************************************/ /*! This function sorts the vwgts of a vertex and returns a hashed value */ /*************************************************************************/ idx_t Mc_HashVRank(idx_t ncon, idx_t *vwgt) { idx_t i, multiplier, retval; multiplier = 1; retval = 0; for (i=0; i<ncon; i++) { multiplier *= (i+1); retval += vwgt[ncon-1-i] * multiplier; } return retval; }
13,136
35.491667
110
c
null
ParMETIS-main/libparmetis/debug.c
/* * Copyright 1997, Regents of the University of Minnesota * * debug.c * * This file contains various functions that are used to display debuging * information * * Started 10/20/96 * George * * $Id: debug.c 10391 2011-06-23 19:00:08Z karypis $ * */ #include <parmetislib.h> /************************************************************************* * This function prints a vector stored in each processor **************************************************************************/ void PrintVector(ctrl_t *ctrl, idx_t n, idx_t first, idx_t *vec, char *title) { idx_t i, penum; for (penum=0; penum<ctrl->npes; penum++) { if (ctrl->mype == penum) { if (ctrl->mype == 0) fprintf(stdout, "%s\n", title); fprintf(stdout, "\t%3"PRIDX". ", ctrl->mype); for (i=0; i<n; i++) fprintf(stdout, "[%"PRIDX" %"PRIDX"] ", first+i, vec[i]); fprintf(stdout, "\n"); fflush(stdout); } gkMPI_Barrier(ctrl->comm); } } /************************************************************************* * This function prints a vector stored in each processor **************************************************************************/ void PrintVector2(ctrl_t *ctrl, idx_t n, idx_t first, idx_t *vec, char *title) { idx_t i, penum; for (penum=0; penum<ctrl->npes; penum++) { if (ctrl->mype == penum) { if (ctrl->mype == 0) printf("%s\n", title); printf("\t%3"PRIDX". ", ctrl->mype); for (i=0; i<n; i++) printf("[%"PRIDX" %"PRIDX".%"PRIDX"] ", first+i, (idx_t)(vec[i]>=KEEP_BIT ? 1 : 0), (idx_t)(vec[i]>=KEEP_BIT ? vec[i]-KEEP_BIT : vec[i])); printf("\n"); fflush(stdout); } gkMPI_Barrier(ctrl->comm); } } /************************************************************************* * This function prints a vector stored in each processor **************************************************************************/ void PrintPairs(ctrl_t *ctrl, idx_t n, ikv_t *pairs, char *title) { idx_t i, penum; for (penum=0; penum<ctrl->npes; penum++) { if (ctrl->mype == penum) { if (ctrl->mype == 0) printf("%s\n", title); printf("\t%3"PRIDX". ", ctrl->mype); for (i=0; i<n; i++) printf("[%"PRIDX" %"PRIDX", %"PRIDX"] ", i, pairs[i].key, pairs[i].val); printf("\n"); fflush(stdout); } gkMPI_Barrier(ctrl->comm); } } /************************************************************************* * This function prints the local portion of the graph stored at each * processor **************************************************************************/ void PrintGraph(ctrl_t *ctrl, graph_t *graph) { idx_t i, j, penum; idx_t firstvtx; gkMPI_Barrier(ctrl->comm); firstvtx = graph->vtxdist[ctrl->mype]; for (penum=0; penum<ctrl->npes; penum++) { if (ctrl->mype == penum) { printf("\t%"PRIDX"", penum); for (i=0; i<graph->nvtxs; i++) { if (i==0) printf("\t%2"PRIDX" %2"PRIDX"\t", firstvtx+i, graph->vwgt[i]); else printf("\t\t%2"PRIDX" %2"PRIDX"\t", firstvtx+i, graph->vwgt[i]); for (j=graph->xadj[i]; j<graph->xadj[i+1]; j++) printf("[%"PRIDX" %"PRIDX"] ", graph->adjncy[j], graph->adjwgt[j]); printf("\n"); } fflush(stdout); } gkMPI_Barrier(ctrl->comm); } } /************************************************************************* * This function prints the local portion of the graph stored at each * processor along with degree information during refinement **************************************************************************/ void PrintGraph2(ctrl_t *ctrl, graph_t *graph) { idx_t i, j, penum; idx_t firstvtx; gkMPI_Barrier(ctrl->comm); firstvtx = graph->vtxdist[ctrl->mype]; for (penum=0; penum<ctrl->npes; penum++) { if (ctrl->mype == penum) { printf("\t%"PRIDX"", penum); for (i=0; i<graph->nvtxs; i++) { if (i==0) printf("\t%2"PRIDX" %2"PRIDX" [%"PRIDX" %"PRIDX" %"PRIDX"]\t", firstvtx+i, graph->vwgt[i], graph->where[i], graph->ckrinfo[i].id, graph->ckrinfo[i].ed); else printf("\t\t%2"PRIDX" %2"PRIDX" [%"PRIDX" %"PRIDX" %"PRIDX"]\t", firstvtx+i, graph->vwgt[i], graph->where[i], graph->ckrinfo[i].id, graph->ckrinfo[i].ed); for (j=graph->xadj[i]; j<graph->xadj[i+1]; j++) printf("[%"PRIDX" %"PRIDX"] ", graph->adjncy[j], graph->adjwgt[j]); printf("\n"); } fflush(stdout); } gkMPI_Barrier(ctrl->comm); } } /************************************************************************* * This function prints the information computed during setup **************************************************************************/ void PrintSetUpInfo(ctrl_t *ctrl, graph_t *graph) { idx_t i, j, penum; gkMPI_Barrier(ctrl->comm); for (penum=0; penum<ctrl->npes; penum++) { if (ctrl->mype == penum) { printf("PE: %"PRIDX", nnbrs: %"PRIDX"\n", ctrl->mype, graph->nnbrs); printf("\tSending...\n"); for (i=0; i<graph->nnbrs; i++) { printf("\t\tTo: %"PRIDX": ", graph->peind[i]); for (j=graph->sendptr[i]; j<graph->sendptr[i+1]; j++) printf("%"PRIDX" ", graph->sendind[j]); printf("\n"); } printf("\tReceiving...\n"); for (i=0; i<graph->nnbrs; i++) { printf("\t\tFrom: %"PRIDX": ", graph->peind[i]); for (j=graph->recvptr[i]; j<graph->recvptr[i+1]; j++) printf("%"PRIDX" ", graph->recvind[j]); printf("\n"); } printf("\n"); } gkMPI_Barrier(ctrl->comm); } } /************************************************************************* * This function prints information about the graphs that were sent/received **************************************************************************/ void PrintTransferedGraphs(ctrl_t *ctrl, idx_t nnbrs, idx_t *peind, idx_t *slens, idx_t *rlens, idx_t *sgraph, idx_t *rgraph) { idx_t i, ii, jj, ll, penum; gkMPI_Barrier(ctrl->comm); for (penum=0; penum<ctrl->npes; penum++) { if (ctrl->mype == penum) { printf("PE: %"PRIDX", nnbrs: %"PRIDX"", ctrl->mype, nnbrs); for (ll=i=0; i<nnbrs; i++) { if (slens[i+1]-slens[i] > 0) { printf("\n\tTo %"PRIDX"\t", peind[i]); for (ii=slens[i]; ii<slens[i+1]; ii++) { printf("%"PRIDX" %"PRIDX" %"PRIDX", ", sgraph[ll], sgraph[ll+1], sgraph[ll+2]); for (jj=0; jj<sgraph[ll+1]; jj++) printf("[%"PRIDX" %"PRIDX"] ", sgraph[ll+3+2*jj], sgraph[ll+3+2*jj+1]); printf("\n\t\t"); ll += 3+2*sgraph[ll+1]; } } } for (ll=i=0; i<nnbrs; i++) { if (rlens[i+1]-rlens[i] > 0) { printf("\n\tFrom %"PRIDX"\t", peind[i]); for (ii=rlens[i]; ii<rlens[i+1]; ii++) { printf("%"PRIDX" %"PRIDX" %"PRIDX", ", rgraph[ll], rgraph[ll+1], rgraph[ll+2]); for (jj=0; jj<rgraph[ll+1]; jj++) printf("[%"PRIDX" %"PRIDX"] ", rgraph[ll+3+2*jj], rgraph[ll+3+2*jj+1]); printf("\n\t\t"); ll += 3+2*rgraph[ll+1]; } } } printf("\n"); } gkMPI_Barrier(ctrl->comm); } } /************************************************************************* * This function writes a graph in the format used by serial METIS **************************************************************************/ void WriteMetisGraph(idx_t nvtxs, idx_t *xadj, idx_t *adjncy, idx_t *vwgt, idx_t *adjwgt) { idx_t i, j; FILE *fp; fp = fopen("test.graph", "w"); fprintf(fp, "%"PRIDX" %"PRIDX" 11", nvtxs, xadj[nvtxs]/2); for (i=0; i<nvtxs; i++) { fprintf(fp, "\n%"PRIDX" ", vwgt[i]); for (j=xadj[i]; j<xadj[i+1]; j++) fprintf(fp, " %"PRIDX" %"PRIDX"", adjncy[j]+1, adjwgt[j]); } fclose(fp); }
7,879
30.52
164
c
null
ParMETIS-main/libparmetis/struct.h
/* * Copyright 1997, Regents of the University of Minnesota * * struct.h * * This file contains data structures for ILU routines. * * Started 9/26/95 * George * * $Id: struct.h 10592 2011-07-16 21:17:53Z karypis $ */ /*************************************************************************/ /*! This data structure stores cut-based k-way refinement info about an * adjacent subdomain for a given vertex. */ /*************************************************************************/ typedef struct cnbr_t { idx_t pid; /*!< The partition ID */ idx_t ed; /*!< The sum of the weights of the adjacent edges that are incident on pid */ } cnbr_t; /************************************************************************* * The following data structure stores key-key-value triplets **************************************************************************/ typedef struct i2kv_t { idx_t key1, key2; idx_t val; } i2kv_t; /************************************************************************* * The following data structure holds information on degrees for k-way * partition **************************************************************************/ typedef struct ckrinfo_t { idx_t id; /*!< The internal degree of a vertex (sum of weights) */ idx_t ed; /*!< The total external degree of a vertex */ idx_t nnbrs; /*!< The number of neighboring subdomains */ idx_t inbr; /*!< The index in the cnbr_t array where the nnbrs list of neighbors is stored */ } ckrinfo_t; /************************************************************************* * The following data structure holds information on degrees for k-way * partition **************************************************************************/ struct nrinfodef { idx_t edegrees[2]; }; typedef struct nrinfodef NRInfoType; /************************************************************************* * The following data structure stores a sparse matrix in CSR format * The diagonal entry is in the first position of each row. **************************************************************************/ typedef struct matrix_t { idx_t nrows, nnzs; /* Number of rows and nonzeros in the matrix */ idx_t *rowptr; idx_t *colind; real_t *values; real_t *transfer; } matrix_t; /************************************************************************* * This data structure holds the input graph **************************************************************************/ typedef struct graph_t { idx_t gnvtxs, nvtxs, nedges, ncon, nobj; idx_t *xadj; /* Pointers to the locally stored vertices */ idx_t *vwgt; /* Vertex weights */ real_t *nvwgt; /* Vertex weights */ idx_t *vsize; /* Vertex size */ idx_t *adjncy; /* Array that stores the adjacency lists of nvtxs */ idx_t *adjwgt; /* Array that stores the weights of the adjacency lists */ idx_t *vtxdist; /* Distribution of vertices */ idx_t *home; /* The initial partition of the vertex */ /* used for not freeing application supplied arrays */ idx_t free_xadj; idx_t free_adjncy; idx_t free_vwgt; idx_t free_adjwgt; idx_t free_vsize; /* Coarsening structures */ idx_t *match; idx_t *cmap; /* Dropedges */ idx_t *unmatched; /* used to mark the coarse vertices that resulted from match[u]=u */ /* Used during initial partitioning */ idx_t *label; /* Communication/Setup parameters */ idx_t nnbrs; /*!< The number of neighboring processors */ idx_t nrecv; /*!< The total number of remote vertices that need to be received. nrecv == recvptr[nnbrs] */ idx_t nsend; /*!< The total number of local vertices that need to be sent. This corresponds to the communication volume of each pe, in the sense that if a vertex needs to be sent multiple times, it is accounted in nsend. nsend == sendptr[nnbrs] */ idx_t *peind; /*!< Array of size nnbrs storing the neighboring PEs */ idx_t *sendptr, *sendind; /*!< CSR format of the vertices that are sent to each of the neighboring processors */ idx_t *recvptr, *recvind; /*!< CSR format of the vertices that are received from each of the neighboring PEs. */ idx_t *imap; /*!< The inverse map of local to global indices */ idx_t *pexadj, *peadjncy, *peadjloc; /*!< CSR format of the PEs each vertex is adjancent to along with the location in the sendind of the non-local adjancent vertices */ idx_t nlocal; /*!< Number of interior vertices */ idx_t *lperm; /*!< lperm[0:nlocal] points to interior vertices, the rest are interface */ /* Communication parameters for projecting the partition. * These are computed during CreateCoarseGraph and used during projection * Note that during projection, the meaning of received and sent is reversed! */ idx_t *rlens, *slens; /* Arrays of size nnbrs of how many vertices you are sending and receiving */ ikv_t *rcand; /* Partition parameters */ idx_t *where; idx_t *lpwgts, *gpwgts; real_t *lnpwgts, *gnpwgts; ckrinfo_t *ckrinfo; /* Node refinement information */ idx_t nsep; /* The number of vertices in the separator */ NRInfoType *nrinfo; idx_t *sepind; /* The indices of the vertices in the separator */ /* Vertex/edge metadata information use by DistDGL */ size_t emdata_size, vmdata_size; idx_t *vmptr, *emptr; char *vmdata, *emdata; idx_t *vtype; /* Various fields for out-of-core processing */ int gID; int ondisk; idx_t lmincut, mincut; idx_t level; idx_t match_type; idx_t edgewgt_type; struct graph_t *coarser, *finer; } graph_t; /************************************************************************* * The following data type implements a timer **************************************************************************/ typedef double timer; /************************************************************************* * The following structure stores information used by parallel kmetis **************************************************************************/ typedef struct ctrl_t { pmoptype_et optype; /*!< The operation being performed */ idx_t mype, npes; /*!< Info about the parallel system */ idx_t ncon; /*!< The number of balancing constraints */ idx_t CoarsenTo; /*!< The # of vertices in the coarsest graph */ idx_t dbglvl; /*!< Controls the debuging output of the program */ idx_t nparts; /*!< The number of partitions */ idx_t foldf; /*!< What is the folding factor */ idx_t mtype; /*!< The matching type */ idx_t ipart; /*!< The initial partitioning type */ idx_t rtype; /*!< The refinement type */ idx_t p_nseps; /*!< The number of separators to compute at each parallel bisection */ idx_t s_nseps; /* The number of separators to compute at each serial bisection */ real_t ubfrac; /* The max/avg fraction for separator bisections */ idx_t seed; /* Random number seed */ idx_t sync; /* Random number seed */ real_t *tpwgts; /* Target subdomain weights */ real_t *invtvwgts; /* Per-constraint 1/total vertex weight */ real_t *ubvec; /* Per-constraint unbalance factor */ idx_t dropedges; idx_t twohop; idx_t fast; idx_t partType; idx_t ps_relation; real_t redist_factor; real_t redist_base; real_t ipc_factor; real_t edge_size_ratio; matrix_t *matrix; idx_t free_comm; /*!< Used to indicate if gcomm needs to be freed */ MPI_Comm gcomm; /*!< A copy of the application supplied communicator */ MPI_Comm comm; /*!< The current communicator */ idx_t ncommpes; /*!< The maximum number of processors that a processor may need to communicate with. This determines the size of the sreq/rreq/statuses arrays and is updated after every call to CommSetup() */ MPI_Request *sreq; /*!< MPI send requests */ MPI_Request *rreq; /*!< MPI receive requests */ MPI_Status *statuses; /*!< MPI status for p2p i-messages */ MPI_Status status; /* workspace variables */ gk_mcore_t *mcore; /* GKlib's mcore */ /* These are for use by the k-way refinement routines */ size_t nbrpoolsize; /*!< The number of cnbr_t entries that have been allocated */ size_t nbrpoolcpos; /*!< The position of the first free entry in the array */ size_t nbrpoolreallocs; /*!< The number of times the pool was resized */ cnbr_t *cnbrpool; /*!< The pool of cnbr_t entries to be used during refinement. The size and current position of the pool is controlled by nnbrs & cnbrs */ /* ondisk-related info */ idx_t ondisk; pid_t pid; /*!< The pid of the running process */ /* Various Timers */ timer TotalTmr, InitPartTmr, MatchTmr, ContractTmr, CoarsenTmr, RefTmr, SetupTmr, ProjectTmr, KWayInitTmr, KWayTmr, MoveTmr, RemapTmr, SerialTmr, AuxTmr1, AuxTmr2, AuxTmr3, AuxTmr4, AuxTmr5, AuxTmr6; } ctrl_t; /************************************************************************* * The following data structure stores a mesh. **************************************************************************/ typedef struct mesh_t { idx_t etype; idx_t gnelms, gnns; idx_t nelms, nns; idx_t ncon; idx_t esize, gminnode; idx_t *elmdist; idx_t *elements; idx_t *elmwgt; } mesh_t;
10,131
37.378788
101
h
null
ParMETIS-main/libparmetis/stat.c
/* * Copyright 1997, Regents of the University of Minnesota * * stat.c * * This file computes various statistics * * Started 7/25/97 * George * * $Id: stat.c 10578 2011-07-14 18:10:15Z karypis $ * */ #include <parmetislib.h> /************************************************************************* * This function computes the balance of the partitioning **************************************************************************/ void ComputeSerialBalance(ctrl_t *ctrl, graph_t *graph, idx_t *where, real_t *ubvec) { idx_t i, j, nvtxs, ncon, nparts; idx_t *pwgts, *tvwgts, *vwgt; real_t *tpwgts, maximb; nvtxs = graph->nvtxs; ncon = graph->ncon; vwgt = graph->vwgt; nparts = ctrl->nparts; tpwgts = ctrl->tpwgts; pwgts = ismalloc(nparts*ncon, 0, "pwgts"); tvwgts = ismalloc(ncon, 0, "tvwgts"); for (i=0; i<graph->nvtxs; i++) { for (j=0; j<ncon; j++) { pwgts[where[i]*ncon+j] += vwgt[i*ncon+j]; tvwgts[j] += vwgt[i*ncon+j]; } } /* The +1 in the following code is to deal with bad cases of tpwgts[i*ncon+j] == 0 */ for (j=0; j<ncon; j++) { maximb = 0.0; for (i=0; i<nparts; i++) maximb =gk_max(maximb, (1.0+(real_t)pwgts[i*ncon+j])/(1.0+(tpwgts[i*ncon+j]*(real_t)tvwgts[j]))); ubvec[j] = maximb; } gk_free((void **)&pwgts, (void **)&tvwgts, LTERM); } /************************************************************************* * This function computes the balance of the partitioning **************************************************************************/ void ComputeParallelBalance(ctrl_t *ctrl, graph_t *graph, idx_t *where, real_t *ubvec) { idx_t i, j, nvtxs, ncon, nparts; real_t *nvwgt, *lnpwgts, *gnpwgts, *lminvwgts, *gminvwgts; real_t *tpwgts, maximb; WCOREPUSH; ncon = graph->ncon; nvtxs = graph->nvtxs; nvwgt = graph->nvwgt; nparts = ctrl->nparts; tpwgts = ctrl->tpwgts; lminvwgts = rset(ncon, 1.0, rwspacemalloc(ctrl, ncon)); gminvwgts = rwspacemalloc(ctrl, ncon); lnpwgts = rset(nparts*ncon, 0.0, rwspacemalloc(ctrl, nparts*ncon)); gnpwgts = rwspacemalloc(ctrl, nparts*ncon); for (i=0; i<nvtxs; i++) { for (j=0; j<ncon; j++) { lnpwgts[where[i]*ncon+j] += nvwgt[i*ncon+j]; /* The following is to deal with tpwgts[] that are 0.0 for certain partitions/constraints */ lminvwgts[j] = (nvwgt[i*ncon+j] > 0.0 && lminvwgts[j] > nvwgt[i*ncon+j] ? nvwgt[i*ncon+j] : lminvwgts[j]); } } gkMPI_Allreduce((void *)(lnpwgts), (void *)(gnpwgts), nparts*ncon, REAL_T, MPI_SUM, ctrl->comm); gkMPI_Allreduce((void *)(lminvwgts), (void *)(gminvwgts), ncon, REAL_T, MPI_MIN, ctrl->comm); /* The +gminvwgts[j] in the following code is to deal with bad cases of tpwgts[i*ncon+j] == 0 */ for (j=0; j<ncon; j++) { maximb = 0.0; for (i=0; i<nparts; i++) maximb =gk_max(maximb, (gminvwgts[j]+gnpwgts[i*ncon+j])/(gminvwgts[j]+tpwgts[i*ncon+j])); ubvec[j] = maximb; } WCOREPOP; } /************************************************************************* * This function prints a matrix **************************************************************************/ void Mc_PrintThrottleMatrix(ctrl_t *ctrl, graph_t *graph, real_t *matrix) { idx_t i, j; for (i=0; i<ctrl->npes; i++) { if (i == ctrl->mype) { for (j=0; j<ctrl->npes; j++) printf("%.3"PRREAL" ", matrix[j]); printf("\n"); fflush(stdout); } gkMPI_Barrier(ctrl->comm); } if (ctrl->mype == 0) { printf("****************************\n"); fflush(stdout); } gkMPI_Barrier(ctrl->comm); return; } /***********************************************************************************/ /*! This function prints post-partitioning information */ /***********************************************************************************/ void PrintPostPartInfo(ctrl_t *ctrl, graph_t *graph, idx_t movestats) { idx_t i, j, ncon, nmoved, maxin, maxout, nparts; real_t maximb, *tpwgts; ncon = graph->ncon; nparts = ctrl->nparts; tpwgts = ctrl->tpwgts; rprintf(ctrl, "Final %3"PRIDX"-way Cut: %6"PRIDX" \tBalance: ", nparts, graph->mincut); for (j=0; j<ncon; j++) { for (maximb=0.0, i=0; i<nparts; i++) maximb = gk_max(maximb, graph->gnpwgts[i*ncon+j]/tpwgts[i*ncon+j]); rprintf(ctrl, "%.3"PRREAL" ", maximb); } if (movestats) { Mc_ComputeMoveStatistics(ctrl, graph, &nmoved, &maxin, &maxout); rprintf(ctrl, "\nNMoved: %"PRIDX" %"PRIDX" %"PRIDX" %"PRIDX"\n", nmoved, maxin, maxout, maxin+maxout); } else { rprintf(ctrl, "\n"); } } /************************************************************************* * This function computes movement statistics for adaptive refinement * schemes **************************************************************************/ void ComputeMoveStatistics(ctrl_t *ctrl, graph_t *graph, idx_t *nmoved, idx_t *maxin, idx_t *maxout) { idx_t i, j, nvtxs; idx_t *vwgt, *where; idx_t *lpvtxs, *gpvtxs; nvtxs = graph->nvtxs; vwgt = graph->vwgt; where = graph->where; lpvtxs = ismalloc(ctrl->nparts, 0, "ComputeMoveStatistics: lpvtxs"); gpvtxs = ismalloc(ctrl->nparts, 0, "ComputeMoveStatistics: gpvtxs"); for (j=i=0; i<nvtxs; i++) { lpvtxs[where[i]]++; if (where[i] != ctrl->mype) j++; } /* PrintVector(ctrl, ctrl->npes, 0, lpvtxs, "Lpvtxs: "); */ gkMPI_Allreduce((void *)lpvtxs, (void *)gpvtxs, ctrl->nparts, IDX_T, MPI_SUM, ctrl->comm); *nmoved = GlobalSESum(ctrl, j); *maxout = GlobalSEMax(ctrl, j); *maxin = GlobalSEMax(ctrl, gpvtxs[ctrl->mype]-(nvtxs-j)); gk_free((void **)&lpvtxs, (void **)&gpvtxs, LTERM); }
5,661
27.59596
112
c
null
ParMETIS-main/libparmetis/remap.c
/* * premap.c * * This file contains code that computes the assignment of processors to * partition numbers so that it will minimize the redistribution cost * * Started 4/16/98 * George * * $Id: remap.c 10361 2011-06-21 19:16:22Z karypis $ * */ #include <parmetislib.h> /************************************************************************* * This function remaps that graph so that it will minimize the * redistribution cost **************************************************************************/ void ParallelReMapGraph(ctrl_t *ctrl, graph_t *graph) { idx_t i, nvtxs, nparts; idx_t *where, *vsize, *map, *lpwgts; IFSET(ctrl->dbglvl, DBG_TIME, gkMPI_Barrier(ctrl->comm)); IFSET(ctrl->dbglvl, DBG_TIME, starttimer(ctrl->RemapTmr)); if (ctrl->npes != ctrl->nparts) { IFSET(ctrl->dbglvl, DBG_TIME, stoptimer(ctrl->RemapTmr)); return; } WCOREPUSH; nvtxs = graph->nvtxs; where = graph->where; vsize = graph->vsize; nparts = ctrl->nparts; map = iwspacemalloc(ctrl, nparts); lpwgts = iset(nparts, 0, iwspacemalloc(ctrl, nparts)); for (i=0; i<nvtxs; i++) lpwgts[where[i]] += (vsize == NULL) ? 1 : vsize[i]; ParallelTotalVReMap(ctrl, lpwgts, map, NREMAP_PASSES, graph->ncon); for (i=0; i<nvtxs; i++) where[i] = map[where[i]]; WCOREPOP; IFSET(ctrl->dbglvl, DBG_TIME, gkMPI_Barrier(ctrl->comm)); IFSET(ctrl->dbglvl, DBG_TIME, stoptimer(ctrl->RemapTmr)); } /************************************************************************* * This function computes the assignment using the the objective the * minimization of the total volume of data that needs to move **************************************************************************/ void ParallelTotalVReMap(ctrl_t *ctrl, idx_t *lpwgts, idx_t *map, idx_t npasses, idx_t ncon) { idx_t i, ii, j, k, nparts, mype; idx_t pass, maxipwgt, nmapped, oldwgt, newwgt, done; idx_t *rowmap, *mylpwgts; ikv_t *recv, send; idx_t nsaved, gnsaved; WCOREPUSH; mype = ctrl->mype; nparts = ctrl->nparts; rowmap = iset(nparts, -1, iwspacemalloc(ctrl, nparts)); mylpwgts = icopy(nparts, lpwgts, iwspacemalloc(ctrl, nparts)); recv = ikvwspacemalloc(ctrl, nparts); iset(nparts, -1, map); done = nmapped = 0; for (pass=0; pass<npasses; pass++) { maxipwgt = iargmax(nparts, mylpwgts, 1); if (mylpwgts[maxipwgt] > 0 && !done) { send.key = -mylpwgts[maxipwgt]; send.val = mype*nparts+maxipwgt; } else { send.key = 0; send.val = -1; } /* each processor sends its selection */ gkMPI_Allgather((void *)&send, 2, IDX_T, (void *)recv, 2, IDX_T, ctrl->comm); ikvsorti(nparts, recv); if (recv[0].key == 0) break; /* now make as many assignments as possible */ for (ii=0; ii<nparts; ii++) { i = recv[ii].val; if (i == -1) continue; j = i%nparts; k = i/nparts; if (map[j] == -1 && rowmap[k] == -1 && SimilarTpwgts(ctrl->tpwgts, ncon, j, k)) { map[j] = k; rowmap[k] = j; nmapped++; mylpwgts[j] = 0; if (mype == k) done = 1; } if (nmapped == nparts) break; } if (nmapped == nparts) break; } /* Map unmapped partitions */ if (nmapped < nparts) { for (i=j=0; j<nparts && nmapped<nparts; j++) { if (map[j] == -1) { for (; i<nparts; i++) { if (rowmap[i] == -1 && SimilarTpwgts(ctrl->tpwgts, ncon, i, j)) { map[j] = i; rowmap[i] = j; nmapped++; break; } } } } } /* check to see if remapping fails (due to dis-similar tpwgts) */ /* if remapping fails, revert to original mapping */ if (nmapped < nparts) { for (i=0; i<nparts; i++) map[i] = i; IFSET(ctrl->dbglvl, DBG_REMAP, rprintf(ctrl, "Savings from parallel remapping: %0\n")); } else { /* check for a savings */ oldwgt = lpwgts[mype]; newwgt = lpwgts[rowmap[mype]]; nsaved = newwgt - oldwgt; gnsaved = GlobalSESum(ctrl, nsaved); /* undo everything if we don't see a savings */ if (gnsaved <= 0) { for (i=0; i<nparts; i++) map[i] = i; } IFSET(ctrl->dbglvl, DBG_REMAP, rprintf(ctrl, "Savings from parallel remapping: %"PRIDX"\n",gk_max(0,gnsaved))); } WCOREPOP; } /************************************************************************* * This function computes the assignment using the the objective the * minimization of the total volume of data that needs to move **************************************************************************/ idx_t SimilarTpwgts(real_t *tpwgts, idx_t ncon, idx_t s1, idx_t s2) { idx_t i; for (i=0; i<ncon; i++) if (fabs(tpwgts[s1*ncon+i]-tpwgts[s2*ncon+i]) > SMALLFLOAT) break; if (i == ncon) return 1; return 0; }
4,883
24.978723
92
c
null
ParMETIS-main/libparmetis/balancemylink.c
/* * Copyright 1997, Regents of the University of Minnesota * * balancemylink.c * * This file contains code that implements the edge-based FM refinement * * Started 7/23/97 * George * * $Id: balancemylink.c 10542 2011-07-11 16:56:22Z karypis $ */ #include <parmetislib.h> #define PE 0 /************************************************************************* * This function performs an edge-based FM refinement **************************************************************************/ idx_t BalanceMyLink(ctrl_t *ctrl, graph_t *graph, idx_t *home, idx_t me, idx_t you, real_t *flows, real_t maxdiff, real_t *diff_cost, real_t *diff_lbavg, real_t avgvwgt) { idx_t h, i, ii, j, k, mype; idx_t nvtxs, ncon; idx_t nqueues, minval, maxval, higain, vtx, edge, totalv; idx_t from, to, qnum, index, nchanges, cut, tmp; idx_t pass, nswaps, nmoves, multiplier; idx_t *xadj, *vsize, *adjncy, *adjwgt, *where, *ed, *id; idx_t *hval, *nvpq, *inq, *map, *rmap, *ptr, *myqueue, *changes; real_t *nvwgt, *lbvec, *pwgts, *tpwgts, *my_wgt; real_t newgain; real_t lbavg, bestflow, mycost; real_t ipc_factor, redist_factor, ftmp; rpq_t **queues; WCOREPUSH; gkMPI_Comm_rank(MPI_COMM_WORLD, &mype); nvtxs = graph->nvtxs; ncon = graph->ncon; xadj = graph->xadj; nvwgt = graph->nvwgt; vsize = graph->vsize; adjncy = graph->adjncy; adjwgt = graph->adjwgt; where = graph->where; ipc_factor = ctrl->ipc_factor; redist_factor = ctrl->redist_factor; hval = iwspacemalloc(ctrl, nvtxs); id = iwspacemalloc(ctrl, nvtxs); ed = iwspacemalloc(ctrl, nvtxs); map = iwspacemalloc(ctrl, nvtxs); rmap = iwspacemalloc(ctrl, nvtxs); myqueue = iwspacemalloc(ctrl, nvtxs); changes = iwspacemalloc(ctrl, nvtxs); lbvec = rwspacemalloc(ctrl, ncon); pwgts = rset(2*ncon, 0.0, rwspacemalloc(ctrl, 2*ncon)); tpwgts = rwspacemalloc(ctrl, 2*ncon); my_wgt = rset(ncon, 0.0, rwspacemalloc(ctrl, ncon)); for (h=0; h<ncon; h++) { tpwgts[h] = -1.0*flows[h]; tpwgts[ncon+h] = flows[h]; } for (i=0; i<nvtxs; i++) { if (where[i] == me) { for (h=0; h<ncon; h++) { tpwgts[h] += nvwgt[i*ncon+h]; pwgts[h] += nvwgt[i*ncon+h]; } } else { ASSERT(where[i] == you); for (h=0; h<ncon; h++) { tpwgts[ncon+h] += nvwgt[i*ncon+h]; pwgts[ncon+h] += nvwgt[i*ncon+h]; } } } /* we don't want any tpwgts to be less than zero */ for (h=0; h<ncon; h++) { if (tpwgts[h] < 0.0) { tpwgts[ncon+h] += tpwgts[h]; tpwgts[h] = 0.0; } if (tpwgts[ncon+h] < 0.0) { tpwgts[h] += tpwgts[ncon+h]; tpwgts[ncon+h] = 0.0; } } /*******************************/ /* insert vertices into queues */ /*******************************/ minval = maxval = 0; multiplier = 1; for (i=0; i<ncon; i++) { multiplier *= (i+1); maxval += i*multiplier; minval += (ncon-1-i)*multiplier; } nqueues = maxval-minval+1; nvpq = iset(nqueues, 0, iwspacemalloc(ctrl, nqueues)); ptr = iwspacemalloc(ctrl, nqueues+1); inq = iwspacemalloc(ctrl, 2*nqueues); queues = (rpq_t **)(wspacemalloc(ctrl, sizeof(rpq_t *)*2*nqueues)); for (i=0; i<nvtxs; i++) hval[i] = Mc_HashVwgts(ctrl, ncon, nvwgt+i*ncon) - minval; for (i=0; i<nvtxs; i++) nvpq[hval[i]]++; for (ptr[0]=0, i=0; i<nqueues; i++) ptr[i+1] = ptr[i] + nvpq[i]; for (i=0; i<nvtxs; i++) { map[i] = ptr[hval[i]]; rmap[ptr[hval[i]]++] = i; } SHIFTCSR(i, nqueues, ptr); /* initialize queues */ for (i=0; i<nqueues; i++) if (nvpq[i] > 0) { queues[i] = rpqCreate(nvpq[i]); queues[nqueues+i] = rpqCreate(nvpq[i]); } /* compute internal/external degrees */ iset(nvtxs, 0, id); iset(nvtxs, 0, ed); for (j=0; j<nvtxs; j++) { for (k=xadj[j]; k<xadj[j+1]; k++) { if (where[adjncy[k]] == where[j]) id[j] += adjwgt[k]; else ed[j] += adjwgt[k]; } } nswaps = 0; for (pass=0; pass<N_MOC_BAL_PASSES; pass++) { iset(nvtxs, -1, myqueue); iset(nqueues*2, 0, inq); /* insert vertices into correct queues */ for (j=0; j<nvtxs; j++) { index = (where[j] == me) ? 0 : nqueues; newgain = ipc_factor*(real_t)(ed[j]-id[j]); if (home[j] == me || home[j] == you) { if (where[j] == home[j]) newgain -= redist_factor*(real_t)vsize[j]; else newgain += redist_factor*(real_t)vsize[j]; } rpqInsert(queues[hval[j]+index], map[j]-ptr[hval[j]], newgain); myqueue[j] = (where[j] == me) ? 0 : 1; inq[hval[j]+index]++; } /* bestflow = rfavg(ncon, flows); */ for (j=0, h=0; h<ncon; h++) { if (fabs(flows[h]) > fabs(flows[j])) j = h; } bestflow = fabs(flows[j]); nchanges = nmoves = 0; for (ii=0; ii<nvtxs/2; ii++) { from = -1; Mc_DynamicSelectQueue(ctrl, nqueues, ncon, me, you, inq, flows, &from, &qnum, minval, avgvwgt, maxdiff); /* can't find a vertex in one subdomain, try the other */ if (from != -1 && qnum == -1) { from = (from == me) ? you : me; if (from == me) { for (j=0; j<ncon; j++) { if (flows[j] > avgvwgt) break; } } else { for (j=0; j<ncon; j++) { if (flows[j] < -1.0*avgvwgt) break; } } if (j != ncon) Mc_DynamicSelectQueue(ctrl, nqueues, ncon, me, you, inq, flows, &from, &qnum, minval, avgvwgt, maxdiff); } if (qnum == -1) break; to = (from == me) ? you : me; index = (from == me) ? 0 : nqueues; higain = rpqGetTop(queues[qnum+index]); inq[qnum+index]--; ASSERT(higain != -1); /*****************/ /* make the swap */ /*****************/ vtx = rmap[higain+ptr[qnum]]; myqueue[vtx] = -1; where[vtx] = to; nswaps++; nmoves++; /* update the flows */ for (j=0; j<ncon; j++) flows[j] += (to == me) ? nvwgt[vtx*ncon+j] : -1.0*nvwgt[vtx*ncon+j]; /* ftmp = rfavg(ncon, flows); */ for (j=0, h=0; h<ncon; h++) { if (fabs(flows[h]) > fabs(flows[j])) j = h; } ftmp = fabs(flows[j]); if (ftmp < bestflow) { bestflow = ftmp; nchanges = 0; } else { changes[nchanges++] = vtx; } gk_SWAP(id[vtx], ed[vtx], tmp); for (j=xadj[vtx]; j<xadj[vtx+1]; j++) { edge = adjncy[j]; tmp = (to == where[edge] ? adjwgt[j] : -adjwgt[j]); INC_DEC(id[edge], ed[edge], tmp); if (myqueue[edge] != -1) { newgain = ipc_factor*(real_t)(ed[edge]-id[edge]); if (home[edge] == me || home[edge] == you) { if (where[edge] == home[edge]) newgain -= redist_factor*(real_t)vsize[edge]; else newgain += redist_factor*(real_t)vsize[edge]; } rpqUpdate(queues[hval[edge]+(nqueues*myqueue[edge])], map[edge]-ptr[hval[edge]], newgain); } } } /****************************/ /* now go back to best flow */ /****************************/ nswaps -= nchanges; nmoves -= nchanges; for (i=0; i<nchanges; i++) { vtx = changes[i]; from = where[vtx]; where[vtx] = to = (from == me) ? you : me; gk_SWAP(id[vtx], ed[vtx], tmp); for (j=xadj[vtx]; j<xadj[vtx+1]; j++) { edge = adjncy[j]; tmp = (to == where[edge] ? adjwgt[j] : -adjwgt[j]); INC_DEC(id[edge], ed[edge], tmp); } } for (i=0; i<nqueues; i++) { if (nvpq[i] > 0) { rpqReset(queues[i]); rpqReset(queues[i+nqueues]); } } if (nmoves == 0) break; } /***************************/ /* compute 2-way imbalance */ /***************************/ for (i=0; i<nvtxs; i++) { if (where[i] == me) { for (h=0; h<ncon; h++) my_wgt[h] += nvwgt[i*ncon+h]; } } for (i=0; i<ncon; i++) { ftmp = (pwgts[i]+pwgts[ncon+i])/2.0; if (ftmp != 0.0) lbvec[i] = fabs(my_wgt[i]-tpwgts[i]) / ftmp; else lbvec[i] = 0.0; } lbavg = ravg(ncon, lbvec); *diff_lbavg = lbavg; /****************/ /* compute cost */ /****************/ cut = totalv = 0; for (i=0; i<nvtxs; i++) { if (where[i] != home[i]) totalv += vsize[i]; for (j=xadj[i]; j<xadj[i+1]; j++) { if (where[adjncy[j]] != where[i]) cut += adjwgt[j]; } } cut /= 2; mycost = cut*ipc_factor + totalv*redist_factor; *diff_cost = mycost; /* free memory */ for (i=0; i<nqueues; i++) { if (nvpq[i] > 0) { rpqDestroy(queues[i]); rpqDestroy(queues[i+nqueues]); } } WCOREPOP; return nswaps; }
8,895
24.489971
76
c
null
ParMETIS-main/libparmetis/move.c
/* * Copyright 1997, Regents of the University of Minnesota * * mmove.c * * This file contains functions that move the graph given a partition * * Started 11/22/96 * George * * $Id: move.c 10657 2011-08-03 14:34:35Z karypis $ * */ #include <parmetislib.h> /*************************************************************************/ /*! This function moves the graph, and returns a new graph. This routine can be called with or without performing refinement. In the latter case it allocates and computes lpwgts itself. */ /*************************************************************************/ graph_t *MoveGraph(ctrl_t *ctrl, graph_t *graph) { idx_t h, i, ii, j, jj, nvtxs, ncon, npes, nsnbrs, nrnbrs; idx_t *xadj, *vwgt, *adjncy, *adjwgt, *mvtxdist; idx_t *where, *newlabel, *lpwgts, *gpwgts; idx_t *sgraph, *rgraph; ikv_t *sinfo, *rinfo; graph_t *mgraph; WCOREPUSH; /* this routine only works when nparts <= npes */ PASSERT(ctrl, ctrl->nparts <= ctrl->npes); npes = ctrl->npes; nvtxs = graph->nvtxs; ncon = graph->ncon; xadj = graph->xadj; vwgt = graph->vwgt; adjncy = graph->adjncy; adjwgt = graph->adjwgt; where = graph->where; mvtxdist = imalloc(npes+1, "MoveGraph: mvtxdist"); /* Let's do a prefix scan to determine the labeling of the nodes given */ lpwgts = iwspacemalloc(ctrl, npes+1); gpwgts = iwspacemalloc(ctrl, npes+1); sinfo = ikvwspacemalloc(ctrl, npes); rinfo = ikvwspacemalloc(ctrl, npes); for (i=0; i<npes; i++) sinfo[i].key = sinfo[i].val = 0; for (i=0; i<nvtxs; i++) { sinfo[where[i]].key++; sinfo[where[i]].val += xadj[i+1]-xadj[i]; } for (i=0; i<npes; i++) lpwgts[i] = sinfo[i].key; gkMPI_Scan((void *)lpwgts, (void *)gpwgts, npes, IDX_T, MPI_SUM, ctrl->comm); gkMPI_Allreduce((void *)lpwgts, (void *)mvtxdist, npes, IDX_T, MPI_SUM, ctrl->comm); MAKECSR(i, npes, mvtxdist); /* gpwgts[i] will store the label of the first vertex for each domain in each processor */ for (i=0; i<npes; i++) /* We were interested in an exclusive scan */ gpwgts[i] = mvtxdist[i] + gpwgts[i] - lpwgts[i]; newlabel = iwspacemalloc(ctrl, nvtxs+graph->nrecv); for (i=0; i<nvtxs; i++) newlabel[i] = gpwgts[where[i]]++; /* OK, now send the newlabel info to processors storing adjacent interface nodes */ CommInterfaceData(ctrl, graph, newlabel, newlabel+nvtxs); /* Now lets tell everybody what and from where he will get it. */ gkMPI_Alltoall((void *)sinfo, 2, IDX_T, (void *)rinfo, 2, IDX_T, ctrl->comm); /* Use lpwgts and gpwgts as pointers to where data will be received and send */ lpwgts[0] = 0; /* Send part */ gpwgts[0] = 0; /* Received part */ for (nsnbrs=nrnbrs=0, i=0; i<npes; i++) { lpwgts[i+1] = lpwgts[i] + (1+ncon)*sinfo[i].key + 2*sinfo[i].val; gpwgts[i+1] = gpwgts[i] + (1+ncon)*rinfo[i].key + 2*rinfo[i].val; if (rinfo[i].key > 0) nrnbrs++; if (sinfo[i].key > 0) nsnbrs++; } /* Update the max # of sreq/rreq/statuses */ CommUpdateNnbrs(ctrl, gk_max(nsnbrs, nrnbrs)); rgraph = iwspacemalloc(ctrl, gpwgts[npes]); WCOREPUSH; /* for freeing the send part early */ sgraph = iwspacemalloc(ctrl, lpwgts[npes]); /* Issue the receives first */ for (j=0, i=0; i<npes; i++) { if (rinfo[i].key > 0) gkMPI_Irecv((void *)(rgraph+gpwgts[i]), gpwgts[i+1]-gpwgts[i], IDX_T, i, 1, ctrl->comm, ctrl->rreq+j++); else PASSERT(ctrl, gpwgts[i+1]-gpwgts[i] == 0); } /* Assemble the graph to be sent and send it */ for (i=0; i<nvtxs; i++) { PASSERT(ctrl, where[i] >= 0 && where[i] < npes); ii = lpwgts[where[i]]; sgraph[ii++] = xadj[i+1]-xadj[i]; for (h=0; h<ncon; h++) sgraph[ii++] = vwgt[i*ncon+h]; for (j=xadj[i]; j<xadj[i+1]; j++) { sgraph[ii++] = newlabel[adjncy[j]]; sgraph[ii++] = adjwgt[j]; } lpwgts[where[i]] = ii; } SHIFTCSR(i, npes, lpwgts); for (j=0, i=0; i<npes; i++) { if (sinfo[i].key > 0) gkMPI_Isend((void *)(sgraph+lpwgts[i]), lpwgts[i+1]-lpwgts[i], IDX_T, i, 1, ctrl->comm, ctrl->sreq+j++); else PASSERT(ctrl, lpwgts[i+1]-lpwgts[i] == 0); } /* Wait for the send/recv to finish */ gkMPI_Waitall(nrnbrs, ctrl->rreq, ctrl->statuses); gkMPI_Waitall(nsnbrs, ctrl->sreq, ctrl->statuses); WCOREPOP; /* frees sgraph */ /* OK, now go and put the graph into graph_t Format */ mgraph = CreateGraph(); mgraph->vtxdist = mvtxdist; mgraph->gnvtxs = graph->gnvtxs; mgraph->ncon = ncon; mgraph->level = 0; mgraph->nvtxs = mgraph->nedges = 0; for (i=0; i<npes; i++) { mgraph->nvtxs += rinfo[i].key; mgraph->nedges += rinfo[i].val; } nvtxs = mgraph->nvtxs; xadj = mgraph->xadj = imalloc(nvtxs+1, "MMG: mgraph->xadj"); vwgt = mgraph->vwgt = imalloc(nvtxs*ncon, "MMG: mgraph->vwgt"); adjncy = mgraph->adjncy = imalloc(mgraph->nedges, "MMG: mgraph->adjncy"); adjwgt = mgraph->adjwgt = imalloc(mgraph->nedges, "MMG: mgraph->adjwgt"); for (jj=ii=i=0; i<nvtxs; i++) { xadj[i] = rgraph[ii++]; for (h=0; h<ncon; h++) vwgt[i*ncon+h] = rgraph[ii++]; for (j=0; j<xadj[i]; j++, jj++) { adjncy[jj] = rgraph[ii++]; adjwgt[jj] = rgraph[ii++]; } } MAKECSR(i, nvtxs, xadj); PASSERT(ctrl, jj == mgraph->nedges); PASSERT(ctrl, ii == gpwgts[npes]); PASSERTP(ctrl, jj == mgraph->nedges, (ctrl, "%"PRIDX" %"PRIDX"\n", jj, mgraph->nedges)); PASSERTP(ctrl, ii == gpwgts[npes], (ctrl, "%"PRIDX" %"PRIDX" %"PRIDX" %"PRIDX" %"PRIDX"\n", ii, gpwgts[npes], jj, mgraph->nedges, nvtxs)); #ifdef DEBUG IFSET(ctrl->dbglvl, DBG_INFO, rprintf(ctrl, "Checking moved graph...\n")); CheckMGraph(ctrl, mgraph); IFSET(ctrl->dbglvl, DBG_INFO, rprintf(ctrl, "Moved graph is consistent.\n")); #endif WCOREPOP; return mgraph; } /************************************************************************* * This function is used to transfer information from the moved graph * back to the original graph. The information is transfered from array * minfo to array info. The routine assumes that graph->where is left intact * and it is used to get the inverse mapping information. * The routine assumes that graph->where corresponds to a npes-way partition. **************************************************************************/ void ProjectInfoBack(ctrl_t *ctrl, graph_t *graph, idx_t *info, idx_t *minfo) { idx_t i, nvtxs, nparts, nrecvs, nsends; idx_t *where, *auxinfo, *sinfo, *rinfo; WCOREPUSH; nparts = ctrl->npes; nvtxs = graph->nvtxs; where = graph->where; sinfo = iwspacemalloc(ctrl, nparts+1); rinfo = iwspacemalloc(ctrl, nparts+1); /* Find out in rinfo how many entries are received per partition */ iset(nparts, 0, rinfo); for (i=0; i<nvtxs; i++) rinfo[where[i]]++; /* The rinfo are transposed and become the sinfo for the back-projection */ gkMPI_Alltoall((void *)rinfo, 1, IDX_T, (void *)sinfo, 1, IDX_T, ctrl->comm); MAKECSR(i, nparts, sinfo); MAKECSR(i, nparts, rinfo); /* allocate memory for auxinfo */ auxinfo = iwspacemalloc(ctrl, rinfo[nparts]); /*----------------------------------------------------------------- * Now, go and send back the minfo -----------------------------------------------------------------*/ for (nrecvs=0, i=0; i<nparts; i++) { if (rinfo[i+1]-rinfo[i] > 0) gkMPI_Irecv((void *)(auxinfo+rinfo[i]), rinfo[i+1]-rinfo[i], IDX_T, i, 1, ctrl->comm, ctrl->rreq+nrecvs++); } for (nsends=0, i=0; i<nparts; i++) { if (sinfo[i+1]-sinfo[i] > 0) gkMPI_Isend((void *)(minfo+sinfo[i]), sinfo[i+1]-sinfo[i], IDX_T, i, 1, ctrl->comm, ctrl->sreq+nsends++); } PASSERT(ctrl, nrecvs <= ctrl->ncommpes); PASSERT(ctrl, nsends <= ctrl->ncommpes); /* Wait for the send/recv to finish */ gkMPI_Waitall(nrecvs, ctrl->rreq, ctrl->statuses); gkMPI_Waitall(nsends, ctrl->sreq, ctrl->statuses); /* Scatter the info received in auxinfo back to info. */ for (i=0; i<nvtxs; i++) info[i] = auxinfo[rinfo[where[i]]++]; WCOREPOP; } /************************************************************************* * This function is used to convert a partition vector to a permutation * vector. **************************************************************************/ void FindVtxPerm(ctrl_t *ctrl, graph_t *graph, idx_t *perm) { idx_t i, nvtxs, nparts; idx_t *xadj, *adjncy, *adjwgt, *mvtxdist; idx_t *where, *lpwgts, *gpwgts; WCOREPUSH; nparts = ctrl->nparts; nvtxs = graph->nvtxs; xadj = graph->xadj; adjncy = graph->adjncy; adjwgt = graph->adjwgt; where = graph->where; mvtxdist = iwspacemalloc(ctrl, nparts+1); lpwgts = iwspacemalloc(ctrl, nparts+1); gpwgts = iwspacemalloc(ctrl, nparts+1); /* Here we care about the count and not total weight (diff since graph may be weighted */ iset(nparts, 0, lpwgts); for (i=0; i<nvtxs; i++) lpwgts[where[i]]++; /* Let's do a prefix scan to determine the labeling of the nodes given */ gkMPI_Scan((void *)lpwgts, (void *)gpwgts, nparts, IDX_T, MPI_SUM, ctrl->comm); gkMPI_Allreduce((void *)lpwgts, (void *)mvtxdist, nparts, IDX_T, MPI_SUM, ctrl->comm); MAKECSR(i, nparts, mvtxdist); for (i=0; i<nparts; i++) gpwgts[i] = mvtxdist[i] + gpwgts[i] - lpwgts[i]; /* We were interested in an exclusive Scan */ for (i=0; i<nvtxs; i++) perm[i] = gpwgts[where[i]]++; WCOREPOP; } /************************************************************************* * This function quickly performs a check on the consistency of moved graph. **************************************************************************/ void CheckMGraph(ctrl_t *ctrl, graph_t *graph) { idx_t i, j, jj, k, nvtxs, firstvtx, lastvtx; idx_t *xadj, *adjncy, *vtxdist; nvtxs = graph->nvtxs; xadj = graph->xadj; adjncy = graph->adjncy; vtxdist = graph->vtxdist; firstvtx = vtxdist[ctrl->mype]; lastvtx = vtxdist[ctrl->mype+1]; for (i=0; i<nvtxs; i++) { for (j=xadj[i]; j<xadj[i+1]; j++) { if (firstvtx+i == adjncy[j]) myprintf(ctrl, "(%"PRIDX" %"PRIDX") diagonal entry\n", i, i); if (adjncy[j] >= firstvtx && adjncy[j] < lastvtx) { k = adjncy[j]-firstvtx; for (jj=xadj[k]; jj<xadj[k+1]; jj++) { if (adjncy[jj] == firstvtx+i) break; } if (jj == xadj[k+1]) myprintf(ctrl, "(%"PRIDX" %"PRIDX") but not (%"PRIDX" %"PRIDX") [%"PRIDX" %"PRIDX"] [%"PRIDX" %"PRIDX"]\n", i, k, k, i, firstvtx+i, firstvtx+k, xadj[i+1]-xadj[i], xadj[k+1]-xadj[k]); } } } }
10,661
30.175439
118
c
null
ParMETIS-main/libparmetis/node_refine.c
/* * Copyright 1997, Regents of the University of Minnesota * * node_refine.c * * This file contains code that performs the k-way refinement * * Started 3/1/96 * George * * $Id: node_refine.c 10391 2011-06-23 19:00:08Z karypis $ */ #include <parmetislib.h> /************************************************************************************/ /*! This function allocates the memory required for the nodeND refinement code. The only refinement-related information that is has is the \c graph->where vector and allocates the memory for the remaining of the refinement-related data-structures. */ /************************************************************************************/ void AllocateNodePartitionParams(ctrl_t *ctrl, graph_t *graph) { idx_t nparts, nvtxs; idx_t *vwgt; NRInfoType *rinfo, *myrinfo; IFSET(ctrl->dbglvl, DBG_TIME, starttimer(ctrl->KWayInitTmr)); nvtxs = graph->nvtxs; nparts = ctrl->nparts; graph->nrinfo = (NRInfoType *)gk_malloc(sizeof(NRInfoType)*nvtxs, "AllocateNodePartitionParams: rinfo"); graph->lpwgts = imalloc(2*nparts, "AllocateNodePartitionParams: lpwgts"); graph->gpwgts = imalloc(2*nparts, "AllocateNodePartitionParams: gpwgts"); graph->sepind = imalloc(nvtxs, "AllocateNodePartitionParams: sepind"); /* Allocate additional memory for graph->vwgt in order to store the weights of the remote vertices */ vwgt = graph->vwgt; graph->vwgt = imalloc(nvtxs+graph->nrecv, "AllocateNodePartitionParams: graph->vwgt"); icopy(nvtxs, vwgt, graph->vwgt); gk_free((void **)&vwgt, LTERM); IFSET(ctrl->dbglvl, DBG_TIME, stoptimer(ctrl->KWayInitTmr)); } /************************************************************************************/ /*! This function computes the initial node refinment information for the parallel nodeND code. It requires that the required data-structures have already been allocated via a call to AllocateNodePartitionParams. */ /************************************************************************************/ void ComputeNodePartitionParams(ctrl_t *ctrl, graph_t *graph) { idx_t i, j, nparts, nvtxs, nsep; idx_t *xadj, *adjncy, *adjwgt, *vtxdist, *vwgt, *lpwgts, *gpwgts, *sepind; idx_t *where; NRInfoType *rinfo, *myrinfo; idx_t me, other, otherwgt; IFSET(ctrl->dbglvl, DBG_TIME, starttimer(ctrl->KWayInitTmr)); nvtxs = graph->nvtxs; nparts = ctrl->nparts; vtxdist = graph->vtxdist; xadj = graph->xadj; adjncy = graph->adjncy; adjwgt = graph->adjwgt; vwgt = graph->vwgt; where = graph->where; rinfo = graph->nrinfo; lpwgts = graph->lpwgts; gpwgts = graph->gpwgts; sepind = graph->sepind; /* Reset refinement data structures */ iset(2*nparts, 0, lpwgts); /* Send/Receive the where and vwgt information of interface vertices. */ CommInterfaceData(ctrl, graph, where, where+nvtxs); CommInterfaceData(ctrl, graph, vwgt, vwgt+nvtxs); /*------------------------------------------------------------ / Compute now the degrees /------------------------------------------------------------*/ for (nsep=i=0; i<nvtxs; i++) { me = where[i]; PASSERT(ctrl, me >= 0 && me < 2*nparts); lpwgts[me] += vwgt[i]; if (me >= nparts) { /* If it is a separator vertex */ sepind[nsep++] = i; lpwgts[2*nparts-1] += vwgt[i]; /* Keep track of total separator weight */ myrinfo = rinfo+i; myrinfo->edegrees[0] = myrinfo->edegrees[1] = 0; for (j=xadj[i]; j<xadj[i+1]; j++) { other = where[adjncy[j]]; if (me != other) myrinfo->edegrees[other%2] += vwgt[adjncy[j]]; } } } graph->nsep = nsep; /* Finally, sum-up the partition weights */ gkMPI_Allreduce((void *)lpwgts, (void *)gpwgts, 2*nparts, IDX_T, MPI_SUM, ctrl->comm); graph->mincut = gpwgts[2*nparts-1]; IFSET(ctrl->dbglvl, DBG_TIME, stoptimer(ctrl->KWayInitTmr)); } /************************************************************************************/ /*! This function updates the node refinment information after a where[] change */ /************************************************************************************/ void UpdateNodePartitionParams(ctrl_t *ctrl, graph_t *graph) { idx_t i, j, nparts, nvtxs, nsep; idx_t *xadj, *adjncy, *adjwgt, *vtxdist, *vwgt, *lpwgts, *gpwgts, *sepind; idx_t *where; NRInfoType *rinfo, *myrinfo; idx_t me, other, otherwgt; IFSET(ctrl->dbglvl, DBG_TIME, starttimer(ctrl->KWayInitTmr)); nvtxs = graph->nvtxs; nparts = ctrl->nparts; vtxdist = graph->vtxdist; xadj = graph->xadj; adjncy = graph->adjncy; adjwgt = graph->adjwgt; vwgt = graph->vwgt; where = graph->where; rinfo = graph->nrinfo; lpwgts = graph->lpwgts; gpwgts = graph->gpwgts; sepind = graph->sepind; /* Reset refinement data structures */ iset(2*nparts, 0, lpwgts); /* Send/Receive the where and vwgt information of interface vertices. */ CommInterfaceData(ctrl, graph, where, where+nvtxs); /*------------------------------------------------------------ / Compute now the degrees /------------------------------------------------------------*/ for (nsep=i=0; i<nvtxs; i++) { me = where[i]; PASSERT(ctrl, me >= 0 && me < 2*nparts); lpwgts[me] += vwgt[i]; if (me >= nparts) { /* If it is a separator vertex */ sepind[nsep++] = i; lpwgts[2*nparts-1] += vwgt[i]; /* Keep track of total separator weight */ myrinfo = rinfo+i; myrinfo->edegrees[0] = myrinfo->edegrees[1] = 0; for (j=xadj[i]; j<xadj[i+1]; j++) { other = where[adjncy[j]]; if (me != other) myrinfo->edegrees[other%2] += vwgt[adjncy[j]]; } } } graph->nsep = nsep; /* Finally, sum-up the partition weights */ gkMPI_Allreduce((void *)lpwgts, (void *)gpwgts, 2*nparts, IDX_T, MPI_SUM, ctrl->comm); graph->mincut = gpwgts[2*nparts-1]; IFSET(ctrl->dbglvl, DBG_TIME, stoptimer(ctrl->KWayInitTmr)); } /************************************************************************************/ /*! This function performs k-way node-based refinement. The refinement is done concurrently for all the different partitions. It works because each of the partitions is disconnected from each other due to the removal of the previous level separators. This version uses a priority queue to order the nodes and incorporates gain updates from the local information within each inner iteration. The refinement exits when there is no improvement in two successive itereations in order to account for the fact that a 0 => 1 iteration may have no gain but a 1 => 0 iteration may have a gain. */ /************************************************************************************/ void KWayNodeRefine_Greedy(ctrl_t *ctrl, graph_t *graph, idx_t npasses, real_t ubfrac) { idx_t i, ii, iii, j, jj, k, pass, nvtxs, nrecv, firstvtx, lastvtx, otherlastvtx, side, c, cc, nmoves, nlupd, nsupd, nnbrs, nchanged, nsep, nzerogainiterations; idx_t npes = ctrl->npes, mype = ctrl->mype, nparts = ctrl->nparts; idx_t *xadj, *adjncy, *adjwgt, *vtxdist, *vwgt; idx_t *where, *lpwgts, *gpwgts, *sepind; idx_t *peind, *recvptr, *sendptr; idx_t *update, *supdate, *rupdate, *pe_updates, *marker, *changed; idx_t *badmaxpwgt; ikv_t *swchanges, *rwchanges; idx_t *nupds_pe; NRInfoType *rinfo, *myrinfo; idx_t from, to, me, other, oldcut; rpq_t *queue; idx_t *inqueue; idx_t *rxadj, *radjncy; char title[1024]; IFSET(ctrl->dbglvl, DBG_TIME, starttimer(ctrl->KWayTmr)); WCOREPUSH; nvtxs = graph->nvtxs; nrecv = graph->nrecv; vtxdist = graph->vtxdist; xadj = graph->xadj; adjncy = graph->adjncy; adjwgt = graph->adjwgt; vwgt = graph->vwgt; firstvtx = vtxdist[mype]; lastvtx = vtxdist[mype+1]; where = graph->where; rinfo = graph->nrinfo; lpwgts = graph->lpwgts; gpwgts = graph->gpwgts; nsep = graph->nsep; sepind = graph->sepind; nnbrs = graph->nnbrs; peind = graph->peind; recvptr = graph->recvptr; sendptr = graph->sendptr; badmaxpwgt = iwspacemalloc(ctrl, nparts); nupds_pe = iwspacemalloc(ctrl, npes); changed = iwspacemalloc(ctrl, nvtxs); update = iwspacemalloc(ctrl, nvtxs); marker = iset(nvtxs+nrecv, 0, iwspacemalloc(ctrl, nvtxs+nrecv)); inqueue = iwspacemalloc(ctrl, nvtxs+nrecv); rwchanges = ikvwspacemalloc(ctrl, graph->nrecv); swchanges = ikvwspacemalloc(ctrl, graph->nsend); supdate = iwspacemalloc(ctrl, graph->nrecv); rupdate = iwspacemalloc(ctrl, graph->nsend); queue = rpqCreate(nvtxs); for (i=0; i<nparts; i+=2) { //badmaxpwgt[i] = badmaxpwgt[i+1] = ubfrac*(gpwgts[i]+gpwgts[i+1]+gpwgts[nparts+i])/2; badmaxpwgt[i] = badmaxpwgt[i+1] = ubfrac*(gpwgts[i]+gpwgts[i+1])/2; } /* construct the local adjacency list of the interface nodes */ rxadj = iset(nrecv+1, 0, iwspacemalloc(ctrl, nrecv+1)); for (i=0; i<nvtxs; i++) { for (j=xadj[i]; j<xadj[i+1]; j++) { if ((k = adjncy[j]-nvtxs) >= 0) rxadj[k]++; } } MAKECSR(i, nrecv, rxadj); radjncy = iwspacemalloc(ctrl, rxadj[nrecv]); for (i=0; i<nvtxs; i++) { for (j=xadj[i]; j<xadj[i+1]; j++) { if ((k = adjncy[j]-nvtxs) >= 0) radjncy[rxadj[k]++] = i; } } SHIFTCSR(i, nrecv, rxadj); IFSET(ctrl->dbglvl, DBG_REFINEINFO, PrintNodeBalanceInfo(ctrl, nparts, gpwgts, badmaxpwgt, "K-way sep-refinement")); c = GlobalSESum(ctrl, RandomInRange(2))%2; nzerogainiterations = 0; for (pass=0; pass<npasses; pass++) { oldcut = graph->mincut; for (side=0; side<2; side++) { cc = (c+1)%2; #ifndef NDEBUG /* This is for debugging purposes */ for (ii=0, i=0; i<nvtxs; i++) { if (where[i] >= nparts) ii++; } PASSERT(ctrl, ii == nsep); #endif /* Put the separator nodes in queue */ rpqReset(queue); iset(nvtxs+nrecv, 0, inqueue); for (ii=0; ii<nsep; ii++) { i = sepind[ii]; PASSERT(ctrl, inqueue[i] == 0); PASSERT(ctrl, where[i] >= nparts); rpqInsert(queue, i, vwgt[i] - rinfo[i].edegrees[cc]); inqueue[i] = 1; } nlupd = nsupd = nmoves = nchanged = nsep = 0; while ((i = rpqGetTop(queue)) != -1) { inqueue[i] = 0; from = where[i]; PASSERT(ctrl, from >= nparts); /* It is a one-sided move so it will go to the other partition. Look at the comments in InitMultisection to understand the meaning of from%nparts */ to = from%nparts+c; /* where to move the separator node */ other = from%nparts+cc; /* the other partition involved in the 3-way view */ /* Go through the loop to see if gain is possible for the separator vertex */ if (gpwgts[to]+vwgt[i] <= badmaxpwgt[to] && vwgt[i] - rinfo[i].edegrees[cc] >= 0) { /* Update the where information of the vertex you moved */ where[i] = to; lpwgts[from] -= vwgt[i]; lpwgts[2*nparts-1] -= vwgt[i]; lpwgts[to] += vwgt[i]; gpwgts[to] += vwgt[i]; /* Update and record future updates */ for (j=xadj[i]; j<xadj[i+1]; j++) { ii = adjncy[j]; /* If vertex ii is being pulled into the separator for the first time, then update the edegrees[] of the nodes currently in the queue that vertex ii is connected to */ if (marker[ii] == 0 && where[ii] == other) { if (ii < nvtxs) { /* local vertices */ for (jj=xadj[ii]; jj<xadj[ii+1]; jj++) { iii = adjncy[jj]; if (inqueue[iii] == 1) { PASSERT(ctrl, rinfo[iii].edegrees[cc] >= vwgt[ii]); rinfo[iii].edegrees[cc] -= vwgt[ii]; rpqUpdate(queue, iii, vwgt[iii]-rinfo[iii].edegrees[cc]); } } } else { /* remote vertices */ for (jj=rxadj[ii-nvtxs]; jj<rxadj[ii-nvtxs+1]; jj++) { iii = radjncy[jj]; if (inqueue[iii] == 1) { PASSERT(ctrl, rinfo[iii].edegrees[cc] >= vwgt[ii]); rinfo[iii].edegrees[cc] -= vwgt[ii]; rpqUpdate(queue, iii, vwgt[iii]-rinfo[iii].edegrees[cc]); } } } } /* Put the vertices adjacent to i that belong to either the separator or the cc partition into the update array */ if (marker[ii] == 0 && where[ii] != to) { marker[ii] = 1; if (ii<nvtxs) update[nlupd++] = ii; else supdate[nsupd++] = ii; } } nmoves++; if (graph->pexadj[i+1]-graph->pexadj[i] > 0) changed[nchanged++] = i; } else { /* This node will remain in the separator for the next iteration */ sepind[nsep++] = i; } } /* myprintf(ctrl, "nmoves: %"PRIDX", nlupd: %"PRIDX", nsupd: %"PRIDX"\n", nmoves, nlupd, nsupd); */ IFSET(ctrl->dbglvl, DBG_RMOVEINFO, rprintf(ctrl, "\t[%"PRIDX" %"PRIDX"], [%"PRIDX" %"PRIDX" %"PRIDX"]\n", pass, c, GlobalSESum(ctrl, nmoves), GlobalSESum(ctrl, nsupd), GlobalSESum(ctrl, nlupd))); /*----------------------------------------------------------------------- / Time to communicate with processors to send the vertices whose degrees / need to be updated. /-----------------------------------------------------------------------*/ /* Issue the receives first */ for (i=0; i<nnbrs; i++) { gkMPI_Irecv((void *)(rupdate+sendptr[i]), sendptr[i+1]-sendptr[i], IDX_T, peind[i], 1, ctrl->comm, ctrl->rreq+i); } /* Issue the sends next. This needs some preporcessing */ for (i=0; i<nsupd; i++) { marker[supdate[i]] = 0; supdate[i] = graph->imap[supdate[i]]; } isorti(nsupd, supdate); for (j=i=0; i<nnbrs; i++) { otherlastvtx = vtxdist[peind[i]+1]; for (k=j; k<nsupd && supdate[k] < otherlastvtx; k++); gkMPI_Isend((void *)(supdate+j), k-j, IDX_T, peind[i], 1, ctrl->comm, ctrl->sreq+i); j = k; } /* OK, now get into the loop waiting for the send/recv operations to finish */ gkMPI_Waitall(nnbrs, ctrl->rreq, ctrl->statuses); for (i=0; i<nnbrs; i++) gkMPI_Get_count(ctrl->statuses+i, IDX_T, nupds_pe+i); gkMPI_Waitall(nnbrs, ctrl->sreq, ctrl->statuses); /*------------------------------------------------------------- / Place the received to-be updated vertices into update[] /-------------------------------------------------------------*/ for (i=0; i<nnbrs; i++) { pe_updates = rupdate+sendptr[i]; for (j=0; j<nupds_pe[i]; j++) { k = pe_updates[j]; if (marker[k-firstvtx] == 0) { marker[k-firstvtx] = 1; update[nlupd++] = k-firstvtx; } } } /*------------------------------------------------------------- / Update the where information of the vertices that are pulled / into the separator. /-------------------------------------------------------------*/ for (ii=0; ii<nlupd; ii++) { i = update[ii]; me = where[i]; if (me < nparts && me%2 == cc) { /* This vertex is pulled into the separator */ lpwgts[me] -= vwgt[i]; where[i] = nparts+me-(me%2); sepind[nsep++] = i; /* Put the vertex into the sepind array */ if (graph->pexadj[i+1]-graph->pexadj[i] > 0) changed[nchanged++] = i; lpwgts[where[i]] += vwgt[i]; lpwgts[2*nparts-1] += vwgt[i]; /* myprintf(ctrl, "Vertex %"PRIDX" moves into the separator from %"PRIDX" to %"PRIDX"\n", i+firstvtx, me, where[i]); */ } } /* Tell everybody interested what the new where[] info is for the interface vertices */ CommChangedInterfaceData(ctrl, graph, nchanged, changed, where, swchanges, rwchanges); /*------------------------------------------------------------- / Update the rinfo of the vertices in the update[] array /-------------------------------------------------------------*/ for (ii=0; ii<nlupd; ii++) { i = update[ii]; PASSERT(ctrl, marker[i] == 1); marker[i] = 0; me = where[i]; if (me >= nparts) { /* If it is a separator vertex */ /* myprintf(ctrl, "Updating %"PRIDX" %"PRIDX"\n", i+firstvtx, me); */ myrinfo = rinfo+i; myrinfo->edegrees[0] = myrinfo->edegrees[1] = 0; for (j=xadj[i]; j<xadj[i+1]; j++) { other = where[adjncy[j]]; if (me != other) myrinfo->edegrees[other%2] += vwgt[adjncy[j]]; } } } /* Finally, sum-up the partition weights */ gkMPI_Allreduce((void *)lpwgts, (void *)gpwgts, 2*nparts, IDX_T, MPI_SUM, ctrl->comm); graph->mincut = gpwgts[2*nparts-1]; sprintf(title, "\tTotalSep [%"PRIDX"]", c); IFSET(ctrl->dbglvl, DBG_REFINEINFO, PrintNodeBalanceInfo(ctrl, nparts, gpwgts, badmaxpwgt, title)); /* break out if there is no improvement in two successive inner iterations that can span successive outer iterations */ if (graph->mincut == oldcut) { if (++nzerogainiterations == 2) break; } else { nzerogainiterations = 0; } c = cc; } /* break out if there is no improvement in two successive inner iterations that can span successive outer iterations */ if (graph->mincut == oldcut && nzerogainiterations == 2) break; } rpqDestroy(queue); WCOREPOP; IFSET(ctrl->dbglvl, DBG_TIME, stoptimer(ctrl->KWayTmr)); } /************************************************************************************/ /*! This function performs k-way node-based refinement. The key difference between this and the previous routine is that the well-interior nodes are refined using a serial node-based refinement algortihm. */ /************************************************************************************/ void KWayNodeRefine2Phase(ctrl_t *ctrl, graph_t *graph, idx_t npasses, real_t ubfrac) { idx_t i, oldcut; oldcut = graph->mincut+1; for (i=0; i<npasses; i++) { KWayNodeRefine_Greedy(ctrl, graph, npasses, ubfrac); if (graph->mincut == oldcut) break; oldcut = graph->mincut; KWayNodeRefineInterior(ctrl, graph, 2, ubfrac); UpdateNodePartitionParams(ctrl, graph); if (graph->mincut == oldcut) break; oldcut = graph->mincut; } } /************************************************************************************/ /*! This function performs k-way node-based refinement of the interior nodes of the graph assigned to each processor using a serial node-refinement algorithm. */ /************************************************************************************/ void KWayNodeRefineInterior(ctrl_t *ctrl, graph_t *graph, idx_t npasses, real_t ubfrac) { idx_t i, j, k, ii, gnnz, gid, qsize; idx_t npes = ctrl->npes, mype = ctrl->mype, nparts = ctrl->nparts; idx_t nvtxs, *xadj, *adjncy, *vwgt, *where, *pexadj; idx_t gnvtxs, *gxadj, *gadjncy, *gvwgt, *gwhere, *ghmarker; idx_t *gmap, *gimap; idx_t *pptr, *pind; IFSET(ctrl->dbglvl, DBG_TIME, starttimer(ctrl->AuxTmr1)); IFSET(ctrl->dbglvl, DBG_TIME, starttimer(ctrl->KWayTmr)); WCOREPUSH; nvtxs = graph->nvtxs; xadj = graph->xadj; adjncy = graph->adjncy; vwgt = graph->vwgt; where = graph->where; pexadj = graph->pexadj; gxadj = iwspacemalloc(ctrl, nvtxs+1); gvwgt = iwspacemalloc(ctrl, nvtxs); gadjncy = iwspacemalloc(ctrl, xadj[nvtxs]); gwhere = iwspacemalloc(ctrl, nvtxs); ghmarker = iwspacemalloc(ctrl, nvtxs); gmap = iset(nvtxs, -1, iwspacemalloc(ctrl, nvtxs)); gimap = iwspacemalloc(ctrl, nvtxs); pptr = iset(2*nparts+1, 0, iwspacemalloc(ctrl, 2*nparts+1)); pind = iwspacemalloc(ctrl, nvtxs); /* Set pptr/pind to contain the vertices in each one of the partitions */ for (i=0; i<nvtxs; i++) pptr[where[i]]++; MAKECSR(i, 2*nparts, pptr); for (i=0; i<nvtxs; i++) pind[pptr[where[i]]++] = i; SHIFTCSR(i, 2*nparts, pptr); /* Extract each individual graph and refine it */ for (gid=0; gid<nparts; gid+=2) { if (graph->lpwgts[nparts+gid] == 0) continue; /* a quick test to determine if there are sufficient non-interface separator nodes */ for (qsize=0, ii=pptr[nparts+gid]; ii<pptr[nparts+gid+1]; ii++) { if (pexadj[pind[ii]] == pexadj[pind[ii]+1]) { if (++qsize >= 2) break; } } if (ii == pptr[nparts+gid+1]) break; /* no need to proceed. not enough non-interface separator nodes */ /* compute the gmap/gimap and other node info for the extracted graph */ for (gnvtxs=0, ii=pptr[nparts+gid]; ii<pptr[nparts+gid+1]; ii++, gnvtxs++) { i = pind[ii]; gmap[i] = gnvtxs; gimap[gnvtxs] = i; gvwgt[gnvtxs] = vwgt[i]; gwhere[gnvtxs] = 2; ghmarker[gnvtxs] = (pexadj[i+1]-pexadj[i] > 0 ? gwhere[gnvtxs] : -1); } for (ii=pptr[gid]; ii<pptr[gid+2]; ii++, gnvtxs++) { i = pind[ii]; gmap[i] = gnvtxs; gimap[gnvtxs] = i; gvwgt[gnvtxs] = vwgt[i]; gwhere[gnvtxs] = where[i] - gid; ghmarker[gnvtxs] = (pexadj[i+1]-pexadj[i] > 0 ? gwhere[gnvtxs] : -1); PASSERT(ctrl, gwhere[gnvtxs] >= 0 && gwhere[gnvtxs] <= 1); } gxadj[0]=0; gnvtxs=0; gnnz=0; /* go over the separator nodes */ for (ii=pptr[nparts+gid]; ii<pptr[nparts+gid+1]; ii++) { i = pind[ii]; for (j=xadj[i]; j<xadj[i+1]; j++) { if (adjncy[j] < nvtxs) gadjncy[gnnz++] = gmap[adjncy[j]]; } gxadj[++gnvtxs] = gnnz; } /* go over the interior nodes */ for (ii=pptr[gid]; ii<pptr[gid+2]; ii++) { i = pind[ii]; for (j=xadj[i]; j<xadj[i+1]; j++) { if (adjncy[j] < nvtxs) gadjncy[gnnz++] = gmap[adjncy[j]]; } gxadj[++gnvtxs] = gnnz; } if (gnnz == 0) continue; /* The 1.03 is here by choice as it is better to refine using tight constraints */ METIS_NodeRefine(gnvtxs, gxadj, gvwgt, gadjncy, gwhere, ghmarker, 1.03); for (i=0; i<gnvtxs; i++) { if (gwhere[i] == 2) where[gimap[i]] = nparts + gid; else where[gimap[i]] = gwhere[i] + gid; } } WCOREPOP; IFSET(ctrl->dbglvl, DBG_TIME, stoptimer(ctrl->KWayTmr)); IFSET(ctrl->dbglvl, DBG_TIME, stoptimer(ctrl->AuxTmr1)); } /************************************************************************************/ /*! This function prints balance information for the parallel k-section refinement algorithm. */ /************************************************************************************/ void PrintNodeBalanceInfo(ctrl_t *ctrl, idx_t nparts, idx_t *gpwgts, idx_t *badmaxpwgt, char *title) { idx_t i; if (ctrl->mype == 0) { printf("%s: %"PRIDX", ", title, gpwgts[2*nparts-1]); for (i=0; i<nparts; i+=2) printf(" [%5"PRIDX" %5"PRIDX" %5"PRIDX" %5"PRIDX"]", gpwgts[i], gpwgts[i+1], gpwgts[nparts+i], badmaxpwgt[i]); printf("\n"); } gkMPI_Barrier(ctrl->comm); }
23,763
32.236364
117
c
null
ParMETIS-main/libparmetis/mesh.c
/* * Copyright 1997, Regents of the University of Minnesota * * mesh.c * * This file contains routines for constructing the dual graph of a mesh. * Assumes that each processor has at least one mesh element. * * Started 10/19/94 * George * * $Id: mesh.c 10575 2011-07-14 14:46:42Z karypis $ * */ #include <parmetislib.h> /************************************************************************* * This function converts a mesh into a dual graph **************************************************************************/ int ParMETIS_V3_Mesh2Dual(idx_t *elmdist, idx_t *eptr, idx_t *eind, idx_t *numflag, idx_t *ncommon, idx_t **r_xadj, idx_t **r_adjncy, MPI_Comm *comm) { idx_t i, j, jj, k, kk, m; idx_t npes, mype, pe, count, mask, pass; idx_t nelms, lnns, my_nns, node; idx_t firstelm, firstnode, lnode, nrecv, nsend; idx_t *scounts, *rcounts, *sdispl, *rdispl; idx_t *nodedist, *nmap, *auxarray; idx_t *gnptr, *gnind, *nptr, *nind, *myxadj=NULL, *myadjncy = NULL; idx_t *sbuffer, *rbuffer, *htable; ikv_t *nodelist, *recvbuffer; idx_t maxcount, *ind, *wgt; idx_t gmaxnode, gminnode; size_t curmem; gk_malloc_init(); curmem = gk_GetCurMemoryUsed(); /* Get basic comm info */ gkMPI_Comm_size(*comm, &npes); gkMPI_Comm_rank(*comm, &mype); nelms = elmdist[mype+1]-elmdist[mype]; if (*numflag > 0) ChangeNumberingMesh(elmdist, eptr, eind, NULL, NULL, NULL, npes, mype, 1); mask = (1<<11)-1; /*****************************/ /* Determine number of nodes */ /*****************************/ gminnode = GlobalSEMinComm(*comm, imin(eptr[nelms], eind, 1)); for (i=0; i<eptr[nelms]; i++) eind[i] -= gminnode; gmaxnode = GlobalSEMaxComm(*comm, imax(eptr[nelms], eind, 1)); /**************************/ /* Check for input errors */ /**************************/ ASSERT(nelms > 0); /* construct node distribution array */ nodedist = ismalloc(npes+1, 0, "nodedist"); for (nodedist[0]=0, i=0,j=gmaxnode+1; i<npes; i++) { k = j/(npes-i); nodedist[i+1] = nodedist[i]+k; j -= k; } my_nns = nodedist[mype+1]-nodedist[mype]; firstnode = nodedist[mype]; nodelist = ikvmalloc(eptr[nelms], "nodelist"); auxarray = imalloc(eptr[nelms], "auxarray"); htable = ismalloc(gk_max(my_nns, mask+1), -1, "htable"); scounts = imalloc(npes, "scounts"); rcounts = imalloc(npes, "rcounts"); sdispl = imalloc(npes+1, "sdispl"); rdispl = imalloc(npes+1, "rdispl"); /*********************************************/ /* first find a local numbering of the nodes */ /*********************************************/ for (i=0; i<nelms; i++) { for (j=eptr[i]; j<eptr[i+1]; j++) { nodelist[j].key = eind[j]; nodelist[j].val = j; auxarray[j] = i; /* remember the local element ID that uses this node */ } } ikvsorti(eptr[nelms], nodelist); for (count=1, i=1; i<eptr[nelms]; i++) { if (nodelist[i].key > nodelist[i-1].key) count++; } lnns = count; nmap = imalloc(lnns, "nmap"); /* renumber the nodes of the elements array */ count = 1; nmap[0] = nodelist[0].key; eind[nodelist[0].val] = 0; nodelist[0].val = auxarray[nodelist[0].val]; /* Store the local element ID */ for (i=1; i<eptr[nelms]; i++) { if (nodelist[i].key > nodelist[i-1].key) { nmap[count] = nodelist[i].key; count++; } eind[nodelist[i].val] = count-1; nodelist[i].val = auxarray[nodelist[i].val]; /* Store the local element ID */ } gkMPI_Barrier(*comm); /**********************************************************/ /* perform comms necessary to construct node-element list */ /**********************************************************/ iset(npes, 0, scounts); for (pe=i=0; i<eptr[nelms]; i++) { while (nodelist[i].key >= nodedist[pe+1]) pe++; scounts[pe] += 2; } ASSERT(pe < npes); gkMPI_Alltoall((void *)scounts, 1, IDX_T, (void *)rcounts, 1, IDX_T, *comm); icopy(npes, scounts, sdispl); MAKECSR(i, npes, sdispl); icopy(npes, rcounts, rdispl); MAKECSR(i, npes, rdispl); ASSERT(sdispl[npes] == eptr[nelms]*2); nrecv = rdispl[npes]/2; recvbuffer = ikvmalloc(gk_max(1, nrecv), "recvbuffer"); gkMPI_Alltoallv((void *)nodelist, scounts, sdispl, IDX_T, (void *)recvbuffer, rcounts, rdispl, IDX_T, *comm); /**************************************/ /* construct global node-element list */ /**************************************/ gnptr = ismalloc(my_nns+1, 0, "gnptr"); for (i=0; i<npes; i++) { for (j=rdispl[i]/2; j<rdispl[i+1]/2; j++) { lnode = recvbuffer[j].key-firstnode; ASSERT(lnode >= 0 && lnode < my_nns) gnptr[lnode]++; } } MAKECSR(i, my_nns, gnptr); gnind = imalloc(gk_max(1, gnptr[my_nns]), "gnind"); for (pe=0; pe<npes; pe++) { firstelm = elmdist[pe]; for (j=rdispl[pe]/2; j<rdispl[pe+1]/2; j++) { lnode = recvbuffer[j].key-firstnode; gnind[gnptr[lnode]++] = recvbuffer[j].val+firstelm; } } SHIFTCSR(i, my_nns, gnptr); /*********************************************************/ /* send the node-element info to the relevant processors */ /*********************************************************/ iset(npes, 0, scounts); /* use a hash table to ensure that each node is sent to a proc only once */ for (pe=0; pe<npes; pe++) { for (j=rdispl[pe]/2; j<rdispl[pe+1]/2; j++) { lnode = recvbuffer[j].key-firstnode; if (htable[lnode] == -1) { scounts[pe] += gnptr[lnode+1]-gnptr[lnode]; htable[lnode] = 1; } } /* now reset the hash table */ for (j=rdispl[pe]/2; j<rdispl[pe+1]/2; j++) { lnode = recvbuffer[j].key-firstnode; htable[lnode] = -1; } } gkMPI_Alltoall((void *)scounts, 1, IDX_T, (void *)rcounts, 1, IDX_T, *comm); icopy(npes, scounts, sdispl); MAKECSR(i, npes, sdispl); /* create the send buffer */ nsend = sdispl[npes]; sbuffer = imalloc(gk_max(1, nsend), "sbuffer"); count = 0; for (pe=0; pe<npes; pe++) { for (j=rdispl[pe]/2; j<rdispl[pe+1]/2; j++) { lnode = recvbuffer[j].key-firstnode; if (htable[lnode] == -1) { for (k=gnptr[lnode]; k<gnptr[lnode+1]; k++) { if (k == gnptr[lnode]) sbuffer[count++] = -1*(gnind[k]+1); else sbuffer[count++] = gnind[k]; } htable[lnode] = 1; } } ASSERT(count == sdispl[pe+1]); /* now reset the hash table */ for (j=rdispl[pe]/2; j<rdispl[pe+1]/2; j++) { lnode = recvbuffer[j].key-firstnode; htable[lnode] = -1; } } icopy(npes, rcounts, rdispl); MAKECSR(i, npes, rdispl); nrecv = rdispl[npes]; rbuffer = imalloc(gk_max(1, nrecv), "rbuffer"); gkMPI_Alltoallv((void *)sbuffer, scounts, sdispl, IDX_T, (void *)rbuffer, rcounts, rdispl, IDX_T, *comm); k = -1; nptr = ismalloc(lnns+1, 0, "nptr"); nind = rbuffer; for (pe=0; pe<npes; pe++) { for (j=rdispl[pe]; j<rdispl[pe+1]; j++) { if (nind[j] < 0) { k++; nind[j] = (-1*nind[j])-1; } nptr[k]++; } } MAKECSR(i, lnns, nptr); ASSERT(k+1 == lnns); ASSERT(nptr[lnns] == nrecv) myxadj = *r_xadj = (idx_t *)malloc(sizeof(idx_t)*(nelms+1)); if (myxadj == NULL) gk_errexit(SIGMEM, "Failed to allocate memory for the dual graph's xadj array.\n"); iset(nelms+1, 0, myxadj); iset(mask+1, -1, htable); firstelm = elmdist[mype]; /* Two passes -- in first pass, simply find out the memory requirements */ maxcount = 200; ind = imalloc(maxcount, "ParMETIS_V3_Mesh2Dual: ind"); wgt = imalloc(maxcount, "ParMETIS_V3_Mesh2Dual: wgt"); for (pass=0; pass<2; pass++) { for (i=0; i<nelms; i++) { for (count=0, j=eptr[i]; j<eptr[i+1]; j++) { node = eind[j]; for (k=nptr[node]; k<nptr[node+1]; k++) { if ((kk=nind[k]) == firstelm+i) continue; m = htable[(kk&mask)]; if (m == -1) { ind[count] = kk; wgt[count] = 1; htable[(kk&mask)] = count++; } else { if (ind[m] == kk) { wgt[m]++; } else { for (jj=0; jj<count; jj++) { if (ind[jj] == kk) { wgt[jj]++; break; } } if (jj == count) { ind[count] = kk; wgt[count++] = 1; } } } /* Adjust the memory. This will be replaced by a idxrealloc() when GKlib will be incorporated */ if (count == maxcount-1) { maxcount *= 2; ind = irealloc(ind, maxcount, "ParMETIS_V3_Mesh2Dual: ind"); wgt = irealloc(wgt, maxcount, "ParMETIS_V3_Mesh2Dual: wgt"); } } } for (j=0; j<count; j++) { htable[(ind[j]&mask)] = -1; if (wgt[j] >= *ncommon) { if (pass == 0) myxadj[i]++; else myadjncy[myxadj[i]++] = ind[j]; } } } if (pass == 0) { MAKECSR(i, nelms, myxadj); myadjncy = *r_adjncy = (idx_t *)malloc(sizeof(idx_t)*myxadj[nelms]); if (myadjncy == NULL) gk_errexit(SIGMEM, "Failed to allocate memory for dual graph's adjncy array.\n"); } else { SHIFTCSR(i, nelms, myxadj); } } /*****************************************/ /* correctly renumber the elements array */ /*****************************************/ for (i=0; i<eptr[nelms]; i++) eind[i] = nmap[eind[i]] + gminnode; if (*numflag == 1) ChangeNumberingMesh(elmdist, eptr, eind, myxadj, myadjncy, NULL, npes, mype, 0); /* do not free nodelist, recvbuffer, rbuffer */ gk_free((void **)&nodedist, &nodelist, &auxarray, &htable, &scounts, &rcounts, &sdispl, &rdispl, &nmap, &recvbuffer, &gnptr, &gnind, &sbuffer, &rbuffer, &nptr, &ind, &wgt, LTERM); if (gk_GetCurMemoryUsed() - curmem > 0) { printf("ParMETIS appears to have a memory leak of %zdbytes. Report this.\n", (ssize_t)(gk_GetCurMemoryUsed() - curmem)); } gk_malloc_cleanup(0); return METIS_OK; }
10,199
27.333333
89
c
null
ParMETIS-main/libparmetis/initmsection.c
/* * Copyright 1997, Regents of the University of Minnesota * * initmsection.c * * This file contains code that performs the k-way multisection * * Started 6/3/97 * George * * $Id: initmsection.c 10361 2011-06-21 19:16:22Z karypis $ */ #include <parmetislib.h> #define DEBUG_IPART_ /************************************************************************************/ /*! The entry point of the algorithm that finds the separators of the coarsest graph. This algorithm first assembles the graph to all the processors, it then splits the processors into groups depending on the number of partitions for which we want to compute the separator. The processors of each group compute the separator of their corresponding graph and the smallest separator is selected. The parameter nparts on calling this routine indicates the number of desired partitions after the multisection (excluding the nodes that end up on the separator). The initial bisection is achieved when nparts==2 and upon entry graph->where[] = 0 for all vertices. Similarly, if nparts==4, it indicates that we have a graph that is already partitioned into two parts (as specified in graph->where) and we need to find the separator of each one of these parts. The final partitioning is encoded in the graph->where vector as follows. If nparts is the number of partitions, the left, right, and separator subpartitions of the original partition i will be labeled 2*i, 2*i+1, and nparts+2*i, respectively. Note that in the above expressions, i goes from [0...nparts/2]. As a result of this encoding, the left (i.e., 0th) partition of a node \c i on the separator will be given by where[i]%nparts. */ /************************************************************************************/ void InitMultisection(ctrl_t *ctrl, graph_t *graph) { idx_t i, myrank, mypart, options[METIS_NOPTIONS]; idx_t *vtxdist, *gwhere = NULL, *part, *label; graph_t *agraph; idx_t *sendcounts, *displs; MPI_Comm newcomm, labelcomm; struct { double cut; int rank; } lpecut, gpecut; IFSET(ctrl->dbglvl, DBG_TIME, starttimer(ctrl->InitPartTmr)); WCOREPUSH; /* Assemble the graph and do the necessary pre-processing */ agraph = AssembleMultisectedGraph(ctrl, graph); part = agraph->where; agraph->where = NULL; /* Split the processors into groups so that each one can do a bisection */ mypart = ctrl->mype%(ctrl->nparts/2); gkMPI_Comm_split(ctrl->comm, mypart, 0, &newcomm); gkMPI_Comm_rank(newcomm, &myrank); /* Each processor keeps the graph that it only needs and bisects it */ KeepPart(ctrl, agraph, part, mypart); label = agraph->label; /* Save this because ipart may need it */ agraph->label = NULL; /* Bisect the graph and construct the separator */ METIS_SetDefaultOptions(options); options[METIS_OPTION_SEED] = (ctrl->mype+8)*101; options[METIS_OPTION_NSEPS] = 5; options[METIS_OPTION_UFACTOR] = (idx_t)(1000.0*(ctrl->ubfrac - 1.0)); WCOREPUSH; /* for freeing agraph->where and gwhere */ agraph->where = iwspacemalloc(ctrl, agraph->nvtxs); METIS_ComputeVertexSeparator(&agraph->nvtxs, agraph->xadj, agraph->adjncy, agraph->vwgt, options, &agraph->mincut, agraph->where); for (i=0; i<agraph->nvtxs; i++) { PASSERT(ctrl, agraph->where[i]>=0 && agraph->where[i]<=2); if (agraph->where[i] == 2) agraph->where[i] = ctrl->nparts+2*mypart; else agraph->where[i] += 2*mypart; } /* Determine which PE got the minimum cut */ lpecut.cut = agraph->mincut; lpecut.rank = myrank; gkMPI_Allreduce(&lpecut, &gpecut, 1, MPI_DOUBLE_INT, MPI_MINLOC, newcomm); /* myprintf(ctrl, "Nvtxs: %"PRIDX", Mincut: %"PRIDX", GMincut: %"PRIDX", %"PRIDX"\n", agraph->nvtxs, agraph->mincut, (idx_t)gpecut.cut, (idx_t)gpecut.rank); */ /* Send the best where to the root processor of this partition */ if (myrank != 0 && myrank == gpecut.rank) gkMPI_Send((void *)agraph->where, agraph->nvtxs, IDX_T, 0, 1, newcomm); if (myrank == 0 && myrank != gpecut.rank) gkMPI_Recv((void *)agraph->where, agraph->nvtxs, IDX_T, gpecut.rank, 1, newcomm, &ctrl->status); /* Create a communicator that stores all the i-th processors of the newcomm */ gkMPI_Comm_split(ctrl->comm, myrank, 0, &labelcomm); /* Map the separator back to agraph. This is inefficient! */ if (myrank == 0) { gwhere = iset(graph->gnvtxs, 0, iwspacemalloc(ctrl, graph->gnvtxs)); for (i=0; i<agraph->nvtxs; i++) gwhere[label[i]] = agraph->where[i]; gkMPI_Reduce((void *)gwhere, (void *)part, graph->gnvtxs, IDX_T, MPI_SUM, 0, labelcomm); } WCOREPOP; /* free agraph->where & gwhere */ agraph->where = part; /* The minimum PE performs the Scatter */ vtxdist = graph->vtxdist; PASSERT(ctrl, graph->where != NULL); gk_free((void **)&graph->where, LTERM); /* Remove the propagated down where info */ graph->where = imalloc(graph->nvtxs+graph->nrecv, "InitPartition: where"); sendcounts = iwspacemalloc(ctrl, ctrl->npes); displs = iwspacemalloc(ctrl, ctrl->npes); for (i=0; i<ctrl->npes; i++) { sendcounts[i] = vtxdist[i+1]-vtxdist[i]; displs[i] = vtxdist[i]; } gkMPI_Scatterv((void *)agraph->where, sendcounts, displs, IDX_T, (void *)graph->where, graph->nvtxs, IDX_T, 0, ctrl->comm); agraph->label = label; FreeGraph(agraph); gkMPI_Comm_free(&newcomm); gkMPI_Comm_free(&labelcomm); WCOREPOP; IFSET(ctrl->dbglvl, DBG_TIME, stoptimer(ctrl->InitPartTmr)); } /*************************************************************************/ /*! This function assembles the graph into a single processor */ /*************************************************************************/ graph_t *AssembleMultisectedGraph(ctrl_t *ctrl, graph_t *graph) { idx_t i, j, k, l, gnvtxs, nvtxs, gnedges, nedges, gsize; idx_t *xadj, *vwgt, *where, *adjncy, *adjwgt, *vtxdist, *imap; idx_t *axadj, *aadjncy, *aadjwgt, *avwgt, *awhere, *alabel; idx_t *mygraph, *ggraph; idx_t *recvcounts, *displs, mysize; graph_t *agraph; WCOREPUSH; gnvtxs = graph->gnvtxs; nvtxs = graph->nvtxs; nedges = graph->xadj[nvtxs]; xadj = graph->xadj; vwgt = graph->vwgt; where = graph->where; adjncy = graph->adjncy; adjwgt = graph->adjwgt; vtxdist = graph->vtxdist; imap = graph->imap; /* Determine the # of idx_t to receive from each processor */ recvcounts = iwspacemalloc(ctrl, ctrl->npes); mysize = 3*nvtxs + 2*nedges; gkMPI_Allgather((void *)(&mysize), 1, IDX_T, (void *)recvcounts, 1, IDX_T, ctrl->comm); displs = iwspacemalloc(ctrl, ctrl->npes+1); for (displs[0]=0, i=1; i<ctrl->npes+1; i++) displs[i] = displs[i-1] + recvcounts[i-1]; /* allocate memory for the recv buffer of the assembled graph */ gsize = displs[ctrl->npes]; ggraph = iwspacemalloc(ctrl, gsize); /* Construct the one-array storage format of the assembled graph */ WCOREPUSH; /* for freeing mygraph */ mygraph = iwspacemalloc(ctrl, mysize); for (k=i=0; i<nvtxs; i++) { mygraph[k++] = xadj[i+1]-xadj[i]; mygraph[k++] = vwgt[i]; mygraph[k++] = where[i]; for (j=xadj[i]; j<xadj[i+1]; j++) { mygraph[k++] = imap[adjncy[j]]; mygraph[k++] = adjwgt[j]; } } PASSERT(ctrl, mysize == k); /* Assemble the entire graph */ gkMPI_Allgatherv((void *)mygraph, mysize, IDX_T, (void *)ggraph, recvcounts, displs, IDX_T, ctrl->comm); WCOREPOP; /* free mygraph */ agraph = CreateGraph(); agraph->nvtxs = gnvtxs; agraph->ncon = 1; agraph->nedges = gnedges = (gsize-3*gnvtxs)/2; /* Allocate memory for the assembled graph */ axadj = agraph->xadj = imalloc(gnvtxs+1, "AssembleGraph: axadj"); avwgt = agraph->vwgt = imalloc(gnvtxs, "AssembleGraph: avwgt"); awhere = agraph->where = imalloc(gnvtxs, "AssembleGraph: awhere"); aadjncy = agraph->adjncy = imalloc(gnedges, "AssembleGraph: adjncy"); aadjwgt = agraph->adjwgt = imalloc(gnedges, "AssembleGraph: adjwgt"); alabel = agraph->label = imalloc(gnvtxs, "AssembleGraph: alabel"); for (k=j=i=0; i<gnvtxs; i++) { axadj[i] = ggraph[k++]; avwgt[i] = ggraph[k++]; awhere[i] = ggraph[k++]; for (l=0; l<axadj[i]; l++) { aadjncy[j] = ggraph[k++]; aadjwgt[j] = ggraph[k++]; j++; } } /* Now fix up the received graph */ MAKECSR(i, gnvtxs, axadj); iincset(gnvtxs, 0, alabel); WCOREPOP; return agraph; }
8,484
33.076305
103
c
null
ParMETIS-main/conf/check_thread_storage.c
extern __thread int x; int main(int argc, char **argv) { return 0; }
72
11.166667
33
c
null
ParMETIS-main/programs/adaptgraph.c
/* * Copyright 1998, Regents of the University of Minnesota * * tstadpt.c * * This file contains code for testing teh adaptive partitioning routines * * Started 5/19/97 * George * * $Id: adaptgraph.c,v 1.2 2003/07/21 17:50:22 karypis Exp $ * */ #include <parmetisbin.h> /************************************************************************* * This function implements a simple graph adaption strategy. **************************************************************************/ void AdaptGraph(graph_t *graph, idx_t afactor, MPI_Comm comm) { idx_t i, nvtxs, nadapt, firstvtx, lastvtx; idx_t npes, mype, mypwgt, max, min, sum; idx_t *vwgt, *xadj, *adjncy, *adjwgt, *perm; gkMPI_Comm_size(comm, &npes); gkMPI_Comm_rank(comm, &mype); srand(mype*afactor); nvtxs = graph->nvtxs; xadj = graph->xadj; adjncy = graph->adjncy; if (graph->adjwgt == NULL) adjwgt = graph->adjwgt = ismalloc(graph->nedges, 1, "AdaptGraph: adjwgt"); else adjwgt = graph->adjwgt; vwgt = graph->vwgt; firstvtx = graph->vtxdist[mype]; lastvtx = graph->vtxdist[mype+1]; perm = imalloc(nvtxs, "AdaptGraph: perm"); FastRandomPermute(nvtxs, perm, 1); nadapt = RandomInRange(nvtxs); nadapt = RandomInRange(nvtxs); nadapt = RandomInRange(nvtxs); for (i=0; i<nadapt; i++) vwgt[perm[i]] = afactor*vwgt[perm[i]]; /* for (i=0; i<nvtxs; i++) { for (j=xadj[i]; j<xadj[i+1]; j++) { k = adjncy[j]; if (k >= firstvtx && k < lastvtx) { adjwgt[j] = (int)pow(1.0*(gk_min(vwgt[i],vwgt[k-firstvtx])), .6667); if (adjwgt[j] == 0) adjwgt[j] = 1; } } } */ mypwgt = isum(nvtxs, vwgt, 1); MPI_Allreduce((void *)&mypwgt, (void *)&max, 1, IDX_T, MPI_MAX, comm); MPI_Allreduce((void *)&mypwgt, (void *)&min, 1, IDX_T, MPI_MIN, comm); MPI_Allreduce((void *)&mypwgt, (void *)&sum, 1, IDX_T, MPI_SUM, comm); if (mype == 0) printf("Initial Load Imbalance: %5.4"PRREAL", [%5"PRIDX" %5"PRIDX" %5"PRIDX"] for afactor: %"PRIDX"\n", (1.0*max*npes)/(1.0*sum), min, max, sum, afactor); free(perm); } /************************************************************************* * This function implements a simple graph adaption strategy. **************************************************************************/ void AdaptGraph2(graph_t *graph, idx_t afactor, MPI_Comm comm) { idx_t i, j, k, nvtxs, firstvtx, lastvtx; idx_t npes, mype, mypwgt, max, min, sum; idx_t *vwgt, *xadj, *adjncy, *adjwgt; gkMPI_Comm_size(comm, &npes); gkMPI_Comm_rank(comm, &mype); srand(mype*afactor); nvtxs = graph->nvtxs; xadj = graph->xadj; adjncy = graph->adjncy; if (graph->adjwgt == NULL) adjwgt = graph->adjwgt = ismalloc(graph->nedges, 1, "AdaptGraph: adjwgt"); else adjwgt = graph->adjwgt; vwgt = graph->vwgt; firstvtx = graph->vtxdist[mype]; lastvtx = graph->vtxdist[mype+1]; /* if (RandomInRange(npes+1) < .05*npes) { */ if (RandomInRange(npes+1) < 2) { printf("[%"PRIDX"] is adapting\n", mype); for (i=0; i<nvtxs; i++) vwgt[i] = afactor*vwgt[i]; } for (i=0; i<nvtxs; i++) { for (j=xadj[i]; j<xadj[i+1]; j++) { k = adjncy[j]; if (k >= firstvtx && k < lastvtx) { adjwgt[j] = (int)pow(1.0*(gk_min(vwgt[i],vwgt[k-firstvtx])), .6667); if (adjwgt[j] == 0) adjwgt[j] = 1; } } } mypwgt = isum(nvtxs, vwgt, 1); gkMPI_Allreduce((void *)&mypwgt, (void *)&max, 1, IDX_T, MPI_MAX, comm); gkMPI_Allreduce((void *)&mypwgt, (void *)&min, 1, IDX_T, MPI_MIN, comm); gkMPI_Allreduce((void *)&mypwgt, (void *)&sum, 1, IDX_T, MPI_SUM, comm); if (mype == 0) printf("Initial Load Imbalance: %5.4"PRREAL", [%5"PRIDX" %5"PRIDX" %5"PRIDX"]\n", (1.0*max*npes)/(1.0*sum), min, max, sum); } /************************************************************************* * This function implements a simple graph adaption strategy. **************************************************************************/ void Mc_AdaptGraph(graph_t *graph, idx_t *part, idx_t ncon, idx_t nparts, MPI_Comm comm) { idx_t h, i; idx_t nvtxs; idx_t npes, mype; idx_t *vwgt, *pwgts; gkMPI_Comm_size(comm, &npes); gkMPI_Comm_rank(comm, &mype); nvtxs = graph->nvtxs; vwgt = graph->vwgt; pwgts = ismalloc(nparts*ncon, 1, "pwgts"); if (mype == 0) { for (i=0; i<nparts; i++) for (h=0; h<ncon; h++) pwgts[i*ncon+h] = RandomInRange(20)+1; } MPI_Bcast((void *)pwgts, nparts*ncon, IDX_T, 0, comm); for (i=0; i<nvtxs; i++) for (h=0; h<ncon; h++) vwgt[i*ncon+h] = pwgts[part[i]*ncon+h]; free(pwgts); return; }
4,617
26.005848
158
c
null
ParMETIS-main/programs/parmetisbin.h
/* * Copyright 1997, Regents of the University of Minnesota * * par_metis.h * * This file includes all necessary header files * * Started 8/27/94 * George * * $Id: parmetisbin.h,v 1.1 2003/07/21 17:50:23 karypis Exp $ */ /* #define DEBUG 1 #define DMALLOC 1 */ #include <GKlib.h> #include <parmetis.h> #include "../libparmetis/gklib_defs.h" #include "../libparmetis/rename.h" #include "../libparmetis/defs.h" #include "../libparmetis/struct.h" #include "../libparmetis/macros.h" #include "../libparmetis/proto.h" #include "proto.h" #define MAXNCON 32
579
17.125
61
h
null
ParMETIS-main/programs/ptest.c
/* * Copyright 1997, Regents of the University of Minnesota * * main.c * * This file contains code for testing teh adaptive partitioning routines * * Started 5/19/97 * George * * $Id: ptest.c,v 1.3 2003/07/22 21:47:20 karypis Exp $ * */ #include <parmetisbin.h> #define NCON 5 /*************************************************************************/ /*! Entry point of the testing routine */ /*************************************************************************/ int main(int argc, char *argv[]) { idx_t mype, npes; MPI_Comm comm; MPI_Init(&argc, &argv); MPI_Comm_dup(MPI_COMM_WORLD, &comm); gkMPI_Comm_size(comm, &npes); gkMPI_Comm_rank(comm, &mype); if (argc != 2 && argc != 3) { if (mype == 0) printf("Usage: %s <graph-file> [coord-file]\n", argv[0]); MPI_Finalize(); exit(0); } TestParMetis_GPart(argv[1], (argc == 3 ? argv[2] : NULL), comm); gkMPI_Comm_free(&comm); MPI_Finalize(); return 0; } /***********************************************************************************/ /*! This function tests the various graph partitioning and ordering routines */ /***********************************************************************************/ void TestParMetis_GPart(char *filename, char *xyzfile, MPI_Comm comm) { idx_t ncon, nparts, npes, mype, opt2, realcut; graph_t graph, mgraph; idx_t *part, *mpart, *savepart, *order, *sizes; idx_t numflag=0, wgtflag=0, options[10], edgecut, ndims; real_t ipc2redist, *xyz=NULL, *tpwgts = NULL, ubvec[MAXNCON]; gkMPI_Comm_size(comm, &npes); gkMPI_Comm_rank(comm, &mype); ParallelReadGraph(&graph, filename, comm); if (xyzfile) xyz = ReadTestCoordinates(&graph, xyzfile, &ndims, comm); gkMPI_Barrier(comm); part = imalloc(graph.nvtxs, "TestParMetis_V3: part"); tpwgts = rmalloc(MAXNCON*npes*2, "TestParMetis_V3: tpwgts"); rset(MAXNCON, 1.05, ubvec); graph.vwgt = ismalloc(graph.nvtxs*5, 1, "TestParMetis_GPart: vwgt"); /*====================================================================== / ParMETIS_V3_PartKway /=======================================================================*/ options[0] = 1; options[1] = 3; options[2] = 1; wgtflag = 2; numflag = 0; edgecut = 0; for (nparts=2*npes; nparts>=npes/2 && nparts > 0; nparts = nparts/2) { for (ncon=1; ncon<=NCON; ncon++) { if (ncon > 1 && nparts > 1) Mc_AdaptGraph(&graph, part, ncon, nparts, comm); else iset(graph.nvtxs, 1, graph.vwgt); if (mype == 0) printf("\nTesting ParMETIS_V3_PartKway with ncon: %"PRIDX", nparts: %"PRIDX"\n", ncon, nparts); rset(nparts*ncon, 1.0/(real_t)nparts, tpwgts); ParMETIS_V3_PartKway(graph.vtxdist, graph.xadj, graph.adjncy, graph.vwgt, NULL, &wgtflag, &numflag, &ncon, &nparts, tpwgts, ubvec, options, &edgecut, part, &comm); realcut = ComputeRealCut(graph.vtxdist, part, filename, comm); if (mype == 0) { printf("ParMETIS_V3_PartKway reported a cut of %"PRIDX" [%s:%"PRIDX"]\n", edgecut, (edgecut == realcut ? "OK" : "ERROR"), realcut); } if (mype == 0) printf("\nTesting ParMETIS_V3_RefineKway with ncon: %"PRIDX", nparts: %"PRIDX"\n", ncon, nparts); options[3] = PARMETIS_PSR_UNCOUPLED; ParMETIS_V3_RefineKway(graph.vtxdist, graph.xadj, graph.adjncy, graph.vwgt, NULL, &wgtflag, &numflag, &ncon, &nparts, tpwgts, ubvec, options, &edgecut, part, &comm); realcut = ComputeRealCut(graph.vtxdist, part, filename, comm); if (mype == 0) { printf("ParMETIS_V3_RefineKway reported a cut of %"PRIDX" [%s:%"PRIDX"]\n", edgecut, (edgecut == realcut ? "OK" : "ERROR"), realcut); } } } /*====================================================================== / ParMETIS_V3_PartGeomKway /=======================================================================*/ if (xyzfile != NULL) { options[0] = 1; options[1] = 3; options[2] = 1; wgtflag = 2; numflag = 0; for (nparts=2*npes; nparts>=npes/2 && nparts > 0; nparts = nparts/2) { for (ncon=1; ncon<=NCON; ncon++) { if (ncon > 1) Mc_AdaptGraph(&graph, part, ncon, nparts, comm); else iset(graph.nvtxs, 1, graph.vwgt); if (mype == 0) printf("\nTesting ParMETIS_V3_PartGeomKway with ncon: %"PRIDX", nparts: %"PRIDX"\n", ncon, nparts); rset(nparts*ncon, 1.0/(real_t)nparts, tpwgts); ParMETIS_V3_PartGeomKway(graph.vtxdist, graph.xadj, graph.adjncy, graph.vwgt, NULL, &wgtflag, &numflag, &ndims, xyz, &ncon, &nparts, tpwgts, ubvec, options, &edgecut, part, &comm); realcut = ComputeRealCut(graph.vtxdist, part, filename, comm); if (mype == 0) printf("ParMETIS_V3_PartGeomKway reported a cut of %"PRIDX" [%s:%"PRIDX"]\n", edgecut, (edgecut == realcut ? "OK" : "ERROR"), realcut); } } } /*====================================================================== / ParMETIS_V3_PartGeom /=======================================================================*/ if (xyz != NULL) { wgtflag = 0; numflag = 0; if (mype == 0) printf("\nTesting ParMETIS_V3_PartGeom\n"); ParMETIS_V3_PartGeom(graph.vtxdist, &ndims, xyz, part, &comm); realcut = ComputeRealCut(graph.vtxdist, part, filename, comm); if (mype == 0) printf("ParMETIS_V3_PartGeom reported a cut of %"PRIDX"\n", realcut); } /*====================================================================== / Coupled ParMETIS_V3_RefineKway /=======================================================================*/ options[0] = 1; options[1] = 3; options[2] = 1; options[3] = PARMETIS_PSR_COUPLED; nparts = npes; wgtflag = 0; numflag = 0; ncon = 1; rset(nparts*ncon, 1.0/(real_t)nparts, tpwgts); if (mype == 0) printf("\nTesting coupled ParMETIS_V3_RefineKway with default options (before move)\n"); ParMETIS_V3_RefineKway(graph.vtxdist, graph.xadj, graph.adjncy, NULL, NULL, &wgtflag, &numflag, &ncon, &nparts, tpwgts, ubvec, options, &edgecut, part, &comm); /* Compute a good partition and move the graph. Do so quietly! */ options[0] = 0; nparts = npes; wgtflag = 0; numflag = 0; ncon = 1; rset(nparts*ncon, 1.0/(real_t)nparts, tpwgts); ParMETIS_V3_PartKway(graph.vtxdist, graph.xadj, graph.adjncy, NULL, NULL, &wgtflag, &numflag, &ncon, &npes, tpwgts, ubvec, options, &edgecut, part, &comm); TestMoveGraph(&graph, &mgraph, part, comm); gk_free((void **)&(graph.vwgt), LTERM); mpart = ismalloc(mgraph.nvtxs, mype, "TestParMetis_V3: mpart"); savepart = imalloc(mgraph.nvtxs, "TestParMetis_V3: savepart"); /*====================================================================== / Coupled ParMETIS_V3_RefineKway /=======================================================================*/ options[0] = 1; options[1] = 3; options[2] = 1; options[3] = PARMETIS_PSR_COUPLED; nparts = npes; wgtflag = 0; numflag = 0; for (ncon=1; ncon<=NCON; ncon++) { if (mype == 0) printf("\nTesting coupled ParMETIS_V3_RefineKway with ncon: %"PRIDX", nparts: %"PRIDX"\n", ncon, nparts); rset(nparts*ncon, 1.0/(real_t)nparts, tpwgts); ParMETIS_V3_RefineKway(mgraph.vtxdist, mgraph.xadj, mgraph.adjncy, NULL, NULL, &wgtflag, &numflag, &ncon, &nparts, tpwgts, ubvec, options, &edgecut, mpart, &comm); realcut = ComputeRealCutFromMoved(graph.vtxdist, mgraph.vtxdist, part, mpart, filename, comm); if (mype == 0) printf("ParMETIS_V3_RefineKway reported a cut of %"PRIDX" [%s:%"PRIDX"]\n", edgecut, (edgecut == realcut ? "OK" : "ERROR"), realcut); } /*ADAPTIVE:*/ /*====================================================================== / ParMETIS_V3_AdaptiveRepart /=======================================================================*/ mgraph.vwgt = ismalloc(mgraph.nvtxs*NCON, 1, "TestParMetis_V3: mgraph.vwgt"); mgraph.vsize = ismalloc(mgraph.nvtxs, 1, "TestParMetis_V3: mgraph.vsize"); AdaptGraph(&mgraph, 4, comm); options[0] = 1; options[1] = 7; options[2] = 1; options[3] = PARMETIS_PSR_COUPLED; wgtflag = 2; numflag = 0; for (nparts=2*npes; nparts>=npes/2; nparts = nparts/2) { options[0] = 0; ncon = 1; wgtflag = 0; rset(nparts*ncon, 1.0/(real_t)nparts, tpwgts); ParMETIS_V3_PartKway(mgraph.vtxdist, mgraph.xadj, mgraph.adjncy, NULL, NULL, &wgtflag, &numflag, &ncon, &nparts, tpwgts, ubvec, options, &edgecut, savepart, &comm); options[0] = 1; wgtflag = 2; for (ncon=1; ncon<=NCON; ncon++) { rset(nparts*ncon, 1.0/(real_t)nparts, tpwgts); if (ncon > 1) Mc_AdaptGraph(&mgraph, savepart, ncon, nparts, comm); else AdaptGraph(&mgraph, 4, comm); for (ipc2redist=1000.0; ipc2redist>=0.001; ipc2redist/=1000.0) { icopy(mgraph.nvtxs, savepart, mpart); if (mype == 0) printf("\nTesting ParMETIS_V3_AdaptiveRepart with ipc2redist: %.3"PRREAL", ncon: %"PRIDX", nparts: %"PRIDX"\n", ipc2redist, ncon, nparts); ParMETIS_V3_AdaptiveRepart(mgraph.vtxdist, mgraph.xadj, mgraph.adjncy, mgraph.vwgt, mgraph.vsize, NULL, &wgtflag, &numflag, &ncon, &nparts, tpwgts, ubvec, &ipc2redist, options, &edgecut, mpart, &comm); realcut = ComputeRealCutFromMoved(graph.vtxdist, mgraph.vtxdist, part, mpart, filename, comm); if (mype == 0) printf("ParMETIS_V3_AdaptiveRepart reported a cut of %"PRIDX" [%s:%"PRIDX"]\n", edgecut, (edgecut == realcut ? "OK" : "ERROR"), realcut); } } } gk_free((void **)&tpwgts, &part, &mpart, &savepart, &xyz, &mgraph.vwgt, &mgraph.vsize, LTERM); } /******************************************************************************/ /*! This function takes a partition vector that is distributed and reads in the original graph and computes the edgecut */ /******************************************************************************/ idx_t ComputeRealCut(idx_t *vtxdist, idx_t *part, char *filename, MPI_Comm comm) { idx_t i, j, nvtxs, mype, npes, cut; idx_t *xadj, *adjncy, *gpart; MPI_Status status; gkMPI_Comm_size(comm, &npes); gkMPI_Comm_rank(comm, &mype); if (mype != 0) { gkMPI_Send((void *)part, vtxdist[mype+1]-vtxdist[mype], IDX_T, 0, 1, comm); } else { /* Processor 0 does all the rest */ gpart = imalloc(vtxdist[npes], "ComputeRealCut: gpart"); icopy(vtxdist[1], part, gpart); for (i=1; i<npes; i++) gkMPI_Recv((void *)(gpart+vtxdist[i]), vtxdist[i+1]-vtxdist[i], IDX_T, i, 1, comm, &status); ReadMetisGraph(filename, &nvtxs, &xadj, &adjncy); /* OK, now compute the cut */ for (cut=0, i=0; i<nvtxs; i++) { for (j=xadj[i]; j<xadj[i+1]; j++) { if (gpart[i] != gpart[adjncy[j]]) cut++; } } cut = cut/2; gk_free((void **)&gpart, &xadj, &adjncy, LTERM); return cut; } return 0; } /******************************************************************************/ /*! This function takes a partition vector of the original graph and that of the moved graph and computes the cut of the original graph based on the moved graph */ /*******************************************************************************/ idx_t ComputeRealCutFromMoved(idx_t *vtxdist, idx_t *mvtxdist, idx_t *part, idx_t *mpart, char *filename, MPI_Comm comm) { idx_t i, j, nvtxs, mype, npes, cut; idx_t *xadj, *adjncy, *gpart, *gmpart, *perm, *sizes; MPI_Status status; gkMPI_Comm_size(comm, &npes); gkMPI_Comm_rank(comm, &mype); if (mype != 0) { gkMPI_Send((void *)part, vtxdist[mype+1]-vtxdist[mype], IDX_T, 0, 1, comm); gkMPI_Send((void *)mpart, mvtxdist[mype+1]-mvtxdist[mype], IDX_T, 0, 1, comm); } else { /* Processor 0 does all the rest */ gpart = imalloc(vtxdist[npes], "ComputeRealCut: gpart"); icopy(vtxdist[1], part, gpart); gmpart = imalloc(mvtxdist[npes], "ComputeRealCut: gmpart"); icopy(mvtxdist[1], mpart, gmpart); for (i=1; i<npes; i++) { gkMPI_Recv((void *)(gpart+vtxdist[i]), vtxdist[i+1]-vtxdist[i], IDX_T, i, 1, comm, &status); gkMPI_Recv((void *)(gmpart+mvtxdist[i]), mvtxdist[i+1]-mvtxdist[i], IDX_T, i, 1, comm, &status); } /* OK, now go and reconstruct the permutation to go from the graph to mgraph */ perm = imalloc(vtxdist[npes], "ComputeRealCut: perm"); sizes = ismalloc(npes+1, 0, "ComputeRealCut: sizes"); for (i=0; i<vtxdist[npes]; i++) sizes[gpart[i]]++; MAKECSR(i, npes, sizes); for (i=0; i<vtxdist[npes]; i++) perm[i] = sizes[gpart[i]]++; /* Ok, now read the graph from the file */ ReadMetisGraph(filename, &nvtxs, &xadj, &adjncy); /* OK, now compute the cut */ for (cut=0, i=0; i<nvtxs; i++) { for (j=xadj[i]; j<xadj[i+1]; j++) { if (gmpart[perm[i]] != gmpart[perm[adjncy[j]]]) cut++; } } cut = cut/2; gk_free((void **)&gpart, &gmpart, &perm, &sizes, &xadj, &adjncy, LTERM); return cut; } return 0; } /****************************************************************************** * This function takes a graph and its partition vector and creates a new * graph corresponding to the one after the movement *******************************************************************************/ void TestMoveGraph(graph_t *ograph, graph_t *omgraph, idx_t *part, MPI_Comm comm) { idx_t npes, mype; ctrl_t *ctrl; graph_t *graph, *mgraph; idx_t options[5] = {0, 0, 1, 0, 0}; gkMPI_Comm_size(comm, &npes); ctrl = SetupCtrl(PARMETIS_OP_KMETIS, NULL, 1, npes, NULL, NULL, comm); mype = ctrl->mype; ctrl->CoarsenTo = 1; /* Needed by SetUpGraph, otherwise we can FP errors */ graph = TestSetUpGraph(ctrl, ograph->vtxdist, ograph->xadj, NULL, ograph->adjncy, NULL, 0); AllocateWSpace(ctrl, 0); CommSetup(ctrl, graph); graph->where = part; graph->ncon = 1; mgraph = MoveGraph(ctrl, graph); omgraph->gnvtxs = mgraph->gnvtxs; omgraph->nvtxs = mgraph->nvtxs; omgraph->nedges = mgraph->nedges; omgraph->vtxdist = mgraph->vtxdist; omgraph->xadj = mgraph->xadj; omgraph->adjncy = mgraph->adjncy; mgraph->vtxdist = NULL; mgraph->xadj = NULL; mgraph->adjncy = NULL; FreeGraph(mgraph); graph->where = NULL; FreeInitialGraphAndRemap(graph); FreeCtrl(&ctrl); } /***************************************************************************** * This function sets up a graph data structure for partitioning *****************************************************************************/ graph_t *TestSetUpGraph(ctrl_t *ctrl, idx_t *vtxdist, idx_t *xadj, idx_t *vwgt, idx_t *adjncy, idx_t *adjwgt, idx_t wgtflag) { return SetupGraph(ctrl, 1, vtxdist, xadj, vwgt, NULL, adjncy, adjwgt, wgtflag); }
15,095
31.746204
122
c
null
ParMETIS-main/programs/proto.h
/* * Copyright 1997, Regents of the University of Minnesota * * proto.h * * This file contains header files * * Started 10/19/95 * George * * $Id: proto.h 10076 2011-06-03 15:36:39Z karypis $ * */ /* pio.c */ void ParallelReadGraph(graph_t *, char *, MPI_Comm); void Mc_ParallelWriteGraph(ctrl_t *, graph_t *, char *, idx_t, idx_t); void ReadTestGraph(graph_t *, char *, MPI_Comm); real_t *ReadTestCoordinates(graph_t *, char *, idx_t *, MPI_Comm); void ReadMetisGraph(char *, idx_t *, idx_t **, idx_t **); void Mc_SerialReadGraph(graph_t *, char *, idx_t *, MPI_Comm); void Mc_SerialReadMetisGraph(char *, idx_t *, idx_t *, idx_t *, idx_t *, idx_t **, idx_t **, idx_t **, idx_t **, idx_t *); void WritePVector(char *gname, idx_t *vtxdist, idx_t *part, MPI_Comm comm); void WriteOVector(char *gname, idx_t *vtxdist, idx_t *order, MPI_Comm comm); /* adaptgraph */ void AdaptGraph(graph_t *, idx_t, MPI_Comm); void AdaptGraph2(graph_t *, idx_t, MPI_Comm); void Mc_AdaptGraph(graph_t *, idx_t *, idx_t, idx_t, MPI_Comm); /* ptest.c */ void TestParMetis_GPart(char *filename, char *xyzfile, MPI_Comm comm); idx_t ComputeRealCut(idx_t *, idx_t *, char *, MPI_Comm); idx_t ComputeRealCutFromMoved(idx_t *, idx_t *, idx_t *, idx_t *, char *, MPI_Comm); void TestMoveGraph(graph_t *, graph_t *, idx_t *, MPI_Comm); graph_t *TestSetUpGraph(ctrl_t *, idx_t *, idx_t *, idx_t *, idx_t *, idx_t *, idx_t); /* mienio.c */ void mienIO(mesh_t *, char *, idx_t, idx_t, MPI_Comm); /* meshio.c */ void ParallelReadMesh(mesh_t *, char *, MPI_Comm);
1,553
30.714286
122
h
null
ParMETIS-main/programs/dglpart.c
/* * dglpart.c * * This file partitions a graph for use in DistDGL * * Started 12/31/2020 * George * */ #include <parmetisbin.h> #define CHUNKSIZE (1<<15) /* The following is to perform a cyclic distribution of the input vertex IDs in order to balance the adjancency lists during the partitioning computations */ /* (u%npes)*lnvtxs + u/npes */ #define ToCyclicMap(id, nbuckets, bucketsize) \ (((id)%(nbuckets))*(bucketsize) + (id)/(nbuckets)) /* #define ToCyclicMap(id, nbuckets, bucketdist) \ ((bucketdist)[(id)%(nbuckets)] + (id)/(nbuckets)) */ /* (u%lnvtxs)*npes + u/lnvtxs */ #define FromCyclicMap(id, nbuckets, bucketsize) \ (((id)%(bucketsize))*(nbuckets) + (id)/(bucketsize)) /*! The structure that contains size-information of types of moved data */ typedef struct mvinfo_t { idx_t nvtxs; /*!< The number of vertices to move */ idx_t nedges; /*!< The number of edges to move */ idx_t nvmdata; /*!< The #of idx_t-equivalent of vertex metadata */ idx_t nemdata; /*!< The #of idx_t-equivalent of edge metadata */ } mvinfo_t; int DistDGL_GPart(char *fstem, idx_t nparts_per_pe, MPI_Comm comm); graph_t *DistDGL_ReadGraph(char *fstem, MPI_Comm comm); graph_t *DistDGL_MoveGraph(graph_t *ograph, idx_t *part, idx_t nparts_per_pe, MPI_Comm comm); void DistDGL_CheckMGraph(ctrl_t *ctrl, graph_t *graph, idx_t nparts_per_pe); void i2kvsorti(size_t n, i2kv_t *base); void i2kvsortii(size_t n, i2kv_t *base); void DistDGL_WriteGraphs(char *fstem, graph_t *graph, idx_t nparts_per_pe, MPI_Comm comm); idx_t DistDGL_mapFromCyclic(idx_t u, idx_t npes, idx_t *vtxdist); idx_t DistDGL_mapToCyclic(idx_t u, idx_t npes, idx_t *vtxdist); /*************************************************************************/ /*! Entry point of the partitioning code */ /*************************************************************************/ int main(int argc, char *argv[]) { idx_t mype, npes; MPI_Comm comm; int retval; MPI_Init(&argc, &argv); MPI_Comm_dup(MPI_COMM_WORLD, &comm); gkMPI_Comm_size(comm, &npes); gkMPI_Comm_rank(comm, &mype); if (argc != 3) { if (mype == 0) printf("Usage: %s <fstem> <nparts-per-pe>\n", argv[0]); MPI_Finalize(); exit(0); } retval = DistDGL_GPart(argv[1], atoi(argv[2]), comm); gkMPI_Comm_free(&comm); MPI_Finalize(); return retval; } /*************************************************************************/ /*! Partition, move, and save the local graphs */ /*************************************************************************/ int DistDGL_GPart(char *fstem, idx_t nparts_per_pe, MPI_Comm comm) { idx_t i, npes, mype, nparts; graph_t *graph, *mgraph; idx_t *part; idx_t numflag=0, wgtflag=0, options[10], edgecut, ndims; real_t *tpwgts=NULL, *ubvec=NULL; gkMPI_Comm_size(comm, &npes); gkMPI_Comm_rank(comm, &mype); /* read and create the graph */ graph = DistDGL_ReadGraph(fstem, comm); gkMPI_Barrier(comm); if (graph == NULL) return EXIT_FAILURE; /* Report peak memory use before partitioning */ for (i=npes-1; i>=0; i--) { if (i == mype && mype == npes-1) printf("\n-------------------------------------------------------\n"); if (i == mype) printf("[%03"PRIDX"] proc/self/stat/VmPeak: %.2f MB\n", mype, (float)gk_GetProcVmPeak()/(1024.0*1024.0)); if (i == 0 && mype == 0) printf("-------------------------------------------------------\n"); fflush(stdout); gkMPI_Barrier(comm); } /*====================================================================== / Partition the graph /=======================================================================*/ options[0] = 1; options[1] = 15 + (PARMETIS_DBGLVL_TWOHOP|PARMETIS_DBGLVL_FAST|PARMETIS_DBGLVL_DROPEDGES|PARMETIS_DBGLVL_ONDISK); options[2] = 1; wgtflag = 2; numflag = 0; edgecut = 0; nparts = npes*nparts_per_pe; part = imalloc(graph->nvtxs, "DistDGL_GPart: part"); tpwgts = rsmalloc(nparts*graph->ncon, 1.0/(real_t)nparts, "DistDGL_GPart: tpwgts"); ubvec = rsmalloc(graph->ncon, 1.02, "DistDGL_GPart: unvec"); if (mype == 0) printf("\nDistDGL partitioning, ncon: %"PRIDX", nparts: %"PRIDX" [%s, %s, MPI %d.%d]\n", graph->ncon, nparts, (sizeof(idx_t)==8 ? "i64" : "i32"), (sizeof(real_t)==8 ? "r64" : "r32"), MPI_VERSION, MPI_SUBVERSION); ParMETIS_V3_PartKway(graph->vtxdist, graph->xadj, graph->adjncy, graph->vwgt, NULL, &wgtflag, &numflag, &(graph->ncon), &nparts, tpwgts, ubvec, options, &edgecut, part, &comm); /*====================================================================== / Move the graph based on the partitioning /=======================================================================*/ mgraph = DistDGL_MoveGraph(graph, part, nparts_per_pe, comm); /*====================================================================== / Write the different partitions to disk /=======================================================================*/ DistDGL_WriteGraphs(fstem, mgraph, nparts_per_pe, comm); /* Report peak memory use after partitioning */ for (i=npes-1; i>=0; i--) { if (i == mype && mype == npes-1) printf("\n-------------------------------------------------------\n"); if (i == mype) printf("[%03"PRIDX"] proc/self/stat/VmPeak: %.2f MB\n", mype, (float)gk_GetProcVmPeak()/(1024.0*1024.0)); if (i == 0 && mype == 0) printf("-------------------------------------------------------\n"); fflush(stdout); gkMPI_Barrier(comm); } return EXIT_SUCCESS; } /*************************************************************************/ /*! This function takes a graph and its partition vector and creates a new graph corresponding to the one after the movement */ /*************************************************************************/ graph_t *DistDGL_MoveGraph(graph_t *ograph, idx_t *part, idx_t nparts_per_pe, MPI_Comm comm) { idx_t npes, mype, nparts, idxwidth; ctrl_t *ctrl; idx_t h, i, ii, j, jj, k, nvtxs, nsnbrs, nrnbrs; idx_t *xadj, *adjncy, *mvtxdist; idx_t *where, *newlabel, *vtype, *lpwgts, *gpwgts; idx_t *sgraph, *rgraph; mvinfo_t *sinfo, *rinfo; graph_t *graph, *mgraph; idx_t *vmptr, *emptr; char *vmdata, *emdata; idx_t *iptr, ilen; idxwidth = sizeof(idx_t); gkMPI_Comm_size(comm, &npes); ctrl = SetupCtrl(PARMETIS_OP_KMETIS, NULL, 1, npes, NULL, NULL, comm); npes = ctrl->npes; mype = ctrl->mype; ctrl->CoarsenTo = 1; /* Needed by SetUpGraph, otherwise we can FP errors */ graph = SetupGraph(ctrl, 1, ograph->vtxdist, ograph->xadj, ograph->vwgt, ograph->vsize, ograph->adjncy, ograph->adjwgt, 0); AllocateWSpace(ctrl, 0); CommSetup(ctrl, graph); nparts = npes*nparts_per_pe; WCOREPUSH; /* read the metadata from the disk */ { size_t size; char filein[256]; sprintf(filein, "emdata-%d-%"PRIDX".bin", (int)getpid(), mype); ograph->emdata = gk_creadfilebin(filein, &size); if (size != ograph->emdata_size) printf("[%4"PRIDX"] size: %zu != %zu\n", mype, size, ograph->emdata_size); gk_rmpath(filein); sprintf(filein, "vmdata-%d-%"PRIDX".bin", (int)getpid(), mype); ograph->vmdata = gk_creadfilebin(filein, &size); if (size != ograph->vmdata_size) printf("[%4"PRIDX"] size: %zu != %zu\n", mype, size, ograph->vmdata_size); gk_rmpath(filein); } nvtxs = graph->nvtxs; xadj = graph->xadj; adjncy = graph->adjncy; where = part; vmptr = ograph->vmptr; emptr = ograph->emptr; vmdata = ograph->vmdata; emdata = ograph->emdata; vtype = ograph->vtype; mvtxdist = imalloc(nparts+1, "DistDGL_MoveGraph: mvtxdist"); /* Let's do a prefix scan to determine the labeling of the nodes given */ lpwgts = iwspacemalloc(ctrl, nparts+1); gpwgts = iwspacemalloc(ctrl, nparts+1); sinfo = (mvinfo_t *)iwspacemalloc(ctrl, nparts*sizeof(mvinfo_t)/idxwidth); rinfo = (mvinfo_t *)iwspacemalloc(ctrl, nparts*sizeof(mvinfo_t)/idxwidth); for (i=0; i<nparts; i++) sinfo[i].nvtxs = sinfo[i].nedges = sinfo[i].nvmdata = sinfo[i].nemdata = 0; for (i=0; i<nvtxs; i++) { sinfo[where[i]].nvtxs += 1; sinfo[where[i]].nedges += xadj[i+1]-xadj[i]; sinfo[where[i]].nvmdata += (vmptr[i+1]-vmptr[i])/idxwidth; /* vmdata */ for (j=xadj[i]; j<xadj[i+1]; j++) sinfo[where[i]].nemdata += (emptr[j+1]-emptr[j])/idxwidth; /* emdata */ } for (i=0; i<nparts; i++) lpwgts[i] = sinfo[i].nvtxs; gkMPI_Scan((void *)lpwgts, (void *)gpwgts, nparts, IDX_T, MPI_SUM, ctrl->comm); gkMPI_Allreduce((void *)lpwgts, (void *)mvtxdist, nparts, IDX_T, MPI_SUM, ctrl->comm); MAKECSR(i, nparts, mvtxdist); /* gpwgts[i] will store the label of the first vertex for each domain in each processor */ for (i=0; i<nparts; i++) /* We were interested in an exclusive scan */ gpwgts[i] = mvtxdist[i] + gpwgts[i] - lpwgts[i]; newlabel = iwspacemalloc(ctrl, nvtxs+graph->nrecv); for (i=0; i<nvtxs; i++) newlabel[i] = gpwgts[where[i]]++; /* Send the newlabel info to processors storing adjacent interface nodes */ CommInterfaceData(ctrl, graph, newlabel, newlabel+nvtxs); /* Tell everybody what and from where they will get it. */ gkMPI_Alltoall((void *)sinfo, nparts_per_pe*(sizeof(mvinfo_t)/idxwidth), IDX_T, (void *)rinfo, nparts_per_pe*(sizeof(mvinfo_t)/idxwidth), IDX_T, ctrl->comm); /* Use lpwgts/gpwgts as pointers to where data will be sent/received, respectively */ for (nsnbrs=0, i=0; i<nparts; i++) { lpwgts[i] = 3*sinfo[i].nvtxs + sinfo[i].nedges + sinfo[i].nvtxs + sinfo[i].nvmdata + sinfo[i].nedges + sinfo[i].nemdata ; if (sinfo[i].nvtxs > 0) nsnbrs++; } MAKECSR(i, nparts, lpwgts); //myprintf(ctrl, "lpwgts: %d %d %d\n", lpwgts[0], lpwgts[1], lpwgts[2]); /* The target locations are designed to pack in consecutive memory locations the different chunks of the subpartitions that are coming from the different processors. */ for (nrnbrs=0, k=0; k<nparts_per_pe; k++) { for (i=0; i<npes; i++) { gpwgts[k*npes+i] = 3*rinfo[i*nparts_per_pe+k].nvtxs + rinfo[i*nparts_per_pe+k].nedges + rinfo[i*nparts_per_pe+k].nvtxs + rinfo[i*nparts_per_pe+k].nvmdata + rinfo[i*nparts_per_pe+k].nedges + rinfo[i*nparts_per_pe+k].nemdata ; if (rinfo[i*nparts_per_pe+k].nvtxs > 0) nrnbrs++; } } MAKECSR(i, nparts, gpwgts); //myprintf(ctrl, "gpwgts: %d %d %d\n", gpwgts[0], gpwgts[1], gpwgts[2]); /* Update the max # of sreq/rreq/statuses */ CommUpdateNnbrs(ctrl, gk_max(nsnbrs, nrnbrs)); rgraph = iwspacemalloc(ctrl, gpwgts[nparts]); WCOREPUSH; /* for freeing the send part early */ sgraph = iwspacemalloc(ctrl, lpwgts[nparts]); /* Issue the receives first */ for (j=0, i=0; i<nparts; i++) { if (rinfo[i].nvtxs > 0) { //myprintf(ctrl, "[%"PRIDX"]Irecv from: %"PRIDX" tag: %"PRIDX"\n", i, i%npes, 1+i/nparts_per_pe); gkMPI_Irecv((void *)(rgraph+gpwgts[i]), gpwgts[i+1]-gpwgts[i], IDX_T, i%npes, 1+i/npes, ctrl->comm, ctrl->rreq+j++); } else PASSERT(ctrl, gpwgts[i+1]-gpwgts[i] == 0); } /* Assemble the graph to be sent and send it */ for (i=0; i<nvtxs; i++) { PASSERT(ctrl, where[i] >= 0 && where[i] < nparts); ii = lpwgts[where[i]]; sgraph[ii++] = xadj[i+1]-xadj[i]; sgraph[ii++] = where[i]; sgraph[ii++] = vtype[i]; for (j=xadj[i]; j<xadj[i+1]; j++) sgraph[ii++] = newlabel[adjncy[j]]; /* vertex metadata */ sgraph[ii++] = vmptr[i+1]-vmptr[i]; iptr = (idx_t *)(vmdata+vmptr[i]); ilen = (vmptr[i+1]-vmptr[i])/idxwidth; for (h=0; h<ilen; h++) sgraph[ii++] = iptr[h]; /* edge metadata */ for (j=xadj[i]; j<xadj[i+1]; j++) { sgraph[ii++] = emptr[j+1]-emptr[j]; iptr = (idx_t *)(emdata+emptr[j]); ilen = (emptr[j+1]-emptr[j])/idxwidth; for (h=0; h<ilen; h++) sgraph[ii++] = iptr[h]; } lpwgts[where[i]] = ii; } SHIFTCSR(i, nparts, lpwgts); //myprintf(ctrl, "lpwgts: %d %d %d\n", lpwgts[0], lpwgts[1], lpwgts[2]); for (j=0, i=0; i<nparts; i++) { if (sinfo[i].nvtxs > 0) { //myprintf(ctrl, "[%"PRIDX"]Send to: %"PRIDX" tag: %"PRIDX"\n", i, i/nparts_per_pe, 1+i%nparts_per_pe); gkMPI_Isend((void *)(sgraph+lpwgts[i]), lpwgts[i+1]-lpwgts[i], IDX_T, i/nparts_per_pe, 1+i%nparts_per_pe, ctrl->comm, ctrl->sreq+j++); } else PASSERT(ctrl, lpwgts[i+1]-lpwgts[i] == 0); } /* Wait for the send/recv to finish */ gkMPI_Waitall(nrnbrs, ctrl->rreq, ctrl->statuses); gkMPI_Waitall(nsnbrs, ctrl->sreq, ctrl->statuses); WCOREPOP; /* frees sgraph */ /* OK, now go and put the graph into graph_t Format */ mgraph = CreateGraph(); mgraph->vtxdist = mvtxdist; mgraph->gnvtxs = graph->gnvtxs; mgraph->ncon = 1; mgraph->level = 0; mgraph->nvtxs = mgraph->nedges = 0; idx_t nvmdata=0, nemdata=0; for (i=0; i<nparts; i++) { mgraph->nvtxs += rinfo[i].nvtxs; mgraph->nedges += rinfo[i].nedges; nvmdata += rinfo[i].nvmdata; nemdata += rinfo[i].nemdata; } nvtxs = mgraph->nvtxs; xadj = mgraph->xadj = imalloc(nvtxs+1, "MMG: mgraph->xadj"); adjncy = mgraph->adjncy = imalloc(mgraph->nedges, "MMG: mgraph->adjncy"); vmptr = mgraph->vmptr = imalloc(nvtxs+1, "MMG: mgraph->vmptr"); emptr = mgraph->emptr = imalloc(mgraph->nedges+1, "MMG: mgraph->emptr"); vmdata = mgraph->vmdata = gk_cmalloc(nvmdata*idxwidth, "MMG: mgraph->vmdata"); emdata = mgraph->emdata = gk_cmalloc(nemdata*idxwidth, "MMG: mgraph->emdata"); where = mgraph->where = imalloc(nvtxs, "MMG: mgraph->where"); vtype = mgraph->vtype = imalloc(nvtxs, "MMG: mgraph->vtype"); idx_t *ivptr=(idx_t *)vmdata, *ieptr=(idx_t *)emdata; for (jj=ii=i=0; i<nvtxs; i++) { xadj[i] = rgraph[ii++]; where[i] = rgraph[ii++]; vtype[i] = rgraph[ii++]; for (j=0; j<xadj[i]; j++) adjncy[jj+j] = rgraph[ii++]; /* vertex metadata */ vmptr[i] = rgraph[ii++]; ilen = vmptr[i]/idxwidth; for (h=0; h<ilen; h++, ivptr++) *ivptr = rgraph[ii++]; /* edge metadata */ for (j=0; j<xadj[i]; j++) { emptr[jj+j] = rgraph[ii++]; ilen = emptr[jj+j]/idxwidth; for (h=0; h<ilen; h++, ieptr++) *ieptr = rgraph[ii++]; } jj += xadj[i]; ASSERT(where[i] >= mype*nparts_per_pe && where[i] < (mype+1)*nparts_per_pe); } MAKECSR(i, nvtxs, xadj); MAKECSR(i, nvtxs, vmptr); MAKECSR(i, mgraph->nedges, emptr); PASSERT(ctrl, jj == mgraph->nedges); PASSERT(ctrl, ii == gpwgts[nparts]); PASSERTP(ctrl, jj == mgraph->nedges, (ctrl, "%"PRIDX" %"PRIDX"\n", jj, mgraph->nedges)); PASSERTP(ctrl, ii == gpwgts[nparts], (ctrl, "%"PRIDX" %"PRIDX" %"PRIDX" %"PRIDX" %"PRIDX"\n", ii, gpwgts[nparts], jj, mgraph->nedges, nvtxs)); #ifdef DEBUG IFSET(ctrl->dbglvl, DBG_INFO, rprintf(ctrl, "Checking moved graph...\n")); DistDGL_CheckMGraph(ctrl, mgraph, nparts_per_pe); IFSET(ctrl->dbglvl, DBG_INFO, rprintf(ctrl, "Moved graph is consistent.\n")); #endif #ifdef XXX /* write the graph in stdout */ { idx_t u, v, i, j, pe; for (pe=0; pe<npes; pe++) { if (mype == pe) { for (i=0; i<mgraph->nvtxs; i++) { for (j=mgraph->xadj[i]; j<mgraph->xadj[i+1]; j++) { u = mgraph->vtxdist[mype*nparts_per_pe]+i; v = mgraph->adjncy[j]; printf("XXX%"PRIDX" [%"PRIDX" %"PRIDX"] vmdata: [%s] emdata: [%s]\n", mype, u, v, mgraph->vmdata+mgraph->vmptr[i], (mgraph->emptr[j+1]-mgraph->emptr[j] == 0 ? "NULL" : mgraph->emdata+mgraph->emptr[j])); } } fflush(stdout); } gkMPI_Barrier(comm); } } #endif WCOREPOP; graph->where = NULL; FreeInitialGraphAndRemap(graph); FreeCtrl(&ctrl); mgraph->where = where; return mgraph; } #ifdef XXXX /*************************************************************************/ /*! This function takes a graph and its partition vector and creates a new graph corresponding to the one after the movement */ /*************************************************************************/ DistDGL_TypePermute(graph_t *ograph, idx_t nparts_per_pe, MPI_Comm comm) { idx_t npes, mype, nparts; ctrl_t *ctrl; idx_t h, i, ii, j, jj, k, nvtxs; idx_t *xadj, *adjncy; idx_t *where, *newlabel, *vtype; graph_t *graph, *mgraph; idx_t *vmptr, *emptr; char *vmdata, *emdata; idx_t *iptr, ilen; i2kv_t *cand; idx_t *cvtxdist, *fvtxdist; fvtxdist = ograph->vtxdist; vmptr = ograph->vmptr; emptr = ograph->emptr; vmdata = ograph->vmdata; emdata = ograph->emdata; vtype = ograph->vtype; where = ograph->where; gkMPI_Comm_size(comm, &npes); ctrl = SetupCtrl(PARMETIS_OP_KMETIS, NULL, 1, npes, NULL, NULL, comm); mype = ctrl->mype; ctrl->CoarsenTo = 1; /* Needed by SetUpGraph, otherwise we can FP errors */ vtxdist = imalloc(npes+1, "DistDGL_TypePermute: vtxdist"); for (i=0; i<npes; i++) cvtxdist[i] = fvtxdist[(i+1)*nparts_per_pe]-fvtxdist[i*nparts_per_pe]; MAKECSR(i, npes, cvtxdist); graph = SetupGraph(ctrl, 1, cvtxdist, ograph->xadj, NULL, NULL, ograph->adjncy, NULL, 0); AllocateWSpace(ctrl, 0); CommSetup(ctrl, graph); nparts = npes*nparts_per_pe; WCOREPUSH; nvtxs = graph->nvtxs; xadj = graph->xadj; adjncy = graph->adjncy; cand = (i2kv_t *)iwspacemalloc(ctrl, nvtxs*sizeof(i2kv_t)/sizeof(idx_t)); for (i=0; i<nvtxs; i++) { cand[i].key1 = where[i]; cand[i].key2 = vtype[i]; cand[i].val = i; } i2kvsortii(nvtxs, cand); newlabel = iwspacemalloc(ctrl, nvtxs+graph->nrecv); for (i=0; i<nvtxs; i++) newlabel[cand[i].key3] = cvtxdist[mype]+i; /* Send the newlabel info to processors storing adjacent interface nodes */ CommInterfaceData(ctrl, graph, newlabel, newlabel+nvtxs); WCOREPOP; graph->where = NULL; FreeInitialGraphAndRemap(graph); FreeCtrl(&ctrl); } #endif /*************************************************************************/ /*! Checks the local consistency of moved graph. */ /*************************************************************************/ void DistDGL_CheckMGraph(ctrl_t *ctrl, graph_t *graph, idx_t nparts_per_pe) { idx_t i, j, jj, k, nvtxs, firstvtx, lastvtx; idx_t *xadj, *adjncy, *vtxdist; nvtxs = graph->nvtxs; xadj = graph->xadj; adjncy = graph->adjncy; vtxdist = graph->vtxdist; firstvtx = vtxdist[nparts_per_pe*ctrl->mype]; lastvtx = vtxdist[nparts_per_pe*ctrl->mype+1]; for (i=0; i<nvtxs; i++) { for (j=xadj[i]; j<xadj[i+1]; j++) { if (firstvtx+i == adjncy[j]) myprintf(ctrl, "(%"PRIDX" %"PRIDX") diagonal entry\n", i, i); if (adjncy[j] >= firstvtx && adjncy[j] < lastvtx) { k = adjncy[j]-firstvtx; for (jj=xadj[k]; jj<xadj[k+1]; jj++) { if (adjncy[jj] == firstvtx+i) break; } if (jj == xadj[k+1]) myprintf(ctrl, "(%"PRIDX" %"PRIDX") but not (%"PRIDX" %"PRIDX") [%"PRIDX" %"PRIDX"] [%"PRIDX" %"PRIDX"]\n", i, k, k, i, firstvtx+i, firstvtx+k, xadj[i+1]-xadj[i], xadj[k+1]-xadj[k]); } } } } /*************************************************************************/ /*! Reads, distributes, and pre-processes the DistDGL's input files to create the graph used for partitioning */ /*************************************************************************/ graph_t *DistDGL_ReadGraph(char *fstem, MPI_Comm comm) { idx_t i, j, pe, idxwidth; idx_t npes, mype, ier; graph_t *graph=NULL; idx_t gnvtxs, gnedges, nvtxs, ncon; idx_t *vtxdist, *xadj, *adjncy, *vwgt, *vtype; MPI_Status stat; ssize_t rlen, fsize; size_t lnlen=0; char *filename=NULL, *line=NULL; FILE *fpin=NULL; idxwidth = sizeof(idx_t); gkMPI_Comm_size(comm, &npes); gkMPI_Comm_rank(comm, &mype); /* check to see if the required files exist */ ier = 0; if (mype == 0) { filename = gk_malloc(100+strlen(fstem), "DistDGL_ReadGraph: filename"); sprintf(filename, "%s_stats.txt", fstem); if (!gk_fexists(filename)) { printf("ERROR: File '%s' does not exists.\n", filename); ier++; } sprintf(filename, "%s_edges.txt", fstem); if (!gk_fexists(filename)) { printf("ERROR: File '%s' does not exists.\n", filename); ier++; } sprintf(filename, "%s_nodes.txt", fstem); if (!gk_fexists(filename)) { printf("ERROR: File '%s' does not exists.\n", filename); ier++; } } if (GlobalSEMaxComm(comm, ier) > 0) goto ERROR_EXIT; /* get the basic statistics */ ier = 0; if (mype == 0) { sprintf(filename, "%s_stats.txt", fstem); fpin = gk_fopen(filename, "r", "DistDGL_ReadGraph: stats.txt"); if ((i = fscanf(fpin, "%"SCIDX" %"SCIDX" %"SCIDX, &gnvtxs, &gnedges, &ncon)) != 3) { printf("ERROR: File '%s' contains %"PRIDX"/3 required information.\n", filename, i); ier = 1; } } if (GlobalSEMaxComm(comm, ier) > 0) goto ERROR_EXIT; ncon++; /* the +1 is for the node type */ gkMPI_Bcast(&gnvtxs, 1, IDX_T, 0, comm); gkMPI_Bcast(&gnedges, 1, IDX_T, 0, comm); gkMPI_Bcast(&ncon, 1, IDX_T, 0, comm); printf("[%03"PRIDX"] gnvtxs: %"PRIDX", gnedges: %"PRIDX", ncon: %"PRIDX"\n", mype, gnvtxs, gnedges, ncon); /* ======================================================= */ /* setup the graph structure */ /* ======================================================= */ graph = CreateGraph(); graph->gnvtxs = gnvtxs; graph->ncon = ncon-1; vtxdist = graph->vtxdist = imalloc(npes+1, "DistDGL_ReadGraph: vtxdist"); for (pe=0; pe<npes; pe++) vtxdist[pe] = gnvtxs/npes + (pe < gnvtxs%npes ? 1 : 0); MAKECSR(i, npes, vtxdist); ASSERT(gnvtxs == vtxdist[npes]); nvtxs = graph->nvtxs = vtxdist[mype+1]-vtxdist[mype]; //printf("[%03"PRIDX"] nvtxs: %"PRIDX", vtxdist: %"PRIDX" %"PRIDX" %"PRIDX" %"PRIDX"\n", // mype, nvtxs, vtxdist[0], vtxdist[1], vtxdist[2], vtxdist[3]); /* ======================================================= */ /* read and distribute the edges and their metadata */ /* ======================================================= */ { idx_t u, v, uu, vv, nlinesread, nchunks, chunk, chunksize, lnedges, lnmeta; idx_t *coo_buffers_cpos=NULL, *coo_chunks_len=NULL; i2kv_t **coo_buffers=NULL, **coo_chunks=NULL, *lcoo=NULL; idx_t *meta_buffers_cpos=NULL, *meta_buffers_len=NULL, *meta_chunks_len=NULL; char **meta_buffers=NULL, **meta_chunks=NULL, *lmeta; idx_t *emptr; char *emdata; idx_t firstvtx, lastvtx; chunksize = CHUNKSIZE; nchunks = 2*gnedges/chunksize; nlinesread = 0; if (mype == 0) { sprintf(filename, "%s_edges.txt", fstem); fsize = 2*gk_getfsize(filename)/nchunks; /* give it a 2x xtra space */ fpin = gk_fopen(filename, "r", "DistDGL_ReadGraph: edges.txt"); coo_buffers_cpos = imalloc(npes, "coo_buffers_cpos"); meta_buffers_cpos = imalloc(npes, "meta_buflen_cpos"); meta_buffers_len = ismalloc(npes, fsize, "meta_buflen_len"); coo_buffers = (i2kv_t **)gk_malloc(npes*sizeof(i2kv_t *), "coo_buffers"); meta_buffers = (char **)gk_malloc(npes*sizeof(char *), "meta_buffers"); for (pe=0; pe<npes; pe++) { coo_buffers[pe] = (i2kv_t *)gk_malloc(chunksize*sizeof(i2kv_t), "coo_buffers[pe]"); meta_buffers[pe] = gk_cmalloc(meta_buffers_len[pe], "meta_buffers[pe]"); } } /* allocate memory for the chunks that will be collected by each PE */ coo_chunks_len = imalloc(nchunks, "coo_chunks_len"); meta_chunks_len = imalloc(nchunks, "meta_chunks_len"); coo_chunks = (i2kv_t **)gk_malloc(nchunks*sizeof(i2kv_t *), "coo_chunks"); meta_chunks = (char **)gk_malloc(nchunks*sizeof(char *), "meta_chunks"); /* if (mype == 0) { for (u=0; u<gnvtxs; u++) printf("%6d => %6d => %6d [ %2d %5d ]\n", u, DistDGL_mapToCyclic(u, npes, vtxdist), DistDGL_mapFromCyclic(DistDGL_mapToCyclic(u, npes, vtxdist), npes, vtxdist), u%npes, u/npes); } */ /* start reading the edge file */ for (chunk=0;;chunk++) { if (mype == 0) { iset(npes, 0, coo_buffers_cpos); iset(npes, 0, meta_buffers_cpos); nlinesread = 0; while (gk_getline(&line, &lnlen, fpin) != -1) { rlen = strlen(gk_strtprune(line, "\n\r")); nlinesread++; /* sscanf(line, "%"SCIDX" %"SCIDX, &uu, &vv); */ /* NOTE: The edges are read as (dest-id, source-id), as they are assigned to the partitions based on the dest-id; i.e., each partition stores the incoming edges */ sscanf(line, "%"SCIDX" %"SCIDX, &vv, &uu); u = vtxdist[uu%npes] + uu/npes; v = vtxdist[vv%npes] + vv/npes; ASSERT2(u < gnvtxs); ASSERT2(v < gnvtxs); /* record the edge in its input direction */ pe = uu%npes; coo_buffers[pe][coo_buffers_cpos[pe]].key1 = u; coo_buffers[pe][coo_buffers_cpos[pe]].key2 = v; coo_buffers[pe][coo_buffers_cpos[pe]].val = meta_buffers_cpos[pe]; coo_buffers_cpos[pe]++; /* see if you need to realloc the metadata buffer */ if (meta_buffers_cpos[pe]+rlen+1 >= meta_buffers_len[pe]) { meta_buffers_len[pe] += meta_buffers_len[pe] + rlen + 1; meta_buffers[pe] = gk_crealloc(meta_buffers[pe], meta_buffers_len[pe], "meta_buffers[pe]"); } gk_ccopy(rlen+1, line, meta_buffers[pe]+meta_buffers_cpos[pe]); meta_buffers_cpos[pe] += rlen + 1; /* record the edge in its oppositive direction */ pe = vv%npes; coo_buffers[pe][coo_buffers_cpos[pe]].key1 = v; coo_buffers[pe][coo_buffers_cpos[pe]].key2 = u; coo_buffers[pe][coo_buffers_cpos[pe]].val = -1; coo_buffers_cpos[pe]++; if (coo_buffers_cpos[uu%npes] >= chunksize || coo_buffers_cpos[vv%npes] >= chunksize) break; } } /* distributed termination detection */ if (GlobalSESumComm(comm, nlinesread) == 0) break; /* adjust memory if needed */ if (chunk >= nchunks) { //printf("[%03"PRIDX"] Readjusting nchunks: %"PRIDX"\n", mype, nchunks); nchunks *= 2; coo_chunks_len = irealloc(coo_chunks_len, nchunks, "coo_chunks_len"); meta_chunks_len = irealloc(meta_chunks_len, nchunks, "meta_chunks_len"); coo_chunks = (i2kv_t **)gk_realloc(coo_chunks, nchunks*sizeof(i2kv_t *), "coo_chunks"); meta_chunks = (char **)gk_realloc(meta_chunks, nchunks*sizeof(char *), "meta_chunks"); } if (mype == 0) { for (pe=1; pe<npes; pe++) { gkMPI_Send((void *)&(coo_buffers_cpos[pe]), 1, IDX_T, pe, 0, comm); gkMPI_Send((void *)&(meta_buffers_cpos[pe]), 1, IDX_T, pe, 0, comm); gkMPI_Send((void *)coo_buffers[pe], coo_buffers_cpos[pe]*sizeof(i2kv_t), MPI_BYTE, pe, 0, comm); gkMPI_Send((void *)meta_buffers[pe], meta_buffers_cpos[pe], MPI_CHAR, pe, 0, comm); } coo_chunks_len[chunk] = coo_buffers_cpos[0]; meta_chunks_len[chunk] = meta_buffers_cpos[0]; coo_chunks[chunk] = (i2kv_t *)gk_malloc(coo_chunks_len[chunk]*sizeof(i2kv_t), "coo_chunks[chunk]"); meta_chunks[chunk] = gk_cmalloc(meta_chunks_len[chunk], "meta_chunks[chunk]"); gk_ccopy(coo_buffers_cpos[0]*sizeof(i2kv_t), (char *)coo_buffers[0], (char *)coo_chunks[chunk]); gk_ccopy(meta_buffers_cpos[0], meta_buffers[0], meta_chunks[chunk]); //printf("[%03"PRIDX"] chunk: %"PRIDX", u:%"PRIDX", v:%"PRIDX", val:%s\n", // mype, chunk, coo_chunks[chunk][0].key1, coo_chunks[chunk][0].key2, // (coo_chunks[chunk][0].val == -1 ? "-1" : meta_chunks[chunk]+coo_chunks[chunk][0].val)); } else { gkMPI_Recv((void *)&(coo_chunks_len[chunk]), 1, IDX_T, 0, 0, comm, &stat); gkMPI_Recv((void *)&(meta_chunks_len[chunk]), 1, IDX_T, 0, 0, comm, &stat); coo_chunks[chunk] = (i2kv_t *)gk_malloc(coo_chunks_len[chunk]*sizeof(i2kv_t), "coo_chunks[chunk]"); meta_chunks[chunk] = gk_cmalloc(meta_chunks_len[chunk], "meta_chunks[chunk]"); gkMPI_Recv((void *)coo_chunks[chunk], coo_chunks_len[chunk]*sizeof(i2kv_t), MPI_BYTE, 0, 0, comm, &stat); gkMPI_Recv((void *)meta_chunks[chunk], meta_chunks_len[chunk], MPI_CHAR, 0, 0, comm, &stat); //printf("[%03"PRIDX"] chunk: %"PRIDX", u:%"PRIDX", v:%"PRIDX", val:%s\n", // mype, chunk, coo_chunks[chunk][0].key1, coo_chunks[chunk][0].key2, // (coo_chunks[chunk][0].val == -1 ? "-1" : meta_chunks[chunk]+coo_chunks[chunk][0].val)); } } nchunks = chunk; //printf("[%03"PRIDX"] Final nchunks: %"PRIDX"\n", mype, nchunks); /* done reading the edge file */ if (mype == 0) { gk_fclose(fpin); for (pe=0; pe<npes; pe++) gk_free((void **)&coo_buffers[pe], &meta_buffers[pe], LTERM); gk_free((void **)&coo_buffers_cpos, &meta_buffers_cpos, &meta_buffers_len, &coo_buffers, &meta_buffers, LTERM); } /* consolidate the chunks into lcoo/lmeta lnedges/lnmeta */ lnedges = isum(nchunks, coo_chunks_len, 1); lnmeta = isum(nchunks, meta_chunks_len, 1); //printf("[%03"PRIDX"] lnedges: %"PRIDX", lnmeta: %"PRIDX"\n", mype, lnedges, lnmeta); lcoo = (i2kv_t *)gk_malloc(sizeof(i2kv_t)*lnedges, "lcoo"); lmeta = gk_cmalloc(lnmeta, "lmeta"); lnedges = lnmeta = 0; for (chunk=0; chunk<nchunks; chunk++) { for (i=0; i<coo_chunks_len[chunk]; i++, lnedges++) { lcoo[lnedges] = coo_chunks[chunk][i]; if (lcoo[lnedges].val != -1) lcoo[lnedges].val += lnmeta; } gk_ccopy(meta_chunks_len[chunk], meta_chunks[chunk], lmeta+lnmeta); lnmeta += meta_chunks_len[chunk]; gk_free((void **)&coo_chunks[chunk], &meta_chunks[chunk], LTERM); } gk_free((void **)&coo_chunks_len, &meta_chunks_len, LTERM); /* sort and remove duplicates */ i2kvsorti(lnedges, lcoo); for (j=0, i=1; i<lnedges; i++) { if (lcoo[i].key1 == lcoo[j].key1 && lcoo[i].key2 == lcoo[j].key2) { if (lcoo[i].val != -1) printf("[%03"PRIDX"]Duplicate edges with metadata: %"PRIDX" [%s][%s]\n", mype, i, lmeta+lcoo[i].val, (lcoo[j].val==-1 ? "NULL" : lmeta+lcoo[j].val)); } else { lcoo[++j] = lcoo[i]; } } lnedges = j+1; //printf("[%03"PRIDX"] Done with sorting and de-duplication.\n", mype); gkMPI_Barrier(comm); /* convert the coo into the csr version */ graph->nvtxs = nvtxs; xadj = graph->xadj = ismalloc(nvtxs+1, 0, "DistDGL_ReadGraph: xadj"); adjncy = graph->adjncy = imalloc(lnedges, "DistDGL_ReadGraph: adjncy"); firstvtx = vtxdist[mype]; lastvtx = vtxdist[mype+1]; for (i=0; i<lnedges; i++) { ASSERT2(firstvtx <= lcoo[i].key1 && lcoo[i].key1 < lastvtx); xadj[lcoo[i].key1-firstvtx]++; } MAKECSR(i, nvtxs, xadj); for (i=0; i<lnedges; i++) adjncy[xadj[lcoo[i].key1-firstvtx]++] = lcoo[i].key2; SHIFTCSR(i, nvtxs, xadj); //printf("[%03"PRIDX"] Done with csr conversion.\n", mype); gkMPI_Barrier(comm); /* convert the lmeta into the (emptr, emdata) arrays */ graph->emdata_size = lnmeta+lnedges*idxwidth; emptr = graph->emptr = ismalloc(lnedges+1, 0, "DistDGL_ReadGraph: emptr"); emdata = graph->emdata = gk_cmalloc(graph->emdata_size, "DistDGL_ReadGraph: emdata"); for (i=0; i<lnedges; i++) { if (lcoo[i].val == -1) { emptr[i+1] = emptr[i]; } else { j = strlen(lmeta+lcoo[i].val)+1; gk_ccopy(j, lmeta+lcoo[i].val, emdata+emptr[i]); emptr[i+1] = emptr[i] + ((j+idxwidth-1)/idxwidth)*idxwidth; /* pad them to idxwidth boundaries */ } } /* save the emdata into a file for now */ { char fileout[256]; sprintf(fileout, "emdata-%d-%"PRIDX".bin", (int)getpid(), mype); gk_cwritefilebin(fileout, graph->emdata_size, emdata); gk_free((void **)&graph->emdata, LTERM); } gk_free((void **)&lcoo, &lmeta, LTERM); } //printf("[%03"PRIDX"] Done with edges.\n", mype); gkMPI_Barrier(comm); /* ======================================================= */ /* read and distribute the node weights and their metadata */ /* ======================================================= */ { idx_t u, v, vv, nlinesread, nchunks, chunk, chunksize, lnmeta; idx_t *con_buffers_cpos=NULL, **con_buffers=NULL; idx_t *con_chunks_len=NULL, **con_chunks=NULL; idx_t *meta_buffers_cpos=NULL, *meta_buffers_len=NULL; char **meta_buffers=NULL; idx_t *meta_chunks_len=NULL; char **meta_chunks=NULL; char *curstr, *newstr; idx_t *vmptr; char *vmdata; chunksize = CHUNKSIZE; nlinesread = 0; if (mype == 0) { sprintf(filename, "%s_nodes.txt", fstem); fsize = 3*gk_getfsize(filename)/(2*npes); /* give it a 1.5x xtra space */ fpin = gk_fopen(filename, "r", "DistDGL_ReadGraph: nodes.txt"); con_buffers_cpos = imalloc(npes, "con_buffers_cpos"); meta_buffers_cpos = imalloc(npes, "meta_buflen_cpos"); meta_buffers_len = ismalloc(npes, fsize, "meta_buflen_len"); con_buffers = (idx_t **)gk_malloc(npes*sizeof(idx_t *), "con_buffers"); meta_buffers = (char **)gk_malloc(npes*sizeof(char *), "meta_buffers"); for (pe=0; pe<npes; pe++) { con_buffers[pe] = imalloc((ncon+1)*chunksize, "con_buffers[pe]"); meta_buffers[pe] = gk_cmalloc(meta_buffers_len[pe], "meta_buffers[pe]"); } u = 0; } /* allocate memory for the chunks that will be collected by each PE */ nchunks = 2*gnvtxs/chunksize; con_chunks_len = imalloc(nchunks, "con_chunks_len"); meta_chunks_len = imalloc(nchunks, "meta_chunks_len"); con_chunks = (idx_t **)gk_malloc(nchunks*sizeof(idx_t *), "con_chunks"); meta_chunks = (char **)gk_malloc(nchunks*sizeof(char *), "meta_chunks"); /* start reading the node file */ for (chunk=0;;chunk++) { if (mype == 0) { iset(npes, 0, con_buffers_cpos); iset(npes, 0, meta_buffers_cpos); nlinesread = 0; while (gk_getline(&line, &lnlen, fpin) != -1) { rlen = strlen(gk_strtprune(line, "\n\r")); nlinesread++; pe = u%npes; v = vtxdist[u%npes] + u/npes; u++; if (meta_buffers_cpos[pe]+rlen+1 >= meta_buffers_len[pe]) { meta_buffers_len[pe] += meta_buffers_len[pe] + rlen + 1; meta_buffers[pe] = gk_crealloc(meta_buffers[pe], meta_buffers_len[pe], "meta_buffers[pe]"); } curstr = line; newstr = NULL; for (i=0; i<ncon; i++) { con_buffers[pe][(ncon+1)*con_buffers_cpos[pe]+i] = strtoidx(curstr, &newstr, 10); curstr = newstr; } con_buffers[pe][(ncon+1)*con_buffers_cpos[pe]+ncon] = meta_buffers_cpos[pe]; gk_ccopy(rlen+1, line, meta_buffers[pe]+meta_buffers_cpos[pe]); meta_buffers_cpos[pe] += rlen + 1; con_buffers_cpos[pe]++; if (con_buffers_cpos[pe] >= chunksize) break; } } /* distributed termination detection */ if (GlobalSESumComm(comm, nlinesread) == 0) break; /* adjust memory if needed */ if (chunk >= nchunks) { //printf("[%03"PRIDX"] Readjusting nchunks: %"PRIDX"\n", mype, nchunks); nchunks *= 2; con_chunks_len = irealloc(con_chunks_len, nchunks, "con_chunks_len"); meta_chunks_len = irealloc(meta_chunks_len, nchunks, "meta_chunks_len"); con_chunks = (idx_t **)gk_realloc(con_chunks, nchunks*sizeof(idx_t *), "con_chunks"); meta_chunks = (char **)gk_realloc(meta_chunks, nchunks*sizeof(char *), "meta_chunks"); } if (mype == 0) { for (pe=1; pe<npes; pe++) { gkMPI_Send((void *)&con_buffers_cpos[pe], 1, IDX_T, pe, 0, comm); gkMPI_Send((void *)&meta_buffers_cpos[pe], 1, IDX_T, pe, 0, comm); gkMPI_Send((void *)con_buffers[pe], (ncon+1)*con_buffers_cpos[pe], IDX_T, pe, 0, comm); gkMPI_Send((void *)meta_buffers[pe], meta_buffers_cpos[pe], MPI_CHAR, pe, 0, comm); } con_chunks_len[chunk] = con_buffers_cpos[0]; meta_chunks_len[chunk] = meta_buffers_cpos[0]; con_chunks[chunk] = imalloc((ncon+1)*con_chunks_len[chunk], "con_chunks[chunk]"); meta_chunks[chunk] = gk_cmalloc(meta_chunks_len[chunk], "meta_chunks[chunk]"); icopy((ncon+1)*con_chunks_len[chunk], con_buffers[0], con_chunks[chunk]); gk_ccopy(meta_chunks_len[chunk], meta_buffers[0], meta_chunks[chunk]); } else { gkMPI_Recv((void *)&con_chunks_len[chunk], 1, IDX_T, 0, 0, comm, &stat); gkMPI_Recv((void *)&meta_chunks_len[chunk], 1, IDX_T, 0, 0, comm, &stat); con_chunks[chunk] = imalloc((ncon+1)*con_chunks_len[chunk], "con_chunks[chunk]"); meta_chunks[chunk] = gk_cmalloc(meta_chunks_len[chunk], "meta_chunks[chunk]"); gkMPI_Recv((void *)con_chunks[chunk], (ncon+1)*con_chunks_len[chunk], IDX_T, 0, 0, comm, &stat); gkMPI_Recv((void *)meta_chunks[chunk], meta_chunks_len[chunk], MPI_CHAR, 0, 0, comm, &stat); } } nchunks = chunk; //printf("[%03"PRIDX"] Final nchunks: %"PRIDX"\n", mype, nchunks); /* done reading the node file */ if (mype == 0) { gk_fclose(fpin); for (pe=0; pe<npes; pe++) gk_free((void **)&con_buffers[pe], &meta_buffers[pe], LTERM); gk_free((void **)&con_buffers_cpos, &meta_buffers_cpos, &meta_buffers_len, &con_buffers, &meta_buffers, LTERM); } /* populate vwgt and create (vmptr, vmdata) */ ASSERT2(nvtxs == isum(nchunks, con_chunks_len, 1)); lnmeta = isum(nchunks, meta_chunks_len, 1); //printf("[%03"PRIDX"] nvtxs: %"PRIDX", lnmeta: %"PRIDX"\n", // mype, isum(nchunks, con_chunks_len, 1), lnmeta); graph->vmdata_size = lnmeta+nvtxs*idxwidth; vmptr = graph->vmptr = imalloc(nvtxs+1, "DistDGL_ReadGraph: vmptr"); vmdata = graph->vmdata = gk_cmalloc(graph->vmdata_size, "DistDGL_ReadGraph: vmdata"); vwgt = graph->vwgt = imalloc(nvtxs*(ncon-1), "DistDGL_ReadGraph: vwgt"); vtype = graph->vtype = imalloc(nvtxs, "DistDGL_ReadGraph: vwgt"); nvtxs = 0; vmptr[0] = 0; for (chunk=0; chunk<nchunks; chunk++) { for (i=0; i<con_chunks_len[chunk]; i++, nvtxs++) { vtype[nvtxs] = con_chunks[chunk][(ncon+1)*i+0]; for (j=1; j<ncon; j++) /* the 1st constraint is the vertex type */ vwgt[(ncon-1)*nvtxs+j-1] = con_chunks[chunk][(ncon+1)*i+j]; j = strlen(meta_chunks[chunk]+con_chunks[chunk][(ncon+1)*i+ncon])+1; gk_ccopy(j+1, meta_chunks[chunk]+con_chunks[chunk][(ncon+1)*i+ncon], vmdata+vmptr[nvtxs]); vmptr[nvtxs+1] = vmptr[nvtxs] + ((j+idxwidth-1)/idxwidth)*idxwidth; /* pad it to idxwidth muptliples */ } gk_free((void **)&con_chunks[chunk], &meta_chunks[chunk], LTERM); } ASSERT2(nvtxs == vtxdist[mype+1]-vtxdist[mype]); /* save the vmdata into a file for now */ { char fileout[256]; sprintf(fileout, "vmdata-%d-%"PRIDX".bin", (int)getpid(), mype); gk_cwritefilebin(fileout, graph->vmdata_size, vmdata); gk_free((void **)&graph->vmdata, LTERM); } gk_free((void **)&con_chunks_len, &meta_chunks_len, LTERM); } #ifdef XXX /* write the graph in stdout */ { idx_t u, v, i, j; for (pe=0; pe<npes; pe++) { if (mype == pe) { for (i=0; i<graph->nvtxs; i++) { for (j=graph->xadj[i]; j<graph->xadj[i+1]; j++) { u = graph->vtxdist[mype]+i; v = graph->adjncy[j]; printf("YYY%"PRIDX" [%"PRIDX" %"PRIDX"] [%"PRIDX" %"PRIDX"] vmdata: [%s] emdata: [%s]\n", mype, u, v, DistDGL_mapFromCyclic(u, npes, vtxdist), DistDGL_mapFromCyclic(v, npes, vtxdist), graph->vmdata+graph->vmptr[i], graph->emdata+graph->emptr[j]); } } fflush(stdout); } gkMPI_Barrier(comm); } } #endif ERROR_EXIT: gk_free((void **)&filename, &line, LTERM); return graph; } /*************************************************************************/ /*! Checks the local consistency of moved graph. */ /*************************************************************************/ void DistDGL_WriteGraphs(char *fstem, graph_t *graph, idx_t nparts_per_pe, MPI_Comm comm) { idx_t i, j, ii, jj, k, nvtxs, pnum, firstvtx; idx_t *xadj, *adjncy, *vtxdist, *vmptr, *emptr, *where, *vtype, *newlabel; char *filename, *vmdata, *emdata; FILE *nodefps[nparts_per_pe], *edgefps[nparts_per_pe], *statfps[nparts_per_pe]; i2kv_t *cand; idx_t npes, mype; gkMPI_Comm_size(comm, &npes); gkMPI_Comm_rank(comm, &mype); nvtxs = graph->nvtxs; xadj = graph->xadj; adjncy = graph->adjncy; vtxdist = graph->vtxdist; vmptr = graph->vmptr; emptr = graph->emptr; vmdata = graph->vmdata; emdata = graph->emdata; where = graph->where; vtype = graph->vtype; firstvtx = vtxdist[mype*nparts_per_pe]; { ctrl_t *ctrl; graph_t *ngraph; idx_t *cvtxdist; idx_t *nadjncy; ctrl = SetupCtrl(PARMETIS_OP_KMETIS, NULL, 1, npes, NULL, NULL, comm); ctrl->CoarsenTo = 1; /* Needed by SetUpGraph, otherwise we can FP errors */ cvtxdist = imalloc(npes+1, "cvtxdist"); for (i=0; i<npes; i++) cvtxdist[i] = vtxdist[(i+1)*nparts_per_pe]-vtxdist[i*nparts_per_pe]; MAKECSR(i, npes, cvtxdist); /* allocate memory and copy the adjncy into nadjncy, so that the renumbering will not change the newlabel mapping that you are doing bellow */ nadjncy = imalloc(xadj[nvtxs], "nadjncy"); icopy(xadj[nvtxs], adjncy, nadjncy); ngraph = SetupGraph(ctrl, 1, cvtxdist, xadj, NULL, NULL, nadjncy, NULL, 0); AllocateWSpace(ctrl, 0); CommSetup(ctrl, ngraph); WCOREPUSH; cand = (i2kv_t *)gk_malloc(nvtxs*sizeof(i2kv_t), "cand"); for (i=0; i<nvtxs; i++) { cand[i].key1 = where[i]; cand[i].key2 = vtype[i]; cand[i].val = i; } i2kvsortii(nvtxs, cand); newlabel = imalloc(nvtxs+ngraph->nrecv, "newlabel"); for (i=0; i<nvtxs; i++) newlabel[cand[i].val] = firstvtx+i; /* Send the newlabel info to processors storing adjacent interface nodes */ CommInterfaceData(ctrl, ngraph, newlabel, newlabel+nvtxs); WCOREPOP; /* copy the nadjncy as this is renumbered */ icopy(xadj[nvtxs], ngraph->adjncy, adjncy); FreeInitialGraphAndRemap(ngraph); FreeCtrl(&ctrl); gk_free((void **)&cvtxdist, &nadjncy, LTERM); } filename = gk_malloc(100+strlen(fstem), "DistDGL_WriteGraphs: filename"); for (k=0; k<nparts_per_pe; k++) { sprintf(filename, "p%03"PRIDX"-%s_nodes.txt", mype*nparts_per_pe+k, fstem); nodefps[k] = gk_fopen(filename, "w", "DistDGL_ReadGraph: nodes.txt"); sprintf(filename, "p%03"PRIDX"-%s_edges.txt", mype*nparts_per_pe+k, fstem); edgefps[k] = gk_fopen(filename, "w", "DistDGL_ReadGraph: edges.txt"); } for (ii=0; ii<nvtxs; ii++) { i = cand[ii].val; ASSERT(where[i] >= mype*nparts_per_pe && where[i] < (mype+1)*nparts_per_pe); pnum = where[i]%nparts_per_pe; fprintf(nodefps[pnum], "%"PRIDX" %s\n", newlabel[i], vmdata+vmptr[i]); for (j=xadj[i]; j<xadj[i+1]; j++) { if (emptr[j] < emptr[j+1]) { /* real edge */ fprintf(edgefps[pnum], "%"PRIDX" %"PRIDX" %s\n", newlabel[i], newlabel[adjncy[j]], emdata+emptr[j]); } } } for (k=0; k<nparts_per_pe; k++) { gk_fclose(nodefps[k]); gk_fclose(edgefps[k]); } gk_free((void **)&filename, &cand, &newlabel, LTERM); } /*************************************************************************/ /*! To and From Cyclic node-ID mapping */ /*************************************************************************/ idx_t DistDGL_mapFromCyclic(idx_t u, idx_t npes, idx_t *vtxdist) { idx_t i; for (i=0; i<npes; i++) { if (u < vtxdist[i+1]) break; } return (u-vtxdist[i])*npes + i; } idx_t DistDGL_mapToCyclic(idx_t u, idx_t npes, idx_t *vtxdist) { return vtxdist[u%npes] + u/npes; } /*************************************************************************/ /*! Sorts based on increasing <key1, key2>, and decreasing <val> */ /*************************************************************************/ void i2kvsorti(size_t n, i2kv_t *base) { #define ikeyval_lt(a, b) \ ((a)->key1 < (b)->key1 || \ ((a)->key1 == (b)->key1 && (a)->key2 < (b)->key2) || \ ((a)->key1 == (b)->key1 && (a)->key2 == (b)->key2 && (a)->val > (b)->val)) GK_MKQSORT(i2kv_t, base, n, ikeyval_lt); #undef ikeyval_lt } /*************************************************************************/ /*! Sorts based on increasing <key1, key2>, and decreasing <val> */ /*************************************************************************/ void i2kvsortii(size_t n, i2kv_t *base) { #define ikeyval_lt(a, b) \ ((a)->key1 < (b)->key1 || \ ((a)->key1 == (b)->key1 && (a)->key2 < (b)->key2) || \ ((a)->key1 == (b)->key1 && (a)->key2 == (b)->key2 && (a)->val < (b)->val)) GK_MKQSORT(i2kv_t, base, n, ikeyval_lt); #undef ikeyval_lt }
46,087
34.425058
118
c
null
ParMETIS-main/programs/otest.c
/* * Copyright 1997, Regents of the University of Minnesota * * main.c * * This file contains code for testing teh adaptive partitioning routines * * Started 5/19/97 * George * * $Id: ptest.c,v 1.3 2003/07/22 21:47:20 karypis Exp $ * */ #include <parmetisbin.h> /*************************************************************************/ /*! Entry point of the testing routine */ /*************************************************************************/ idx_t main(idx_t argc, char *argv[]) { idx_t mype, npes; MPI_Comm comm; MPI_Init(&argc, &argv); MPI_Comm_dup(MPI_COMM_WORLD, &comm); MPI_Comm_size(comm, &npes); MPI_Comm_rank(comm, &mype); if (argc != 2) { if (mype == 0) printf("Usage: %s <graph-file>\n", argv[0]); MPI_Finalize(); exit(0); } TestParMetis_GPart(argv[1], comm); MPI_Comm_free(&comm); MPI_Finalize(); return 0; } /***********************************************************************************/ /*! This function tests the various graph partitioning and ordering routines */ /***********************************************************************************/ void TestParMetis(char *filename, MPI_Comm comm) { idx_t ncon, nparts, npes, mype, opt2, realcut; graph_t graph, mgraph; idx_t *part, *mpart, *savepart, *order, *sizes; idx_t numflag=0, wgtflag=0, options[10], edgecut, ndims; real_t ipc2redist, *xyz, *tpwgts = NULL, ubvec[MAXNCON]; MPI_Comm_size(comm, &npes); MPI_Comm_rank(comm, &mype); ndims = 2; ParallelReadGraph(&graph, filename, comm); xyz = ReadTestCoordinates(&graph, filename, 2, comm); MPI_Barrier(comm); part = imalloc(graph.nvtxs, "TestParMetis_V3: part"); tpwgts = rmalloc(MAXNCON*npes*2, "TestParMetis_V3: tpwgts"); rset(MAXNCON, 1.05, ubvec); graph.vwgt = ismalloc(graph.nvtxs*5, 1, "TestParMetis_V3: vwgt"); /*====================================================================== / ParMETIS_V3_PartKway /=======================================================================*/ options[0] = 1; options[1] = 3; options[2] = 1; wgtflag = 2; numflag = 0; edgecut = 0; for (nparts=2*npes; nparts>=npes/2 && nparts > 0; nparts = nparts/2) { for (ncon=1; ncon<=5; ncon+=2) { if (ncon > 1 && nparts > 1) Mc_AdaptGraph(&graph, part, ncon, nparts, comm); else iset(graph.nvtxs, 1, graph.vwgt); for (opt2=1; opt2<=2; opt2++) { options[2] = opt2; rset(nparts*ncon, 1.0/(real_t)nparts, tpwgts); if (mype == 0) printf("\nTesting ParMETIS_V3_PartKway with options[1-2] = {%"PRIDX" %"PRIDX"}, Ncon: %"PRIDX", Nparts: %"PRIDX"\n", options[1], options[2], ncon, nparts); ParMETIS_V3_PartKway(graph.vtxdist, graph.xadj, graph.adjncy, graph.vwgt, NULL, &wgtflag, &numflag, &ncon, &nparts, tpwgts, ubvec, options, &edgecut, part, &comm); if (mype == 0) { printf("ParMETIS_V3_PartKway reported a cut of %"PRIDX"\n", edgecut); } } } } /*====================================================================== / ParMETIS_V3_PartGeomKway /=======================================================================*/ options[0] = 1; options[1] = 3; wgtflag = 2; numflag = 0; for (nparts=2*npes; nparts>=npes/2 && nparts > 0; nparts = nparts/2) { for (ncon=1; ncon<=5; ncon+=2) { if (ncon > 1) Mc_AdaptGraph(&graph, part, ncon, nparts, comm); else iset(graph.nvtxs, 1, graph.vwgt); for (opt2=1; opt2<=2; opt2++) { options[2] = opt2; rset(nparts*ncon, 1.0/(real_t)nparts, tpwgts); if (mype == 0) printf("\nTesting ParMETIS_V3_PartGeomKway with options[1-2] = {%"PRIDX" %"PRIDX"}, Ncon: %"PRIDX", Nparts: %"PRIDX"\n", options[1], options[2], ncon, nparts); ParMETIS_V3_PartGeomKway(graph.vtxdist, graph.xadj, graph.adjncy, graph.vwgt, NULL, &wgtflag, &numflag, &ndims, xyz, &ncon, &nparts, tpwgts, ubvec, options, &edgecut, part, &comm); if (mype == 0) { printf("ParMETIS_V3_PartGeomKway reported a cut of %"PRIDX"\n", edgecut); } } } } /*====================================================================== / ParMETIS_V3_PartGeom /=======================================================================*/ wgtflag = 0; numflag = 0; if (mype == 0) printf("\nTesting ParMETIS_V3_PartGeom\n"); /* ParMETIS_V3_PartGeom(graph.vtxdist, &ndims, xyz, part, &comm); */ if (mype == 0) printf("ParMETIS_V3_PartGeom partition complete\n"); /* realcut = ComputeRealCut(graph.vtxdist, part, filename, comm); if (mype == 0) printf("ParMETIS_V3_PartGeom reported a cut of %"PRIDX"\n", realcut); */ /*====================================================================== / ParMETIS_V3_RefineKway /=======================================================================*/ options[0] = 1; options[1] = 3; options[2] = 1; options[3] = COUPLED; nparts = npes; wgtflag = 0; numflag = 0; ncon = 1; rset(nparts*ncon, 1.0/(real_t)nparts, tpwgts); if (mype == 0) printf("\nTesting ParMETIS_V3_RefineKway with default options (before move)\n"); ParMETIS_V3_RefineKway(graph.vtxdist, graph.xadj, graph.adjncy, NULL, NULL, &wgtflag, &numflag, &ncon, &nparts, tpwgts, ubvec, options, &edgecut, part, &comm); MALLOC_CHECK(NULL); if (mype == 0) { printf("ParMETIS_V3_RefineKway reported a cut of %"PRIDX"\n", edgecut); } MALLOC_CHECK(NULL); /* Compute a good partition and move the graph. Do so quietly! */ options[0] = 0; nparts = npes; wgtflag = 0; numflag = 0; ncon = 1; rset(nparts*ncon, 1.0/(real_t)nparts, tpwgts); ParMETIS_V3_PartKway(graph.vtxdist, graph.xadj, graph.adjncy, NULL, NULL, &wgtflag, &numflag, &ncon, &npes, tpwgts, ubvec, options, &edgecut, part, &comm); TestMoveGraph(&graph, &mgraph, part, comm); gk_free((void **)&(graph.vwgt), LTERM); mpart = ismalloc(mgraph.nvtxs, mype, "TestParMetis_V3: mpart"); savepart = imalloc(mgraph.nvtxs, "TestParMetis_V3: savepart"); MALLOC_CHECK(NULL); /*====================================================================== / ParMETIS_V3_RefineKway /=======================================================================*/ options[0] = 1; options[1] = 3; options[3] = COUPLED; nparts = npes; wgtflag = 0; numflag = 0; for (ncon=1; ncon<=5; ncon+=2) { for (opt2=1; opt2<=2; opt2++) { options[2] = opt2; rset(nparts*ncon, 1.0/(real_t)nparts, tpwgts); if (mype == 0) printf("\nTesting ParMETIS_V3_RefineKway with options[1-3] = {%"PRIDX" %"PRIDX" %"PRIDX"}, Ncon: %"PRIDX", Nparts: %"PRIDX"\n", options[1], options[2], options[3], ncon, nparts); ParMETIS_V3_RefineKway(mgraph.vtxdist, mgraph.xadj, mgraph.adjncy, NULL, NULL, &wgtflag, &numflag, &ncon, &nparts, tpwgts, ubvec, options, &edgecut, mpart, &comm); if (mype == 0) { printf("ParMETIS_V3_RefineKway reported a cut of %"PRIDX"\n", edgecut); } } } /*====================================================================== / ParMETIS_V3_AdaptiveRepart /=======================================================================*/ mgraph.vwgt = ismalloc(mgraph.nvtxs*5, 1, "TestParMetis_V3: mgraph.vwgt"); mgraph.vsize = ismalloc(mgraph.nvtxs, 1, "TestParMetis_V3: mgraph.vsize"); AdaptGraph(&mgraph, 4, comm); options[0] = 1; options[1] = 7; options[3] = COUPLED; wgtflag = 2; numflag = 0; for (nparts=2*npes; nparts>=npes/2; nparts = nparts/2) { ncon = 1; wgtflag = 0; options[0] = 0; rset(nparts*ncon, 1.0/(real_t)nparts, tpwgts); ParMETIS_V3_PartKway(mgraph.vtxdist, mgraph.xadj, mgraph.adjncy, NULL, NULL, &wgtflag, &numflag, &ncon, &nparts, tpwgts, ubvec, options, &edgecut, savepart, &comm); options[0] = 1; wgtflag = 2; for (ncon=1; ncon<=3; ncon+=2) { rset(nparts*ncon, 1.0/(real_t)nparts, tpwgts); if (ncon > 1) Mc_AdaptGraph(&mgraph, savepart, ncon, nparts, comm); else AdaptGraph(&mgraph, 4, comm); /* iset(mgraph.nvtxs, 1, mgraph.vwgt); */ for (ipc2redist=1000.0; ipc2redist>=0.001; ipc2redist/=1000.0) { for (opt2=1; opt2<=2; opt2++) { icopy(mgraph.nvtxs, savepart, mpart); options[2] = opt2; if (mype == 0) printf("\nTesting ParMETIS_V3_AdaptiveRepart with options[1-3] = {%"PRIDX" %"PRIDX" %"PRIDX"}, ipc2redist: %.3"PRREAL", Ncon: %"PRIDX", Nparts: %"PRIDX"\n", options[1], options[2], options[3], ipc2redist, ncon, nparts); ParMETIS_V3_AdaptiveRepart(mgraph.vtxdist, mgraph.xadj, mgraph.adjncy, mgraph.vwgt, mgraph.vsize, NULL, &wgtflag, &numflag, &ncon, &nparts, tpwgts, ubvec, &ipc2redist, options, &edgecut, mpart, &comm); if (mype == 0) { printf("ParMETIS_V3_AdaptiveRepart reported a cut of %"PRIDX"\n", edgecut); } } } } } free(mgraph.vwgt); free(mgraph.vsize); /*====================================================================== / ParMETIS_V3_NodeND /=======================================================================*/ sizes = imalloc(2*npes, "TestParMetis_V3: sizes"); order = imalloc(graph.nvtxs, "TestParMetis_V3: sizes"); options[0] = 1; options[PMV3_OPTION_DBGLVL] = 3; options[PMV3_OPTION_SEED] = 1; numflag = 0; for (opt2=1; opt2<=2; opt2++) { options[PMV3_OPTION_IPART] = opt2; if (mype == 0) printf("\nTesting ParMETIS_V3_NodeND with options[1-3] = {%"PRIDX" %"PRIDX" %"PRIDX"}\n", options[1], options[2], options[3]); ParMETIS_V3_NodeND(graph.vtxdist, graph.xadj, graph.adjncy, &numflag, options, order, sizes, &comm); } gk_free((void **)&tpwgts, &part, &mpart, &savepart, &order, &sizes, LTERM); } /****************************************************************************** * This function takes a partition vector that is distributed and reads in * the original graph and computes the edgecut *******************************************************************************/ idx_t ComputeRealCut(idx_t *vtxdist, idx_t *part, char *filename, MPI_Comm comm) { idx_t i, j, nvtxs, mype, npes, cut; idx_t *xadj, *adjncy, *gpart; MPI_Status status; MPI_Comm_size(comm, &npes); MPI_Comm_rank(comm, &mype); if (mype != 0) { MPI_Send((void *)part, vtxdist[mype+1]-vtxdist[mype], IDX_T, 0, 1, comm); } else { /* Processor 0 does all the rest */ gpart = imalloc(vtxdist[npes], "ComputeRealCut: gpart"); icopy(vtxdist[1], part, gpart); for (i=1; i<npes; i++) MPI_Recv((void *)(gpart+vtxdist[i]), vtxdist[i+1]-vtxdist[i], IDX_T, i, 1, comm, &status); ReadMetisGraph(filename, &nvtxs, &xadj, &adjncy); /* OK, now compute the cut */ for (cut=0, i=0; i<nvtxs; i++) { for (j=xadj[i]; j<xadj[i+1]; j++) { if (gpart[i] != gpart[adjncy[j]]) cut++; } } cut = cut/2; gk_free((void **)&gpart, &xadj, &adjncy, LTERM); return cut; } return 0; } /****************************************************************************** * This function takes a partition vector that is distributed and reads in * the original graph and computes the edgecut *******************************************************************************/ idx_t ComputeRealCut2(idx_t *vtxdist, idx_t *mvtxdist, idx_t *part, idx_t *mpart, char *filename, MPI_Comm comm) { idx_t i, j, nvtxs, mype, npes, cut; idx_t *xadj, *adjncy, *gpart, *gmpart, *perm, *sizes; MPI_Status status; MPI_Comm_size(comm, &npes); MPI_Comm_rank(comm, &mype); if (mype != 0) { MPI_Send((void *)part, vtxdist[mype+1]-vtxdist[mype], IDX_T, 0, 1, comm); MPI_Send((void *)mpart, mvtxdist[mype+1]-mvtxdist[mype], IDX_T, 0, 1, comm); } else { /* Processor 0 does all the rest */ gpart = imalloc(vtxdist[npes], "ComputeRealCut: gpart"); icopy(vtxdist[1], part, gpart); gmpart = imalloc(mvtxdist[npes], "ComputeRealCut: gmpart"); icopy(mvtxdist[1], mpart, gmpart); for (i=1; i<npes; i++) { MPI_Recv((void *)(gpart+vtxdist[i]), vtxdist[i+1]-vtxdist[i], IDX_T, i, 1, comm, &status); MPI_Recv((void *)(gmpart+mvtxdist[i]), mvtxdist[i+1]-mvtxdist[i], IDX_T, i, 1, comm, &status); } /* OK, now go and reconstruct the permutation to go from the graph to mgraph */ perm = imalloc(vtxdist[npes], "ComputeRealCut: perm"); sizes = ismalloc(npes+1, 0, "ComputeRealCut: sizes"); for (i=0; i<vtxdist[npes]; i++) sizes[gpart[i]]++; MAKECSR(i, npes, sizes); for (i=0; i<vtxdist[npes]; i++) perm[i] = sizes[gpart[i]]++; /* Ok, now read the graph from the file */ ReadMetisGraph(filename, &nvtxs, &xadj, &adjncy); /* OK, now compute the cut */ for (cut=0, i=0; i<nvtxs; i++) { for (j=xadj[i]; j<xadj[i+1]; j++) { if (gmpart[perm[i]] != gmpart[perm[adjncy[j]]]) cut++; } } cut = cut/2; gk_free((void **)&gpart, &gmpart, &perm, &sizes, &xadj, &adjncy, LTERM); return cut; } return 0; } /****************************************************************************** * This function takes a graph and its partition vector and creates a new * graph corresponding to the one after the movement *******************************************************************************/ void TestMoveGraph(graph_t *ograph, graph_t *omgraph, idx_t *part, MPI_Comm comm) { idx_t npes, mype; ctrl_t ctrl; wspace_t wspace; graph_t *graph, *mgraph; idx_t options[5] = {0, 0, 1, 0, 0}; MPI_Comm_size(comm, &npes); MPI_Comm_rank(comm, &mype); SetUpCtrl(&ctrl, npes, 0, comm); ctrl.CoarsenTo = 1; /* Needed by SetUpGraph, otherwise we can FP errors */ graph = SetUpGraph(&ctrl, ograph->vtxdist, ograph->xadj, NULL, ograph->adjncy, NULL, 0); AllocateWSpace(&ctrl, graph, &wspace); SetUp(&ctrl, graph, &wspace); graph->where = part; graph->ncon = 1; mgraph = MoveGraph(&ctrl, graph, &wspace); omgraph->gnvtxs = mgraph->gnvtxs; omgraph->nvtxs = mgraph->nvtxs; omgraph->nedges = mgraph->nedges; omgraph->vtxdist = mgraph->vtxdist; omgraph->xadj = mgraph->xadj; omgraph->adjncy = mgraph->adjncy; mgraph->vtxdist = NULL; mgraph->xadj = NULL; mgraph->adjncy = NULL; FreeGraph(mgraph); graph->where = NULL; FreeInitialGraphAndRemap(graph, 0, 1); FreeWSpace(&wspace); } /***************************************************************************** * This function sets up a graph data structure for partitioning *****************************************************************************/ graph_t *SetUpGraph(ctrl_t *ctrl, idx_t *vtxdist, idx_t *xadj, idx_t *vwgt, idx_t *adjncy, idx_t *adjwgt, idx_t wgtflag) { idx_t mywgtflag; mywgtflag = wgtflag; return Mc_SetUpGraph(ctrl, 1, vtxdist, xadj, vwgt, adjncy, adjwgt, &mywgtflag); }
14,967
30.379455
231
c
null
ParMETIS-main/programs/parmetis.c
/* * Copyright 1997, Regents of the University of Minnesota * * main.c * * This is the entry point of the ILUT * * Started 10/19/95 * George * * $Id: parmetis.c,v 1.5 2003/07/30 21:18:54 karypis Exp $ * */ #include <parmetisbin.h> /************************************************************************* * Let the game begin **************************************************************************/ int main(int argc, char *argv[]) { idx_t i, j, npes, mype, optype, nparts, adptf, options[10]; idx_t *part=NULL, *sizes=NULL; graph_t graph; real_t ipc2redist, *xyz=NULL, *tpwgts=NULL, ubvec[MAXNCON]; MPI_Comm comm; idx_t numflag=0, wgtflag=0, ndims, edgecut; char xyzfilename[8192]; MPI_Init(&argc, &argv); MPI_Comm_dup(MPI_COMM_WORLD, &comm); gkMPI_Comm_size(comm, &npes); gkMPI_Comm_rank(comm, &mype); if (argc != 8) { if (mype == 0) printf("Usage: %s <graph-file> <op-type> <nparts> <adapth-factor> <ipc2redist> <dbglvl> <seed>\n", argv[0]); MPI_Finalize(); exit(0); } optype = atoi(argv[2]); nparts = atoi(argv[3]); adptf = atoi(argv[4]); ipc2redist = atof(argv[5]); options[0] = 1; options[PMV3_OPTION_DBGLVL] = atoi(argv[6]); options[PMV3_OPTION_SEED] = atoi(argv[7]); if (mype == 0) printf("reading file: %s\n", argv[1]); ParallelReadGraph(&graph, argv[1], comm); /* Remove the edges for testing */ /*iset(graph.vtxdist[mype+1]-graph.vtxdist[mype]+1, 0, graph.xadj); */ rset(graph.ncon, 1.05, ubvec); tpwgts = rmalloc(nparts*graph.ncon, "tpwgts"); rset(nparts*graph.ncon, 1.0/(real_t)nparts, tpwgts); /* ChangeToFortranNumbering(graph.vtxdist, graph.xadj, graph.adjncy, mype, npes); numflag = 1; nvtxs = graph.vtxdist[mype+1]-graph.vtxdist[mype]; nedges = graph.xadj[nvtxs]; printf("%"PRIDX" %"PRIDX"\n", isum(nvtxs, graph.xadj, 1), isum(nedges, graph.adjncy, 1)); */ if (optype >= 20) { sprintf(xyzfilename, "%s.xyz", argv[1]); xyz = ReadTestCoordinates(&graph, xyzfilename, &ndims, comm); } if (mype == 0) printf("finished reading file: %s\n", argv[1]); part = ismalloc(graph.nvtxs, mype%nparts, "main: part"); sizes = imalloc(2*npes, "main: sizes"); switch (optype) { case 1: wgtflag = 3; ParMETIS_V3_PartKway(graph.vtxdist, graph.xadj, graph.adjncy, graph.vwgt, graph.adjwgt, &wgtflag, &numflag, &graph.ncon, &nparts, tpwgts, ubvec, options, &edgecut, part, &comm); WritePVector(argv[1], graph.vtxdist, part, MPI_COMM_WORLD); break; case 2: wgtflag = 3; options[PMV3_OPTION_PSR] = PARMETIS_PSR_COUPLED; ParMETIS_V3_RefineKway(graph.vtxdist, graph.xadj, graph.adjncy, graph.vwgt, graph.adjwgt, &wgtflag, &numflag, &graph.ncon, &nparts, tpwgts, ubvec, options, &edgecut, part, &comm); WritePVector(argv[1], graph.vtxdist, part, MPI_COMM_WORLD); break; case 3: options[PMV3_OPTION_PSR] = PARMETIS_PSR_COUPLED; graph.vwgt = ismalloc(graph.nvtxs, 1, "main: vwgt"); if (npes > 1) { AdaptGraph(&graph, adptf, comm); } else { wgtflag = 3; ParMETIS_V3_PartKway(graph.vtxdist, graph.xadj, graph.adjncy, graph.vwgt, graph.adjwgt, &wgtflag, &numflag, &graph.ncon, &nparts, tpwgts, ubvec, options, &edgecut, part, &comm); printf("Initial partitioning with edgecut of %"PRIDX"\n", edgecut); for (i=0; i<graph.ncon; i++) { for (j=0; j<graph.nvtxs; j++) { if (part[j] == i) graph.vwgt[j*graph.ncon+i] = adptf; else graph.vwgt[j*graph.ncon+i] = 1; } } } wgtflag = 3; ParMETIS_V3_AdaptiveRepart(graph.vtxdist, graph.xadj, graph.adjncy, graph.vwgt, NULL, graph.adjwgt, &wgtflag, &numflag, &graph.ncon, &nparts, tpwgts, ubvec, &ipc2redist, options, &edgecut, part, &comm); break; case 4: ParMETIS_V3_NodeND(graph.vtxdist, graph.xadj, graph.adjncy, &numflag, options, part, sizes, &comm); /* WriteOVector(argv[1], graph.vtxdist, part, comm); */ break; case 5: ParMETIS_SerialNodeND(graph.vtxdist, graph.xadj, graph.adjncy, &numflag, options, part, sizes, &comm); /* WriteOVector(argv[1], graph.vtxdist, part, comm); */ printf("%"PRIDX" %"PRIDX" %"PRIDX" %"PRIDX" %"PRIDX" %"PRIDX" %"PRIDX"\n", sizes[0], sizes[1], sizes[2], sizes[3], sizes[4], sizes[5], sizes[6]); break; case 11: /* TestAdaptiveMETIS(graph.vtxdist, graph.xadj, graph.adjncy, part, options, adptf, comm); */ break; case 20: wgtflag = 3; ParMETIS_V3_PartGeomKway(graph.vtxdist, graph.xadj, graph.adjncy, graph.vwgt, graph.adjwgt, &wgtflag, &numflag, &ndims, xyz, &graph.ncon, &nparts, tpwgts, ubvec, options, &edgecut, part, &comm); break; case 21: ParMETIS_V3_PartGeom(graph.vtxdist, &ndims, xyz, part, &comm); break; } /* printf("%"PRIDX" %"PRIDX"\n", isum(nvtxs, graph.xadj, 1), isum(nedges, graph.adjncy, 1)); */ gk_free((void **)&part, &sizes, &tpwgts, &graph.vtxdist, &graph.xadj, &graph.adjncy, &graph.vwgt, &graph.adjwgt, &xyz, LTERM); MPI_Comm_free(&comm); MPI_Finalize(); return 0; } /************************************************************************* * This function changes the numbering to be from 1 instead of 0 **************************************************************************/ void ChangeToFortranNumbering(idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t mype, idx_t npes) { idx_t i, nvtxs, nedges; nvtxs = vtxdist[mype+1]-vtxdist[mype]; nedges = xadj[nvtxs]; for (i=0; i<npes+1; i++) vtxdist[i]++; for (i=0; i<nvtxs+1; i++) xadj[i]++; for (i=0; i<nedges; i++) adjncy[i]++; return; }
5,891
30.677419
151
c
null
ParMETIS-main/programs/pometis.c
/* * Copyright 1997, Regents of the University of Minnesota * * pometis.c * * This is the entry point of the ILUT * * Started 10/19/95 * George * * $Id: parmetis.c,v 1.5 2003/07/30 21:18:54 karypis Exp $ * */ #include <parmetisbin.h> /************************************************************************* * Let the game begin **************************************************************************/ int main(int argc, char *argv[]) { idx_t i, j, npes, mype, optype, nparts, adptf, options[10]; idx_t *order, *sizes; graph_t graph; MPI_Comm comm; idx_t numflag=0, wgtflag=0, ndims=3, edgecut; idx_t mtype, rtype, p_nseps, s_nseps, seed, dbglvl; real_t ubfrac; size_t opc; MPI_Init(&argc, &argv); MPI_Comm_dup(MPI_COMM_WORLD, &comm); gkMPI_Comm_size(comm, &npes); gkMPI_Comm_rank(comm, &mype); if (argc != 10) { if (mype == 0) { printf("Usage: %s <graph-file> <op-type> <seed> <dbglvl> <mtype> <rtype> <p_nseps> <s_nseps> <ubfrac>\n", argv[0]); printf(" op-type: 1=ParNodeND_V3, 2=ParNodeND_V32, 3=SerNodeND\n"); printf(" mtype: %"PRIDX"=LOCAL, %"PRIDX"=GLOBAL\n", (idx_t)PARMETIS_MTYPE_LOCAL, (idx_t)PARMETIS_MTYPE_GLOBAL); printf(" rtype: %"PRIDX"=GREEDY, %"PRIDX"=2PHASE\n", (idx_t)PARMETIS_SRTYPE_GREEDY, (idx_t)PARMETIS_SRTYPE_2PHASE); } MPI_Finalize(); exit(0); } optype = atoi(argv[2]); if (mype == 0) printf("reading file: %s\n", argv[1]); ParallelReadGraph(&graph, argv[1], comm); if (mype == 0) printf("done\n"); order = ismalloc(graph.nvtxs, mype, "main: order"); sizes = imalloc(2*npes, "main: sizes"); switch (optype) { case 1: options[0] = 1; options[PMV3_OPTION_SEED] = atoi(argv[3]); options[PMV3_OPTION_DBGLVL] = atoi(argv[4]); ParMETIS_V3_NodeND(graph.vtxdist, graph.xadj, graph.adjncy, &numflag, options, order, sizes, &comm); break; case 2: seed = atoi(argv[3]); dbglvl = atoi(argv[4]); mtype = atoi(argv[5]); rtype = atoi(argv[6]); p_nseps = atoi(argv[7]); s_nseps = atoi(argv[8]); ubfrac = atof(argv[9]); ParMETIS_V32_NodeND(graph.vtxdist, graph.xadj, graph.adjncy, graph.vwgt, &numflag, &mtype, &rtype, &p_nseps, &s_nseps, &ubfrac, &seed, &dbglvl, order, sizes, &comm); break; case 3: options[0] = 0; ParMETIS_SerialNodeND(graph.vtxdist, graph.xadj, graph.adjncy, &numflag, options, order, sizes, &comm); break; default: if (mype == 0) printf("Uknown optype of %"PRIDX"\n", optype); MPI_Finalize(); exit(0); } WriteOVector(argv[1], graph.vtxdist, order, comm); /* print the partition sizes and the separators */ if (mype == 0) { opc = 0; nparts = 1<<log2Int(npes); for (i=0; i<2*nparts-1; i++) { printf(" %6"PRIDX"", sizes[i]); if (i >= nparts) opc += sizes[i]*(sizes[i]+1)/2; } printf("\nTopSep OPC: %zu\n", opc); } gk_free((void **)&order, &sizes, &graph.vtxdist, &graph.xadj, &graph.adjncy, &graph.vwgt, &graph.adjwgt, LTERM); MPI_Comm_free(&comm); MPI_Finalize(); return 0; }
3,225
26.338983
121
c
null
ParMETIS-main/programs/io.c
/* * Copyright 1997, Regents of the University of Minnesota * * pio.c * * This file contains routines related to I/O * * Started 10/19/94 * George * * $Id: io.c,v 1.1 2003/07/22 21:47:18 karypis Exp $ * */ #include <parmetisbin.h> #define MAXLINE 64*1024*1024 /************************************************************************* * This function reads the CSR matrix **************************************************************************/ void ParallelReadGraph(graph_t *graph, char *filename, MPI_Comm comm) { idx_t i, k, l, pe; idx_t npes, mype, ier; idx_t gnvtxs, nvtxs, your_nvtxs, your_nedges, gnedges; idx_t maxnvtxs = -1, maxnedges = -1; idx_t readew = -1, readvw = -1, dummy, edge; idx_t *vtxdist, *xadj, *adjncy, *vwgt, *adjwgt; idx_t *your_xadj, *your_adjncy, *your_vwgt, *your_adjwgt, graphinfo[4]; idx_t fmt, ncon, nobj; MPI_Status stat; char *line = NULL, *oldstr, *newstr; FILE *fpin = NULL; gkMPI_Comm_size(comm, &npes); gkMPI_Comm_rank(comm, &mype); vtxdist = graph->vtxdist = ismalloc(npes+1, 0, "ReadGraph: vtxdist"); if (mype == npes-1) { ier = 0; fpin = fopen(filename, "r"); if (fpin == NULL) { printf("COULD NOT OPEN FILE '%s' FOR SOME REASON!\n", filename); ier++; } gkMPI_Bcast(&ier, 1, IDX_T, npes-1, comm); if (ier > 0){ MPI_Finalize(); exit(0); } line = gk_cmalloc(MAXLINE+1, "line"); while (fgets(line, MAXLINE, fpin) && line[0] == '%'); fmt = ncon = nobj = 0; sscanf(line, "%"PRIDX" %"PRIDX" %"PRIDX" %"PRIDX" %"PRIDX"", &gnvtxs, &gnedges, &fmt, &ncon, &nobj); gnedges *=2; readew = (fmt%10 > 0); readvw = ((fmt/10)%10 > 0); graph->ncon = ncon = (ncon == 0 ? 1 : ncon); graph->nobj = nobj = (nobj == 0 ? 1 : nobj); /*printf("Nvtxs: %"PRIDX", Nedges: %"PRIDX", Ncon: %"PRIDX"\n", gnvtxs, gnedges, ncon); */ graphinfo[0] = ncon; graphinfo[1] = nobj; graphinfo[2] = readvw; graphinfo[3] = readew; gkMPI_Bcast((void *)graphinfo, 4, IDX_T, npes-1, comm); /* Construct vtxdist and send it to all the processors */ vtxdist[0] = 0; for (i=0,k=gnvtxs; i<npes; i++) { l = k/(npes-i); vtxdist[i+1] = vtxdist[i]+l; k -= l; } gkMPI_Bcast((void *)vtxdist, npes+1, IDX_T, npes-1, comm); } else { gkMPI_Bcast(&ier, 1, IDX_T, npes-1, comm); if (ier > 0){ MPI_Finalize(); exit(0); } gkMPI_Bcast((void *)graphinfo, 4, IDX_T, npes-1, comm); graph->ncon = ncon = graphinfo[0]; graph->nobj = nobj = graphinfo[1]; readvw = graphinfo[2]; readew = graphinfo[3]; gkMPI_Bcast((void *)vtxdist, npes+1, IDX_T, npes-1, comm); } if ((ncon > 1 && !readvw) || (nobj > 1 && !readew)) { printf("fmt and ncon/nobj are inconsistant. Exiting...\n"); gkMPI_Finalize(); exit(-1); } graph->gnvtxs = vtxdist[npes]; nvtxs = graph->nvtxs = vtxdist[mype+1]-vtxdist[mype]; xadj = graph->xadj = imalloc(graph->nvtxs+1, "ParallelReadGraph: xadj"); vwgt = graph->vwgt = imalloc(graph->nvtxs*ncon, "ParallelReadGraph: vwgt"); /*******************************************/ /* Go through first time and generate xadj */ /*******************************************/ if (mype == npes-1) { maxnvtxs = vtxdist[1]; for (i=1; i<npes; i++) maxnvtxs = (maxnvtxs < vtxdist[i+1]-vtxdist[i] ? vtxdist[i+1]-vtxdist[i] : maxnvtxs); your_xadj = imalloc(maxnvtxs+1, "your_xadj"); your_vwgt = ismalloc(maxnvtxs*ncon, 1, "your_vwgt"); maxnedges = 0; for (pe=0; pe<npes; pe++) { your_nvtxs = vtxdist[pe+1]-vtxdist[pe]; for (i=0; i<your_nvtxs; i++) { your_nedges = 0; while (fgets(line, MAXLINE, fpin) && line[0] == '%'); /* skip lines with '#' */ oldstr = line; newstr = NULL; if (readvw) { for (l=0; l<ncon; l++) { your_vwgt[i*ncon+l] = strtoidx(oldstr, &newstr, 10); oldstr = newstr; } } for (;;) { edge = strtoidx(oldstr, &newstr, 10) -1; oldstr = newstr; if (edge < 0) break; if (readew) { for (l=0; l<nobj; l++) { dummy = strtoidx(oldstr, &newstr, 10); oldstr = newstr; } } your_nedges++; } your_xadj[i] = your_nedges; } MAKECSR(i, your_nvtxs, your_xadj); maxnedges = (maxnedges < your_xadj[your_nvtxs] ? your_xadj[your_nvtxs] : maxnedges); if (pe < npes-1) { gkMPI_Send((void *)your_xadj, your_nvtxs+1, IDX_T, pe, 0, comm); gkMPI_Send((void *)your_vwgt, your_nvtxs*ncon, IDX_T, pe, 1, comm); } else { for (i=0; i<your_nvtxs+1; i++) xadj[i] = your_xadj[i]; for (i=0; i<your_nvtxs*ncon; i++) vwgt[i] = your_vwgt[i]; } } fclose(fpin); gk_free((void **)&your_xadj, &your_vwgt, LTERM); } else { gkMPI_Recv((void *)xadj, nvtxs+1, IDX_T, npes-1, 0, comm, &stat); gkMPI_Recv((void *)vwgt, nvtxs*ncon, IDX_T, npes-1, 1, comm, &stat); } graph->nedges = xadj[nvtxs]; adjncy = graph->adjncy = imalloc(xadj[nvtxs], "ParallelReadGraph: adjncy"); adjwgt = graph->adjwgt = imalloc(xadj[nvtxs]*nobj, "ParallelReadGraph: adjwgt"); /***********************************************/ /* Now go through again and record adjncy data */ /***********************************************/ if (mype == npes-1) { ier = 0; fpin = fopen(filename, "r"); if (fpin == NULL){ printf("COULD NOT OPEN FILE '%s' FOR SOME REASON!\n", filename); ier++; } gkMPI_Bcast(&ier, 1, IDX_T, npes-1, comm); if (ier > 0){ gkMPI_Finalize(); exit(0); } /* get first line again */ while (fgets(line, MAXLINE, fpin) && line[0] == '%'); your_adjncy = imalloc(maxnedges, "your_adjncy"); your_adjwgt = ismalloc(maxnedges*nobj, 1, "your_adjwgt"); for (pe=0; pe<npes; pe++) { your_nvtxs = vtxdist[pe+1]-vtxdist[pe]; your_nedges = 0; for (i=0; i<your_nvtxs; i++) { while (fgets(line, MAXLINE, fpin) && line[0] == '%'); oldstr = line; newstr = NULL; if (readvw) { for (l=0; l<ncon; l++) { dummy = strtoidx(oldstr, &newstr, 10); oldstr = newstr; } } for (;;) { edge = strtoidx(oldstr, &newstr, 10) -1; oldstr = newstr; if (edge < 0) break; your_adjncy[your_nedges] = edge; if (readew) { for (l=0; l<nobj; l++) { your_adjwgt[your_nedges*nobj+l] = strtoidx(oldstr, &newstr, 10); oldstr = newstr; } } your_nedges++; } } if (pe < npes-1) { gkMPI_Send((void *)your_adjncy, your_nedges, IDX_T, pe, 0, comm); gkMPI_Send((void *)your_adjwgt, your_nedges*nobj, IDX_T, pe, 1, comm); } else { for (i=0; i<your_nedges; i++) adjncy[i] = your_adjncy[i]; for (i=0; i<your_nedges*nobj; i++) adjwgt[i] = your_adjwgt[i]; } } fclose(fpin); gk_free((void **)&your_adjncy, &your_adjwgt, &line, LTERM); } else { gkMPI_Bcast(&ier, 1, IDX_T, npes-1, comm); if (ier > 0){ gkMPI_Finalize(); exit(0); } gkMPI_Recv((void *)adjncy, xadj[nvtxs], IDX_T, npes-1, 0, comm, &stat); gkMPI_Recv((void *)adjwgt, xadj[nvtxs]*nobj, IDX_T, npes-1, 1, comm, &stat); } } /************************************************************************* * This function writes a distributed graph to file **************************************************************************/ void Mc_ParallelWriteGraph(ctrl_t *ctrl, graph_t *graph, char *filename, idx_t nparts, idx_t testset) { idx_t h, i, j; idx_t npes, mype, penum, gnedges; char partfile[256]; FILE *fpin; MPI_Comm comm; comm = ctrl->comm; gkMPI_Comm_size(comm, &npes); gkMPI_Comm_rank(comm, &mype); gnedges = GlobalSESum(ctrl, graph->nedges); sprintf(partfile, "%s.%"PRIDX".%"PRIDX".%"PRIDX"", filename, testset, graph->ncon, nparts); if (mype == 0) { if ((fpin = fopen(partfile, "w")) == NULL) errexit("Failed to open file %s", partfile); fprintf(fpin, "%"PRIDX" %"PRIDX" %"PRIDX" %"PRIDX" %"PRIDX"\n", graph->gnvtxs, gnedges/2, (idx_t)11, graph->ncon, (idx_t)1); fclose(fpin); } gkMPI_Barrier(comm); for (penum=0; penum<npes; penum++) { if (mype == penum) { if ((fpin = fopen(partfile, "a")) == NULL) errexit("Failed to open file %s", partfile); for (i=0; i<graph->nvtxs; i++) { for (h=0; h<graph->ncon; h++) fprintf(fpin, "%"PRIDX" ", graph->vwgt[i*graph->ncon+h]); for (j=graph->xadj[i]; j<graph->xadj[i+1]; j++) { fprintf(fpin, "%"PRIDX" ", graph->adjncy[j]+1); fprintf(fpin, "%"PRIDX" ", graph->adjwgt[j]); } fprintf(fpin, "\n"); } fclose(fpin); } gkMPI_Barrier(comm); } return; } /************************************************************************* * This function reads the CSR matrix **************************************************************************/ void ReadTestGraph(graph_t *graph, char *filename, MPI_Comm comm) { idx_t i, k, l, npes, mype; idx_t nvtxs, penum, snvtxs; idx_t *gxadj, *gadjncy; idx_t *vtxdist, *sxadj, *ssize = NULL; MPI_Status status; gkMPI_Comm_size(comm, &npes); gkMPI_Comm_rank(comm, &mype); vtxdist = graph->vtxdist = ismalloc(npes+1, 0, "ReadGraph: vtxdist"); if (mype == 0) { ssize = ismalloc(npes, 0, "ReadGraph: ssize"); ReadMetisGraph(filename, &nvtxs, &gxadj, &gadjncy); printf("Nvtxs: %"PRIDX", Nedges: %"PRIDX"\n", nvtxs, gxadj[nvtxs]); /* Construct vtxdist and send it to all the processors */ vtxdist[0] = 0; for (i=0,k=nvtxs; i<npes; i++) { l = k/(npes-i); vtxdist[i+1] = vtxdist[i]+l; k -= l; } } gkMPI_Bcast((void *)vtxdist, npes+1, IDX_T, 0, comm); graph->gnvtxs = vtxdist[npes]; graph->nvtxs = vtxdist[mype+1]-vtxdist[mype]; graph->xadj = imalloc(graph->nvtxs+1, "ReadGraph: xadj"); if (mype == 0) { for (penum=0; penum<npes; penum++) { snvtxs = vtxdist[penum+1]-vtxdist[penum]; sxadj = imalloc(snvtxs+1, "ReadGraph: sxadj"); icopy(snvtxs+1, gxadj+vtxdist[penum], sxadj); for (i=snvtxs; i>=0; i--) sxadj[i] -= sxadj[0]; ssize[penum] = gxadj[vtxdist[penum+1]] - gxadj[vtxdist[penum]]; if (penum == mype) icopy(snvtxs+1, sxadj, graph->xadj); else gkMPI_Send((void *)sxadj, snvtxs+1, IDX_T, penum, 1, comm); gk_free((void **)&sxadj, LTERM); } } else gkMPI_Recv((void *)graph->xadj, graph->nvtxs+1, IDX_T, 0, 1, comm, &status); graph->nedges = graph->xadj[graph->nvtxs]; graph->adjncy = imalloc(graph->nedges, "ReadGraph: graph->adjncy"); if (mype == 0) { for (penum=0; penum<npes; penum++) { if (penum == mype) icopy(ssize[penum], gadjncy+gxadj[vtxdist[penum]], graph->adjncy); else gkMPI_Send((void *)(gadjncy+gxadj[vtxdist[penum]]), ssize[penum], IDX_T, penum, 1, comm); } gk_free((void **)&ssize, LTERM); } else gkMPI_Recv((void *)graph->adjncy, graph->nedges, IDX_T, 0, 1, comm, &status); graph->vwgt = NULL; graph->adjwgt = NULL; if (mype == 0) gk_free((void **)&gxadj, &gadjncy, LTERM); MALLOC_CHECK(NULL); } /*************************************************************************/ /*! Reads the coordinates associated with the vertices of a graph */ /*************************************************************************/ real_t *ReadTestCoordinates(graph_t *graph, char *filename, idx_t *r_ndims, MPI_Comm comm) { idx_t i, j, k, npes, mype, penum, ndims; real_t *xyz, *txyz; float ftmp; char line[8192]; FILE *fpin=NULL; idx_t *vtxdist; MPI_Status status; gkMPI_Comm_size(comm, &npes); gkMPI_Comm_rank(comm, &mype); vtxdist = graph->vtxdist; if (mype == 0) { if ((fpin = fopen(filename, "r")) == NULL) errexit("Failed to open file %s\n", filename); /* determine the number of dimensions */ if (fgets(line, 8191, fpin) == NULL) errexit("Failed to read from file %s\n", filename); ndims = sscanf(line, "%e %e %e", &ftmp, &ftmp, &ftmp); fclose(fpin); if ((fpin = fopen(filename, "r")) == NULL) errexit("Failed to open file %s\n", filename); } gkMPI_Bcast((void *)&ndims, 1, IDX_T, 0, comm); *r_ndims = ndims; xyz = rmalloc(graph->nvtxs*ndims, "ReadTestCoordinates"); if (mype == 0) { for (penum=0; penum<npes; penum++) { txyz = rmalloc((vtxdist[penum+1]-vtxdist[penum])*ndims, "ReadTestCoordinates"); for (k=0, i=vtxdist[penum]; i<vtxdist[penum+1]; i++, k++) { for (j=0; j<ndims; j++) if (fscanf(fpin, "%"SCREAL" ", txyz+k*ndims+j) != 1) errexit("Failed to read coordinate for node\n"); } if (penum == mype) memcpy((void *)xyz, (void *)txyz, sizeof(real_t)*ndims*k); else gkMPI_Send((void *)txyz, ndims*k, REAL_T, penum, 1, comm); gk_free((void **)&txyz, LTERM); } fclose(fpin); } else gkMPI_Recv((void *)xyz, ndims*graph->nvtxs, REAL_T, 0, 1, comm, &status); return xyz; } /************************************************************************* * This function reads the spd matrix **************************************************************************/ void ReadMetisGraph(char *filename, idx_t *r_nvtxs, idx_t **r_xadj, idx_t **r_adjncy) { idx_t i, k, edge, nvtxs, nedges; idx_t *xadj, *adjncy; char *line, *oldstr, *newstr; FILE *fpin; line = gk_cmalloc(MAXLINE+1, "ReadMetisGraph: line"); if ((fpin = fopen(filename, "r")) == NULL) { printf("Failed to open file %s\n", filename); exit(0); } oldstr = fgets(line, MAXLINE, fpin); sscanf(line, "%"PRIDX" %"PRIDX"", &nvtxs, &nedges); nedges *=2; xadj = imalloc(nvtxs+1, "ReadGraph: xadj"); adjncy = imalloc(nedges, "ReadGraph: adjncy"); /* Start reading the graph file */ for (xadj[0]=0, k=0, i=0; i<nvtxs; i++) { oldstr = fgets(line, MAXLINE, fpin); oldstr = line; newstr = NULL; for (;;) { edge = strtoidx(oldstr, &newstr, 10) -1; oldstr = newstr; if (edge < 0) break; adjncy[k++] = edge; } xadj[i+1] = k; } fclose(fpin); gk_free((void **)&line, LTERM); *r_nvtxs = nvtxs; *r_xadj = xadj; *r_adjncy = adjncy; } /************************************************************************* * This function reads the CSR matrix **************************************************************************/ void Mc_SerialReadGraph(graph_t *graph, char *filename, idx_t *wgtflag, MPI_Comm comm) { idx_t i, k, l, npes, mype; idx_t nvtxs, ncon, nobj, fmt; idx_t penum, snvtxs; idx_t *gxadj, *gadjncy, *gvwgt, *gadjwgt; idx_t *vtxdist, *sxadj, *ssize = NULL; MPI_Status status; gkMPI_Comm_size(comm, &npes); gkMPI_Comm_rank(comm, &mype); vtxdist = graph->vtxdist = ismalloc(npes+1, 0, "ReadGraph: vtxdist"); if (mype == 0) { ssize = ismalloc(npes, 0, "ReadGraph: ssize"); Mc_SerialReadMetisGraph(filename, &nvtxs, &ncon, &nobj, &fmt, &gxadj, &gvwgt, &gadjncy, &gadjwgt, wgtflag); printf("Nvtxs: %"PRIDX", Nedges: %"PRIDX"\n", nvtxs, gxadj[nvtxs]); /* Construct vtxdist and send it to all the processors */ vtxdist[0] = 0; for (i=0,k=nvtxs; i<npes; i++) { l = k/(npes-i); vtxdist[i+1] = vtxdist[i]+l; k -= l; } } gkMPI_Bcast((void *)(&fmt), 1, IDX_T, 0, comm); gkMPI_Bcast((void *)(&ncon), 1, IDX_T, 0, comm); gkMPI_Bcast((void *)(&nobj), 1, IDX_T, 0, comm); gkMPI_Bcast((void *)(wgtflag), 1, IDX_T, 0, comm); gkMPI_Bcast((void *)vtxdist, npes+1, IDX_T, 0, comm); graph->gnvtxs = vtxdist[npes]; graph->nvtxs = vtxdist[mype+1]-vtxdist[mype]; graph->ncon = ncon; graph->xadj = imalloc(graph->nvtxs+1, "ReadGraph: xadj"); /*************************************************/ /* distribute xadj array */ if (mype == 0) { for (penum=0; penum<npes; penum++) { snvtxs = vtxdist[penum+1]-vtxdist[penum]; sxadj = imalloc(snvtxs+1, "ReadGraph: sxadj"); icopy(snvtxs+1, gxadj+vtxdist[penum], sxadj); for (i=snvtxs; i>=0; i--) sxadj[i] -= sxadj[0]; ssize[penum] = gxadj[vtxdist[penum+1]] - gxadj[vtxdist[penum]]; if (penum == mype) icopy(snvtxs+1, sxadj, graph->xadj); else MPI_Send((void *)sxadj, snvtxs+1, IDX_T, penum, 1, comm); gk_free((void **)&sxadj, LTERM); } } else gkMPI_Recv((void *)graph->xadj, graph->nvtxs+1, IDX_T, 0, 1, comm, &status); graph->nedges = graph->xadj[graph->nvtxs]; graph->adjncy = imalloc(graph->nedges, "ReadGraph: graph->adjncy"); /*************************************************/ /* distribute adjncy array */ if (mype == 0) { for (penum=0; penum<npes; penum++) { if (penum == mype) icopy(ssize[penum], gadjncy+gxadj[vtxdist[penum]], graph->adjncy); else gkMPI_Send((void *)(gadjncy+gxadj[vtxdist[penum]]), ssize[penum], IDX_T, penum, 1, comm); } } else gkMPI_Recv((void *)graph->adjncy, graph->nedges, IDX_T, 0, 1, comm, &status); graph->adjwgt = imalloc(graph->nedges*nobj, "ReadGraph: graph->adjwgt"); if (fmt%10 > 0) { /*************************************************/ /* distribute adjwgt array */ if (mype == 0) { for (penum=0; penum<npes; penum++) { ssize[penum] *= nobj; if (penum == mype) icopy(ssize[penum], gadjwgt+(gxadj[vtxdist[penum]]*nobj), graph->adjwgt); else gkMPI_Send((void *)(gadjwgt+(gxadj[vtxdist[penum]]*nobj)), ssize[penum], IDX_T, penum, 1, comm); } } else gkMPI_Recv((void *)graph->adjwgt, graph->nedges*nobj, IDX_T, 0, 1, comm, &status); } else { for (i=0; i<graph->nedges*nobj; i++) graph->adjwgt[i] = 1; } graph->vwgt = imalloc(graph->nvtxs*ncon, "ReadGraph: graph->vwgt"); if ((fmt/10)%10 > 0) { /*************************************************/ /* distribute vwgt array */ if (mype == 0) { for (penum=0; penum<npes; penum++) { ssize[penum] = (vtxdist[penum+1]-vtxdist[penum])*ncon; if (penum == mype) icopy(ssize[penum], gvwgt+(vtxdist[penum]*ncon), graph->vwgt); else gkMPI_Send((void *)(gvwgt+(vtxdist[penum]*ncon)), ssize[penum], IDX_T, penum, 1, comm); } gk_free((void **)&ssize, LTERM); } else gkMPI_Recv((void *)graph->vwgt, graph->nvtxs*ncon, IDX_T, 0, 1, comm, &status); } else { for (i=0; i<graph->nvtxs*ncon; i++) graph->vwgt[i] = 1; } if (mype == 0) gk_free((void **)&gxadj, &gadjncy, &gvwgt, &gadjwgt, LTERM); MALLOC_CHECK(NULL); } /************************************************************************* * This function reads the spd matrix **************************************************************************/ void Mc_SerialReadMetisGraph(char *filename, idx_t *r_nvtxs, idx_t *r_ncon, idx_t *r_nobj, idx_t *r_fmt, idx_t **r_xadj, idx_t **r_vwgt, idx_t **r_adjncy, idx_t **r_adjwgt, idx_t *wgtflag) { idx_t i, k, l; idx_t ncon, nobj, edge, nvtxs, nedges; idx_t *xadj, *adjncy, *vwgt, *adjwgt; char *line, *oldstr, *newstr; idx_t fmt, readew, readvw; idx_t ewgt[1024]; FILE *fpin; line = gk_cmalloc(MAXLINE+1, "line"); if ((fpin = fopen(filename, "r")) == NULL) { printf("Failed to open file %s\n", filename); exit(-1); } oldstr = fgets(line, MAXLINE, fpin); fmt = ncon = nobj = 0; sscanf(line, "%"PRIDX" %"PRIDX" %"PRIDX" %"PRIDX" %"PRIDX"", &nvtxs, &nedges, &fmt, &ncon, &nobj); readew = (fmt%10 > 0); readvw = ((fmt/10)%10 > 0); *wgtflag = 0; if (readew) *wgtflag += 1; if (readvw) *wgtflag += 2; if ((ncon > 0 && !readvw) || (nobj > 0 && !readew)) { printf("fmt and ncon/nobj are inconsistant.\n"); exit(-1); } nedges *=2; ncon = (ncon == 0 ? 1 : ncon); nobj = (nobj == 0 ? 1 : nobj); xadj = imalloc(nvtxs+1, "ReadGraph: xadj"); adjncy = imalloc(nedges, "Mc_ReadGraph: adjncy"); vwgt = (readvw ? imalloc(ncon*nvtxs, "RG: vwgt") : NULL); adjwgt = (readew ? imalloc(nobj*nedges, "RG: adjwgt") : NULL); /* Start reading the graph file */ for (xadj[0]=0, k=0, i=0; i<nvtxs; i++) { while (fgets(line, MAXLINE, fpin) && line[0] == '%'); oldstr = line; newstr = NULL; if (readvw) { for (l=0; l<ncon; l++) { vwgt[i*ncon+l] = strtoidx(oldstr, &newstr, 10); oldstr = newstr; } } for (;;) { edge = strtoidx(oldstr, &newstr, 10) -1; oldstr = newstr; if (readew) { for (l=0; l<nobj; l++) { ewgt[l] = strtoreal(oldstr, &newstr); oldstr = newstr; } } if (edge < 0) break; adjncy[k] = edge; if (readew) for (l=0; l<nobj; l++) adjwgt[k*nobj+l] = ewgt[l]; k++; } xadj[i+1] = k; } fclose(fpin); gk_free((void **)&line, LTERM); *r_nvtxs = nvtxs; *r_ncon = ncon; *r_nobj = nobj; *r_fmt = fmt; *r_xadj = xadj; *r_vwgt = vwgt; *r_adjncy = adjncy; *r_adjwgt = adjwgt; } /************************************************************************* * This function writes out a partition vector **************************************************************************/ void WritePVector(char *gname, idx_t *vtxdist, idx_t *part, MPI_Comm comm) { idx_t i, j, k, l, rnvtxs, npes, mype, penum; FILE *fpin; idx_t *rpart; char partfile[256]; MPI_Status status; gkMPI_Comm_size(comm, &npes); gkMPI_Comm_rank(comm, &mype); if (mype == 0) { sprintf(partfile, "%s.part", gname); if ((fpin = fopen(partfile, "w")) == NULL) errexit("Failed to open file %s", partfile); for (i=0; i<vtxdist[1]; i++) fprintf(fpin, "%"PRIDX"\n", part[i]); for (penum=1; penum<npes; penum++) { rnvtxs = vtxdist[penum+1]-vtxdist[penum]; rpart = imalloc(rnvtxs, "rpart"); MPI_Recv((void *)rpart, rnvtxs, IDX_T, penum, 1, comm, &status); for (i=0; i<rnvtxs; i++) fprintf(fpin, "%"PRIDX"\n", rpart[i]); gk_free((void **)&rpart, LTERM); } fclose(fpin); } else MPI_Send((void *)part, vtxdist[mype+1]-vtxdist[mype], IDX_T, 0, 1, comm); } /************************************************************************* * This function writes out the ordering vector **************************************************************************/ void WriteOVector(char *gname, idx_t *vtxdist, idx_t *order, MPI_Comm comm) { idx_t i, j, k, l, rnvtxs, npes, mype, penum; FILE *fpout; idx_t *rorder, *gorder; char orderfile[256]; MPI_Status status; gkMPI_Comm_size(comm, &npes); gkMPI_Comm_rank(comm, &mype); if (mype == 0) { gorder = ismalloc(vtxdist[npes], 0, "WriteOVector: gorder"); sprintf(orderfile, "%s.order.%"PRIDX"", gname, npes); if ((fpout = fopen(orderfile, "w")) == NULL) errexit("Failed to open file %s", orderfile); for (i=0; i<vtxdist[1]; i++) { gorder[order[i]]++; fprintf(fpout, "%"PRIDX"\n", order[i]); } for (penum=1; penum<npes; penum++) { rnvtxs = vtxdist[penum+1]-vtxdist[penum]; rorder = imalloc(rnvtxs, "rorder"); MPI_Recv((void *)rorder, rnvtxs, IDX_T, penum, 1, comm, &status); for (i=0; i<rnvtxs; i++) { gorder[rorder[i]]++; fprintf(fpout, "%"PRIDX"\n", rorder[i]); } gk_free((void **)&rorder, LTERM); } fclose(fpout); /* Check the global ordering */ for (i=0; i<vtxdist[npes]; i++) { if (gorder[i] != 1) printf("Global ordering problems with index: %"PRIDX" [%"PRIDX"]\n", i, gorder[i]); } gk_free((void **)&gorder, LTERM); } else MPI_Send((void *)order, vtxdist[mype+1]-vtxdist[mype], IDX_T, 0, 1, comm); } /************************************************************************* * This function reads a mesh from a file **************************************************************************/ void ParallelReadMesh(mesh_t *mesh, char *filename, MPI_Comm comm) { idx_t i, j, k, pe; idx_t npes, mype, ier; idx_t gnelms, nelms, your_nelms, etype, maxnelms; idx_t maxnode, gmaxnode, minnode, gminnode; idx_t *elmdist, *elements; idx_t *your_elements; MPI_Status stat; char *line = NULL, *oldstr, *newstr; FILE *fpin = NULL; idx_t esize, esizes[5] = {-1, 3, 4, 8, 4}; idx_t mgcnum, mgcnums[5] = {-1, 2, 3, 4, 2}; gkMPI_Comm_size(comm, &npes); gkMPI_Comm_rank(comm, &mype); elmdist = mesh->elmdist = ismalloc(npes+1, 0, "ReadGraph: elmdist"); if (mype == npes-1) { ier = 0; fpin = fopen(filename, "r"); if (fpin == NULL){ printf("COULD NOT OPEN FILE '%s' FOR SOME REASON!\n", filename); ier++; } MPI_Bcast(&ier, 1, IDX_T, npes-1, comm); if (ier > 0){ fclose(fpin); MPI_Finalize(); exit(0); } line = gk_cmalloc(MAXLINE+1, "line"); while (fgets(line, MAXLINE, fpin) && line[0] == '%'); sscanf(line, "%"PRIDX" %"PRIDX"", &gnelms, &etype); /* Construct elmdist and send it to all the processors */ elmdist[0] = 0; for (i=0,j=gnelms; i<npes; i++) { k = j/(npes-i); elmdist[i+1] = elmdist[i]+k; j -= k; } MPI_Bcast((void *)elmdist, npes+1, IDX_T, npes-1, comm); } else { MPI_Bcast(&ier, 1, IDX_T, npes-1, comm); if (ier > 0){ MPI_Finalize(); exit(0); } MPI_Bcast((void *)elmdist, npes+1, IDX_T, npes-1, comm); } MPI_Bcast((void *)(&etype), 1, IDX_T, npes-1, comm); gnelms = mesh->gnelms = elmdist[npes]; nelms = mesh->nelms = elmdist[mype+1]-elmdist[mype]; mesh->etype = etype; esize = esizes[etype]; mgcnum = mgcnums[etype]; elements = mesh->elements = imalloc(nelms*esize, "ParallelReadMesh: elements"); if (mype == npes-1) { maxnelms = 0; for (i=0; i<npes; i++) { maxnelms = (maxnelms > elmdist[i+1]-elmdist[i]) ? maxnelms : elmdist[i+1]-elmdist[i]; } your_elements = imalloc(maxnelms*esize, "your_elements"); for (pe=0; pe<npes; pe++) { your_nelms = elmdist[pe+1]-elmdist[pe]; for (i=0; i<your_nelms; i++) { oldstr = fgets(line, MAXLINE, fpin); oldstr = line; newstr = NULL; /*************************************/ /* could get element weigts here too */ /*************************************/ for (j=0; j<esize; j++) { your_elements[i*esize+j] = strtoidx(oldstr, &newstr, 10); oldstr = newstr; } } if (pe < npes-1) { MPI_Send((void *)your_elements, your_nelms*esize, IDX_T, pe, 0, comm); } else { for (i=0; i<your_nelms*esize; i++) elements[i] = your_elements[i]; } } fclose(fpin); gk_free((void **)&your_elements, LTERM); } else { MPI_Recv((void *)elements, nelms*esize, IDX_T, npes-1, 0, comm, &stat); } /*********************************/ /* now check for number of nodes */ /*********************************/ minnode = imin(nelms*esize, elements, 1); MPI_Allreduce((void *)&minnode, (void *)&gminnode, 1, IDX_T, MPI_MIN, comm); for (i=0; i<nelms*esize; i++) elements[i] -= gminnode; maxnode = imax(nelms*esize, elements, 1); MPI_Allreduce((void *)&maxnode, (void *)&gmaxnode, 1, IDX_T, MPI_MAX, comm); mesh->gnns = gmaxnode+1; if (mype==0) printf("Nelements: %"PRIDX", Nnodes: %"PRIDX", EType: %"PRIDX"\n", gnelms, mesh->gnns, etype); }
27,873
26.762948
100
c
null
ParMETIS-main/programs/mtest.c
/* * Copyright 1997, Regents of the University of Minnesota * * main.c * * This file contains code for testing teh adaptive partitioning routines * * Started 5/19/97 * George * * $Id: mtest.c,v 1.3 2003/07/25 14:31:47 karypis Exp $ * */ #include <parmetisbin.h> /************************************************************************* * Let the game begin **************************************************************************/ int main(int argc, char *argv[]) { idx_t i, mype, npes, nelms; idx_t *part, *eptr; mesh_t mesh; MPI_Comm comm; idx_t wgtflag, numflag, edgecut, nparts, options[10]; idx_t mgcnum = -1, mgcnums[5] = {-1, 2, 3, 4, 2}, esizes[5] = {-1, 3, 4, 8, 4}; real_t *tpwgts, ubvec[MAXNCON]; gk_malloc_init(); MPI_Init(&argc, &argv); MPI_Comm_dup(MPI_COMM_WORLD, &comm); gkMPI_Comm_size(comm, &npes); gkMPI_Comm_rank(comm, &mype); if (argc < 2) { if (mype == 0) printf("Usage: %s <mesh-file> [NCommonNodes]\n", argv[0]); MPI_Finalize(); exit(0); } ParallelReadMesh(&mesh, argv[1], comm); mgcnum = mgcnums[mesh.etype]; mesh.ncon = 1; if (argc > 2) mgcnum = atoi(argv[2]); if (mype == 0) printf("MGCNUM: %"PRIDX"\n", mgcnum); nparts = npes; tpwgts = rmalloc(nparts*mesh.ncon, "tpwgts"); for (i=0; i<nparts*mesh.ncon; i++) tpwgts[i] = 1.0/(real_t)(nparts); for (i=0; i<mesh.ncon; i++) ubvec[i] = UNBALANCE_FRACTION; part = imalloc(mesh.nelms, "part"); numflag = wgtflag = 0; options[0] = 1; options[PMV3_OPTION_DBGLVL] = 7; options[PMV3_OPTION_SEED] = 0; nelms = mesh.elmdist[mype+1]-mesh.elmdist[mype]; eptr = ismalloc(nelms+1, esizes[mesh.etype], "main; eptr"); MAKECSR(i, nelms, eptr); eptr[nelms]--; /* make the last element different */ ParMETIS_V3_PartMeshKway(mesh.elmdist, eptr, mesh.elements, NULL, &wgtflag, &numflag, &(mesh.ncon), &mgcnum, &nparts, tpwgts, ubvec, options, &edgecut, part, &comm); /* graph = ParallelMesh2Dual(&mesh, mgcnum, comm); MPI_Barrier(comm); MPI_Allreduce((void *)&(graph->nedges), (void *)&gnedges, 1, IDX_T, MPI_SUM, comm); if (mype == 0) printf("Completed Dual Graph -- Nvtxs: %"PRIDX", Nedges: %"PRIDX"\n", graph->gnvtxs, gnedges/2); numflag = wgtflag = 0; ParMETIS_V3_PartKway(graph->vtxdist, graph->xadj, graph->adjncy, NULL, NULL, &wgtflag, &numflag, &(graph->ncon), &nparts, tpwgts, ubvec, options, &edgecut, part, &comm); gk_free((void **)&(graph.vtxdist), &(graph.xadj), &(graph.vwgt), &(graph.adjncy), &(graph.adjwgt), LTERM); */ gk_free((void **)&part, &tpwgts, &eptr, LTERM); MPI_Comm_free(&comm); MPI_Finalize(); gk_malloc_cleanup(0); return 0; }
2,701
25.752475
108
c
null
ParMETIS-main/programs/plotorder.pl
#!/usr/bin/perl die "Usage: plotorder.pl <graphfile> <orderfile> <sizesfile>\n" unless ($#ARGV == 2); $graphfile = shift(@ARGV); $orderfile = shift(@ARGV); $sizesfile = shift(@ARGV); #========================================================================= # Read the graph file #========================================================================= open(FPIN, "<$graphfile"); $_ = <FPIN>; chomp($_); ($nvtxs, $nedges, $flags) = split(' ', $_); $readvw = $flags&2; $readew = $flags&1; $nnz = 0; $xadj[0] = 0; for ($i=0; $i<$nvtxs; $i++) { $_ = <FPIN>; chomp($_); @fields = split(' ', $_); $vwgt[$i] = shift(@fields) if ($readvw); while (@fields) { $adjncy[$nnz] = shift(@fields)-1; $adjwgt[$nnz] = shift(@fields) if ($readew); $nnz++; } $xadj[$i+1] = $nnz; } close(FPIN);
809
21.5
85
pl
null
ParMETIS-main/include/parmetis.h
/* * Copyright 1997-2003, Regents of the University of Minnesota * * parmetis.h * * This file contains function prototypes and constrant definitions for * ParMETIS * * Started 7/21/03 * George * */ #ifndef __parmetis_h__ #define __parmetis_h__ #include <mpi.h> #include <metis.h> #ifndef _MSC_VER #define __cdecl #endif #if IDXTYPEWIDTH == 32 /*#define IDX_T MPI_INT32_T */ #define IDX_T MPI_INT #define KEEP_BIT 0x40000000L #elif IDXTYPEWIDTH == 64 /*#define IDX_T MPI_INT64_T */ #define IDX_T MPI_LONG_LONG_INT #define KEEP_BIT 0x4000000000000000LL #else #error "Incorrect user-supplied value fo IDXTYPEWIDTH" #endif #if REALTYPEWIDTH == 32 #define REAL_T MPI_FLOAT #elif REALTYPEWIDTH == 64 #define REAL_T MPI_DOUBLE #else #error "Incorrect user-supplied value fo REALTYPEWIDTH" #endif /************************************************************************* * Constants **************************************************************************/ #define PARMETIS_MAJOR_VERSION 4 #define PARMETIS_MINOR_VERSION 0 #define PARMETIS_SUBMINOR_VERSION 3 /************************************************************************* * Function prototypes **************************************************************************/ #ifdef __cplusplus extern "C" { #endif /*------------------------------------------------------------------- * API Introduced with Release 3.0 (current API) *--------------------------------------------------------------------*/ int __cdecl ParMETIS_V3_PartKway( idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *vwgt, idx_t *adjwgt, idx_t *wgtflag, idx_t *numflag, idx_t *ncon, idx_t *nparts, real_t *tpwgts, real_t *ubvec, idx_t *options, idx_t *edgecut, idx_t *part, MPI_Comm *comm); int __cdecl ParMETIS_V3_PartGeomKway( idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *vwgt, idx_t *adjwgt, idx_t *wgtflag, idx_t *numflag, idx_t *ndims, real_t *xyz, idx_t *ncon, idx_t *nparts, real_t *tpwgts, real_t *ubvec, idx_t *options, idx_t *edgecut, idx_t *part, MPI_Comm *comm); int __cdecl ParMETIS_V3_PartGeom( idx_t *vtxdist, idx_t *ndims, real_t *xyz, idx_t *part, MPI_Comm *comm); int __cdecl ParMETIS_V3_RefineKway( idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *vwgt, idx_t *adjwgt, idx_t *wgtflag, idx_t *numflag, idx_t *ncon, idx_t *nparts, real_t *tpwgts, real_t *ubvec, idx_t *options, idx_t *edgecut, idx_t *part, MPI_Comm *comm); int __cdecl ParMETIS_V3_AdaptiveRepart( idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *vwgt, idx_t *vsize, idx_t *adjwgt, idx_t *wgtflag, idx_t *numflag, idx_t *ncon, idx_t *nparts, real_t *tpwgts, real_t *ubvec, real_t *ipc2redist, idx_t *options, idx_t *edgecut, idx_t *part, MPI_Comm *comm); int __cdecl ParMETIS_V3_Mesh2Dual( idx_t *elmdist, idx_t *eptr, idx_t *eind, idx_t *numflag, idx_t *ncommonnodes, idx_t **xadj, idx_t **adjncy, MPI_Comm *comm); int __cdecl ParMETIS_V3_PartMeshKway( idx_t *elmdist, idx_t *eptr, idx_t *eind, idx_t *elmwgt, idx_t *wgtflag, idx_t *numflag, idx_t *ncon, idx_t *ncommonnodes, idx_t *nparts, real_t *tpwgts, real_t *ubvec, idx_t *options, idx_t *edgecut, idx_t *part, MPI_Comm *comm); int __cdecl ParMETIS_V3_NodeND( idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *numflag, idx_t *options, idx_t *order, idx_t *sizes, MPI_Comm *comm); int __cdecl ParMETIS_V32_NodeND( idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *vwgt, idx_t *numflag, idx_t *mtype, idx_t *rtype, idx_t *p_nseps, idx_t *s_nseps, real_t *ubfrac, idx_t *seed, idx_t *dbglvl, idx_t *order, idx_t *sizes, MPI_Comm *comm); int __cdecl ParMETIS_SerialNodeND( idx_t *vtxdist, idx_t *xadj, idx_t *adjncy, idx_t *numflag, idx_t *options, idx_t *order, idx_t *sizes, MPI_Comm *comm); #ifdef __cplusplus } #endif /*------------------------------------------------------------------------ * Enum type definitions *-------------------------------------------------------------------------*/ /*! Operation type codes */ typedef enum { PARMETIS_OP_KMETIS, PARMETIS_OP_GKMETIS, PARMETIS_OP_GMETIS, PARMETIS_OP_RMETIS, PARMETIS_OP_AMETIS, PARMETIS_OP_OMETIS, PARMETIS_OP_M2DUAL, PARMETIS_OP_MKMETIS } pmoptype_et; /************************************************************************* * Various constants used for the different parameters **************************************************************************/ /* Matching types */ #define PARMETIS_MTYPE_LOCAL 1 /* Restrict matching to within processor vertices */ #define PARMETIS_MTYPE_GLOBAL 2 /* Remote vertices can be matched */ /* Separator refinement types */ #define PARMETIS_SRTYPE_GREEDY 1 /* Vertices are visted from highest to lowest gain */ #define PARMETIS_SRTYPE_2PHASE 2 /* Separators are refined in a two-phase fashion using PARMETIS_SRTYPE_GREEDY for the 2nd phase */ /* Coupling types for ParMETIS_V3_RefineKway & ParMETIS_V3_AdaptiveRepart */ #define PARMETIS_PSR_COUPLED 1 /* # of partitions == # of processors */ #define PARMETIS_PSR_UNCOUPLED 2 /* # of partitions != # of processors */ /* Debug levels (fields should be ORed) */ #define PARMETIS_DBGLVL_TIME 1 /* Perform timing analysis */ #define PARMETIS_DBGLVL_INFO 2 /* Perform timing analysis */ #define PARMETIS_DBGLVL_PROGRESS 4 /* Show the coarsening progress */ #define PARMETIS_DBGLVL_REFINEINFO 8 /* Show info on communication during folding */ #define PARMETIS_DBGLVL_MATCHINFO 16 /* Show info on matching */ #define PARMETIS_DBGLVL_RMOVEINFO 32 /* Show info on communication during folding */ #define PARMETIS_DBGLVL_REMAP 64 /* Determines if remapping will take place */ #define PARMETIS_DBGLVL_TWOHOP 128 /* Performs a 2-hop matching */ #define PARMETIS_DBGLVL_DROPEDGES 256 /* Drop edges during coarsening */ #define PARMETIS_DBGLVL_FAST 512 /* Reduces #trials for various steps */ #define PARMETIS_DBGLVL_ONDISK 1024 /* Saves non-active graphs to disk */ #endif
6,414
36.95858
93
h
pyCBT
pyCBT-master/LICENSE.md
Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License. Copyright (C) Aivon Oy 2013. The Software is provided "as is" without warranty of any kind, either express or implied, including without limitation any implied warranties of condition, uninterrupted use, merchantability, fitness for a particular purpose, or non-infringement
353
58
245
md
pyCBT
pyCBT-master/README.md
pyCBT ===== Python library for Coulomb Blockade Thermometer (CBT) data fitting. It uses master equation for conductance calculations according to *Pekola et. al. PRL* **73** *(1994)*. See * [Tutorial](http://nbviewer.ipython.org/urls/raw.github.com/AivonOy/pyCBT/master/pyNotebooks/pyCBT%2520tutorial.ipynb) * [Multifit quickstart](http://nbviewer.ipython.org/urls/raw.github.com/AivonOy/pyCBT/master/pyNotebooks/pyCBT%2520multifit%2520quickstart.ipynb) * [Multifit with explanations](http://nbviewer.ipython.org/urls/raw.github.com/AivonOy/pyCBT/master/pyNotebooks/pyCBT%2520MultiFit%2520tutorial.ipynb) * [Capability calculations](http://nbviewer.ipython.org/github/AivonOy/pyCBT/blob/master/pyNotebooks/On%20CBT%20measurement.ipynb?create=1) ###Requirements * Python 2.7.x http://www.python.org/ * numpy http://www.numpy.org/ * scipy http://www.scipy.org/ * matplotlib http://matplotlib.org/ * pyx http://pyx.sourceforge.net/ Packages except pyx have installers. For pyx installation, run pyx installation file ``setup.py`` in shell ``` python setup.py install ``` ### Usage Edit and run example [script](src/example_fit_and_plot.py) ``` python example_fit_and_plot.py ``` that fits a measured CBT curve. ### Cython There exist a cython version of file ``CBT_lib.py`` named ``CBT_lib.pyx`` that can be compiled to C-code according instructions from [cython webpage](http://cython.org/) In Windows compiling using mingw at least works. In OSX Xcode, command line tools have been tested to work. #### Disclaimer The Software is provided "as is" without warranty of any kind, either express or implied, including without limitation any implied warranties of condition, uninterrupted use, merchantability, fitness for a particular purpose, or non-infringement
1,787
30.928571
245
md
pyCBT
pyCBT-master/src/CBT_fit_lib.py
# -*- coding: utf-8 -*- """ @author: Leif Roschier/Aivon Oy This class fits single C_sigma, R_T from a given curve. """ from matplotlib import mlab from numpy import * import matplotlib import matplotlib.pyplot as plt from pylab import figure, show from scipy import optimize from scipy import interpolate from scipy.constants import * from CBT_lib import * from copy import * import time N=2 class CBT_fitter(): """ Class for fitting measured CBT data """ def __init__(self,filename="data/cbt14.txt", T_init=50e-3, island_size_init=1.0, R_tunnel_init=30,TEC_init=100e-3, n_max=200, N=None, sigma=0.2e9,meas_V0=[],meas_R=[],bounds=None,v_offset=0.0,const_P=1e-18,show_first_fit=True, excitation=1e-9,parallel_arrays=20.0, junctions_in_series = 33.0): """ Give data as link to file or with arrays meas_V0 and meas_R with filename=None T_init: initial guess for temperature in (K) island size: island size in 1e-15 (m**3) R_tunnel_init: tunnelling resistance in (kOhm) TEC_init: charging energy in (K) excitation: value for calculating conductance """ self.tic = time.clock() self.parallel_arrays = parallel_arrays self.junctions_in_series= junctions_in_series self.sigma =sigma self.n_max=n_max if N != None: print "N is obsolete" #self.N=N # 23.5.14 LRR self.N=2 self.v_offset=0.0 self.const_P=const_P self.island_size = island_size_init*1e-15 self.R_tunnel_init = R_tunnel_init # kOhm self.T_init = T_init self.TEC_init = TEC_init self.bounds = bounds self.excitation = excitation self.filename=filename if not filename==None: meas_V0,meas_R = loadtxt(filename, delimiter=None,unpack=True) # make chain equal to 2 junctions #meas_R = meas_R/(junctions_in_series/2.0) #OLD # 23.05.14 ADM #meas_R = meas_R*parallel_arrays/junctions_in_series # OLD # 26.05.14 ADM meas_R = meas_R*parallel_arrays/junctions_in_series*self.N #NEW # tunnel resistance per each junction #meas_G0=1.0/(meas_R*parallel_arrays) #OLD # 23.05.14 ADM meas_G0=1.0/meas_R #NEW # tunnel conductance per each junction meas_V0 = meas_V0/junctions_in_series*self.N # potential drop across N junctions # remove voltages around zero indices = [x for x, y in enumerate(meas_V0) if (y >1e-8 or y<-1e-8)] self.meas_G= meas_G0[indices] self.meas_V= meas_V0[indices] self.meas_R = meas_R[indices] self.v_offset = v_offset = 0.0 #print "Initial v_offset %g"%v_offset #print "Const p:%g"%self.const_P self.classic_curve_fitted = False self.full_curve_fitted = False self.v_offset =0.0 def find_offset(self,points=None): """ finds offset voltage """ #find minimum conductance G = array(self.meas_G) min_G_idx = G.argmin() if points==None: num_points = G.size/10 else: num_points = points min_idx = min_G_idx-num_points max_idx = min_G_idx+num_points if min_idx<0: min_idx=0 if max_idx>G.size: max_idx = G.size #print "min_idx:%g"%min_idx #print "max_idx:%g"%max_idx indices = range(min_idx,max_idx+1) self.offset_data={} self.offset_data['x'] = x = array(self.meas_V[indices]) self.offset_data['y'] = y = array(self.meas_G[indices]) self.offset_data['z'] = z = polyfit(x, y, 2) # fit conductance around its minimum with a parabola self.offset_data['p'] = p = poly1d(z) # build the resulting second degree polynomial self.offset_data['y2'] = p(x) self.v_offset = -z[1]/(2.0*z[0]) # offset evaluation (position of the minimum of the parabola) print "============================================" print " Calculated Voltage Offset = %g"%self.v_offset print "============================================" self.meas_V = self.meas_V-self.v_offset def print_offset_curve(self): """ plots offset calculation """ plt.figure(8) plt.plot( (self.offset_data['x']-self.v_offset)*1e3,self.offset_data['y']*1e6,'ro', self.meas_V*1e3, self.meas_G*1e6,'-x', (self.offset_data['x']-self.v_offset)*1e3,self.offset_data['y2']*1e6,'bo') #plt.plot( meas_V,peval( meas_V,plsq[0])/plsq[0][0], meas_V, meas_G/plsq[0][0],'--') plt.title('Offset Corrected Curve') plt.legend(['Fit range', 'Measurement', 'Fit']) plt.xlabel('voltage (mV)') plt.ylabel(r'conductance ($\mu S$)') plt.show() def print_elapset_time(self): toc = time.clock() print "It has taken %g seconds = %g minutes"%(toc-self.tic,(toc-self.tic)/60.0) def fit_classic_curve(self): # initial values for "classic" curve fit p0=[1.0/(self.R_tunnel_init),self.T_init,self.TEC_init] print "=================================================" print "============== Starting Values ===============" print "=================================================" print "Rt_init: %g KOhm T_init: %g mK E_C_init: %g mK"%(1.0/p0[0],p0[1]*1e3,p0[2]*1e3) # 23.05.14 ADM print "=================================================" # initial optimization self.plsq = optimize.fmin_bfgs(self.residuals1, p0, args=(self.meas_G,self.meas_V), gtol=1e-6, full_output=1,maxiter=50, callback=self.call_func) print "=========================================" print "====== After initial optimization: ======" print "=========================================" #print "R_T = %g kOhm"%(1.0/(plsq[0][0]*self.N)) # OLD # 23.05.14 ADM print "R_T = %g kOhm"%(1.0/(self.plsq[0][0])) # NEW # tunnel resistance of the single junction print "R_T_arrays = %g kOhm"%((1.0/self.plsq[0][0])*self.junctions_in_series/self.parallel_arrays) # NEW # tunnel resistance of the array print "T = %g mK"%(self.plsq[0][1]*1000.0) #print "Ec = %g mK"%(self.plsq[0][2]*(N-1.0)/self.N*1000) # OLD # 28.05.14 ADM print "Ec = %g mK"%(self.plsq[0][2]/2*1000) # NEW # charging energy of the single island print "Csigma = %g fF"%(e**2/(self.plsq[0][2]*k)*1e15) self.classic_curve_fitted = True def fit_full_curve(self): # main optimization if self.classic_curve_fitted==True: #R_T_init = (1.0/(self.plsq[0][0]*self.N)) # OLD # 23.05.14 ADM R_T_init = (1.0/(self.plsq[0][0])) # NEW # tunnel resistance of the single junction C_sigma_init=e**2/(self.plsq[0][2]*k)*1e15 T_p_init = self.plsq[0][1]*1e3 else: R_T_init = self.R_tunnel_init C_sigma_init = e**2/(self.TEC_init*k)*1e15 T_p_init = self.T_init*1e3 island_volume_init = self.island_size x1=[R_T_init,C_sigma_init,T_p_init] if self.bounds == None: self.xopt1 = optimize.fmin_bfgs(self.optimize_1, x1, gtol=1e-3,full_output=1, disp=1,callback=self.call_func) else: "Print optimizing with bounds" self.xopt1 = optimize.fmin_l_bfgs_b(self.optimize_1, x1, factr=1e7, approx_grad=True, bounds=self.bounds) toc = time.clock() print "==========================================" print "====== After main optimization: ======" print "==========================================" # 28.05.14 ADM print "R_T = %g"%(self.xopt1[0][0]) print "T = %g mK"%(self.xopt1[0][2]) print "C_sigma = %g "%(self.xopt1[0][1]) self.full_curve_fitted = True self.T_fit = self.xopt1[0][2] self.R_T = self.xopt1[0][0] self.C_sigma = self.xopt1[0][1] def plot_result_initial(self): meas_V = self.meas_V.tolist() meas_G = self.meas_G.tolist() #plt.plot( self.meas_V,self.peval( self.meas_V,self.plsq[0]),'r', self.meas_V, self.meas_G,'--',self.meas_V,self.peval_1( self.meas_V,self.xopt1[0]),'g--') plt.figure(9) plt.plot( self.meas_V*1e3,array(self.peval(self.meas_V,self.plsq[0]))*1e6,'r', array(meas_V)*1e3, array(meas_G)*1e6,'-x') plt.title('Fit to analytic curve') plt.xlabel('voltage (mV)') plt.ylabel(r'conductance ($\mu S$)') plt.legend(['Fit','Measurement']) plt.show() def plot_all_results(self): meas_V = self.meas_V.tolist() meas_G = self.meas_G.tolist() #plt.plot( self.meas_V,self.peval( self.meas_V,self.plsq[0]),'r', self.meas_V, self.meas_G,'--',self.meas_V,self.peval_1( self.meas_V,self.xopt1[0]),'g--') plt.figure(10) plt.plot( self.meas_V,self.peval( self.meas_V,self.plsq[0]),'r', meas_V, meas_G,'-x',meas_V,self.peval_1( meas_V,self.xopt1[0]),'g--') #plt.plot( meas_V,peval( meas_V,plsq[0])/plsq[0][0], meas_V, meas_G/plsq[0][0],'--') plt.title('Least-squares fit numerical model') plt.legend(['Fit1', 'Measurement', 'Fit2']) plt.show() def plot_nonlin_results(self): meas_V = self.meas_V.tolist() meas_G = self.meas_G.tolist() #plt.plot( self.meas_V,self.peval( self.meas_V,self.plsq[0]),'r', self.meas_V, self.meas_G,'--',self.meas_V,self.peval_1( self.meas_V,self.xopt1[0]),'g--') plt.figure(11) plt.plot( array(meas_V)*1e3, array(meas_G)*1e6,'-x', array(meas_V)*1e3,array(self.peval_1( meas_V,self.xopt1[0]))*1e6,'g--') #plt.plot( meas_V,peval( meas_V,plsq[0])/plsq[0][0], meas_V, meas_G/plsq[0][0],'--') plt.title('Nonlinear fit results') plt.legend([ 'Measurement', 'nonlin fit'],loc=4) plt.xlabel('voltage (mV)') plt.ylabel(r'conductance ($\mu S$)') plt.show() def plot_start(self,x): meas_V = self.meas_V.tolist() meas_G = self.meas_G.tolist() #plt.plot( self.meas_V,self.peval( self.meas_V,self.plsq[0]),'r', self.meas_V, self.meas_G,'--',self.meas_V,self.peval_1( self.meas_V,self.xopt1[0]),'g--') plt.figure(12) plt.plot( self.meas_V,self.peval( self.meas_V,self.plsq[0]),'r', meas_V, meas_G,'-x',meas_V,self.peval_1( meas_V,x),'g--') #plt.plot( meas_V,peval( meas_V,plsq[0])/plsq[0][0], meas_V, meas_G/plsq[0][0],'--') plt.title('Least-squares fit numerical model') plt.legend(['Fit1', 'Measurement', 'Fit2'],loc=4) plt.show() # FIRST OPTIMIZATION def g(self,x): return (x*sinh(x)-4*sinh(x/2.0)**2)/(8.0*sinh(x/2.0)**4) def G_optimize_func(self,x,V): #N = 2 Gt_opt = x[0] T_opt = x[1] EC_opt = x[2] return Gt_opt*(1.0-2*(self.N-1.0)/self.N*EC_opt/T_opt*g(e*V/(self.N*k*T_opt))) def residuals(self,p, y, V): #N = 2 Gt_opt,T_opt,EC_opt = p err = y-Gt_opt*(1.0-2*(self.N-1.0)/self.N*EC_opt/T_opt*self.g(e*V/(self.N*k*T_opt))) return err def residuals1(self,p, meas_G, meas_V): #N = 2 Gt_opt,T_opt,EC_opt = p[0],p[1],p[2] # 23.05.14 ADM meas_G = meas_G*1000.0; # make into 1/kOhm total_error = 0.0 for idx,V in enumerate(meas_V): #print "idx %g"%idx #total_error=total_error + (meas_G[idx]-Gt_opt*(1.0-2*(self.N-1.0)/self.N*EC_opt/T_opt*self.g(e*V/(self.N*k*T_opt))))**2 # OLD 23.05.14 ADM total_error=total_error + (meas_G[idx]-Gt_opt/self.N*(1.0-2*(self.N-1.0)/self.N*EC_opt/T_opt*self.g(e*(V)/(self.N*k*T_opt))))**2 return total_error*1e5 def peval(self,V, p): #N = 2 Gt_opt,T_opt,EC_opt = p[0],p[1],p[2] Gt_opt = Gt_opt/1000.0 #return Gt_opt*(1.0-2*(self.N-1.0)/self.N*EC_opt/T_opt*self.g(e*(V)/(self.N*k*T_opt))) # OLD # 23.05.14 ADM return Gt_opt/self.N*(1.0-2*(self.N-1.0)/self.N*EC_opt/T_opt*self.g(e*(V)/(self.N*k*T_opt))) # NEW conductance per N junctions def call_func(self,x): print x # Full optimization def fit_func(self,x,R_T,C_sigma,T_p,island_volume): #calc_conductance_curve_full_spline(sigma,N,meas_V,R_T,C_sigma,T_p,island_volume) return calc_conductance_curve_full_spline(sigma,self.N,x,R_T*1e3,C_sigma*1e-15,T_p,island_volume*1e-15) def optimize_1(self,x): R_T = x[0]*1e3 C_sigma = x[1]*1e-15 T_p = x[2]*1e-3 #island_volume = abs(x[3])*1e-15 G = [] for V in self.meas_V: #calc_G(sigma,N,V,R_T,C_sigma,T_p,island_volume, const_P, eps=1e-9): G.append(calc_G(self.sigma,self.N,V,R_T,C_sigma,T_p,self.island_size, self.const_P,eps=self.excitation)) res = sum((array(self.meas_G)-array(G))**2)*1e10 print "Rt: %g Csigma: %g Tp: %g res: %g"%(R_T,C_sigma,T_p,res) return res def peval_1(self,meas_V,x): R_T = x[0]*1e3 C_sigma = x[1]*1e-15 T_p = x[2]*1e-3 #island_volume = x[3]*1e-15 calc_G_few = calc_conductance_curve_basic(self.sigma,self.N,meas_V,R_T,C_sigma,T_p,self.island_size) return calc_G_few def original_V(self): #gives original data return self.meas_V.tolist() def original_G(self): #gives original data return self.meas_G.tolist() def nonlinfit_G(self): #gives original data nonlinfit_G = self.peval_1(self.meas_V,self.xopt1[0]) return nonlinfit_G def G_curve(self,R_T0,C_sigma0,T_0): R_T = R_T0*1e3 C_sigma = C_sigma0*1e-15 T_p = T_0*1e-3 calc_G = calc_conductance_curve_basic(self.sigma,self.N,self.meas_V,R_T,C_sigma,T_p,self.island_size) return calc_G if __name__ == '__main__': fitter=CBT_fitter() fitter.plot_results()
14,359
43.184615
163
py
pyCBT
pyCBT-master/src/CBT_fit_multi_T.py
# -*- coding: utf-8 -*- """ Created on Wed Oct 09 09:51:03 2013 @author: Leif Roschier/Aivon Oy This class fits single C_sigma, R_T from list of already fitted fitted curves inside classes CBT_fitter (from file CBT_fit_lib.py). """ from scipy import optimize from CBT_lib import * from multiprocessing import Pool,Queue,Value, Process class CBT_multi_fitter(): def __init__(self,fitters,bounds=None, result_text_filename="mfit_results.txt", multiprocess=False,t_data=None, interpolation_table_file="mfit_interpolation_table.txt"): """ fitters = list of classes CBT_fitter """ self.fitters=fitters self.bounds = bounds self.multiprocess=multiprocess self.fit_curves() # do actual fitting self.print_results(result_file=result_text_filename) self.built_interpolation_table(t_data=t_data) self.save_interp_table_to_file(interpolation_table_file) def built_interpolation_table(self,t_data=None): """ builds interpolation curve """ G_list=[] # conductances R_list=[] # resistances, inverse of conductances T_list=[] # list of temperatures if t_data==None: # no explicitely given temperatures T_list_1=arange(5.0e-3,20.0e-3,0.5e-3) T_list_2=arange(21.0e-3,100.0e-3,1.0e-3) T_list_3=arange(100.0e-3,200.0e-3,5e-3) T_list=concatenate((T_list_1,T_list_2,T_list_3)).tolist() else: T_list=t_data T_list.reverse() # make resistances to appear ascending fitter=self.fitters[0] # should be at least one, all have same _multi values for t in T_list: #sigma,N,V,R_T,C_sigma,T_p,island_volume, const_P, eps=1e-9 #calc_G(fitter.sigma,fitter.N,V,R_T,C_sigma,T_p,fitter.island_size, # fitter.const_P,eps=fitter.excitation) this_G = (calc_G(fitter.sigma,fitter.junctions_in_series,1e-9,fitter.R_T_multi*1e3, fitter.C_sigma_multi*1e-15,t,fitter.island_size, fitter.const_P,eps=fitter.excitation))*fitter.parallel_arrays #print "T:%g,R.%g"%(t,1.0/this_G) G_list.append(this_G) R_list.append(1.0/this_G) self.T_list=T_list self.G_list=G_list self.R_list=R_list # interpolating function self.T_func = interpolate.interp1d(array(R_list), array(T_list),bounds_error=False) def save_interp_table_to_file(self,filename="mfit_interpolation_table.txt"): """ saves interpolation curve to file """ fo = open(filename, "wb") for R,T in zip(self.T_list,self.R_list): fo.write("%g\t%g\n"%(R,T)) fo.close def fit_curves(self): """ fits all curves """ # Take average of fit params self.T_fit = 0.0 self.R_T = 0.0 self.C_sigma = 0.0 n=0.0 for fitter in self.fitters: self.R_T=self.R_T+fitter.R_T self.C_sigma=self.C_sigma+fitter.C_sigma n=n+1 self.R_T=self.R_T/n self.C_sigma=self.C_sigma/n print "Average C_sigma:%g"%self.C_sigma print "Average R_T:%g"%self.R_T # actual fitting x1=[self.R_T,self.C_sigma] # initial conditions for fitter in self.fitters: # add temperatures to initial conditions x1.append(fitter.T_fit) print "Initial vector" print x1 # check if multiprocessing is used, does not work in Windows if self.multiprocess: fit_fcn = self.fit_function_multiprocessing else: fit_fcn = self.fit_function if self.bounds == None: self.xopt = optimize.fmin_bfgs(fit_fcn, x1, gtol=1e-4,full_output=1, disp=1,callback=self.call_func) else: "Print optimizing with bounds" self.xopt = optimize.fmin_l_bfgs_b(fit_fcn, x1, factr=1e7, approx_grad=True, bounds=self.bounds) print "xopt:" print self.xopt print "==== After multi optimization: ====" print "R_T = %g"%(self.xopt[0][0]) print "C_sigma = %g "%(self.xopt[0][1]) for idx,T in enumerate(self.xopt[0]): if idx>1: print "T%i = %g mK"%((idx-1),T) # save results for idx,fitter in enumerate(self.fitters): fitter.R_T_multi = self.xopt[0][0] fitter.C_sigma_multi = self.xopt[0][1] fitter.T_multi = self.xopt[0][idx+2] def fit_function(self,x): """ function to be minimized """ R_T = x[0]*1e3 C_sigma = x[1]*1e-15 res=0.0 for idx,fitter in enumerate(self.fitters): # error for every curve T_p=x[2+idx]*1e-3 G = [] for V in fitter.meas_V: # error for every V point #calc_G(sigma,N,V,R_T,C_sigma,T_p,island_volume, const_P, eps=1e-9): G.append(calc_G(fitter.sigma,fitter.N,V,R_T,C_sigma,T_p,fitter.island_size, fitter.const_P,eps=fitter.excitation)) res = res+sum((array(fitter.meas_G)-array(G))**2)*1e10 print "Idx:%g,Rt:%g Csigma:%g Tp:%g res:%g"%(idx,R_T,C_sigma,T_p,res) return res def fit_function_pool(self,x): """ function to be minimized, DOES NOT WORK """ R_T = x[0]*1e3 C_sigma = x[1]*1e-15 res=0.0 pool = Pool(processes=8) for idx,fitter in enumerate(self.fitters): # error for every curve T_p=x[2+idx]*1e-3 G = [] def G_func_local(V): res = calc_G(fitter.sigma,fitter.N,V,R_T,C_sigma,T_p,fitter.island_size, fitter.const_P,eps=fitter.excitation) return res G = pool.map(G_func_local, fitter.meas_V) res = res+sum((array(fitter.meas_G)-array(G))**2)*1e10 print "Idx:%g,Rt:%g Csigma:%g Tp:%g res:%g"%(idx,R_T,C_sigma,T_p,res) return res def fit_function_multiprocessing(self,x): """ minimized funtio with multiprocessing """ R_T = x[0]*1e3 C_sigma = x[1]*1e-15 results=[] procs=[] values = [] for idx,fitter in enumerate(self.fitters): # error for every curve T_p=x[2+idx]*1e-3 results.append(0.0) values.append(Value('d', 0.0)) p = Process( target=self.fit_G_worker, args=(idx,fitter,R_T,C_sigma,T_p,values[-1])) procs.append(p) p.start() for p in procs: p.join(10) total_error=0.0 for error in values: total_error = total_error + error.value print "error:%g"%error.value return total_error def fit_G_worker(self,idx,fitter,R_T,C_sigma,T_p,result_error): """ worker for multiprocessing """ G = [] for V in fitter.meas_V: # error for every V point #calc_G(sigma,N,V,R_T,C_sigma,T_p,island_volume, const_P, eps=1e-9): G.append(calc_G(fitter.sigma,fitter.N,V,R_T,C_sigma,T_p,fitter.island_size, fitter.const_P,eps=fitter.excitation)) result_error.value = sum((array(fitter.meas_G)-array(G))**2)*1e10 print "Idx:%g,Rt:%g Csigma:%g Tp:%g res:%g"%(idx,R_T,C_sigma,T_p,result_error.value) return def call_func(self,x): """ can be used to print information each fit cycle """ #print x pass def print_results(self,result_file="dummy_results.txt"): """ Prints fit results, original and multi """ fo = open(result_file, "wb") print "====================" print " Final results " for idx,fitter in enumerate(self.fitters): print "file:%s"%fitter.filename fo.write("file:%s \n"%fitter.filename) print "R_T(0):%g R_T(multi):%g"%(fitter.R_T,fitter.R_T_multi) fo.write("R_T(0):%g R_T(multi):%g \n"%(fitter.R_T,fitter.R_T_multi)) print "C_sigma(0):%g C_sigma(multi):%g"%(fitter.C_sigma,fitter.C_sigma_multi) fo.write("C_sigma(0):%g C_sigma(multi):%g \n"%(fitter.C_sigma,fitter.C_sigma_multi)) print "T(0):%g T(multi):%g"%(fitter.T_fit,fitter.T_multi) fo.write("T(0):%g T(multi):%g \n"%(fitter.T_fit,fitter.T_multi)) # Open a file fo.close() # Close opend file
8,780
37.178261
108
py
pyCBT
pyCBT-master/src/CBT_lib.py
# -*- coding: utf-8 -*- """ Copyright Aivon Oy (C) 2013 Created on Wed Feb 23 12:09:04 2011 @author: Leif Roschier Calculates conductance of two junctions in series. When scaling voltage, can be used to calculate junction array conductance """ # LRR 23.2.2011 from numpy import * from scipy import * from scipy.constants import * from scipy.interpolate import UnivariateSpline from scipy import interpolate n_max=150 def fii(n,C_sigma): return n*e/C_sigma def DF1plus(n,V,C_sigma): return (e/2.0)*(fii(n,C_sigma)+fii(n+1,C_sigma)-(V)) def DF1minus(n,V,C_sigma): return (e/2.0)*(V-(fii(n,C_sigma)+fii(n-1,C_sigma))) def DF2plus(n,V,C_sigma): return (e/2.0)*(-V-(fii(n,C_sigma)+fii(n-1,C_sigma))) def DF2minus(n,V,C_sigma): return (e/2.0)*((fii(n,C_sigma)+fii(n+1,C_sigma))+V) def gamma1plus(n,V,T,R_T,C_sigma): if (abs(DF1plus(n,V,C_sigma)/(k*T))>1e-12): return -1.0/(e**2*R_T)*DF1plus(n,V,C_sigma)/(1.0-exp(DF1plus(n,V,C_sigma)/(k*T))) else: return -k*T/(e**2*R_T)*1.0 def gamma1minus(n,V,T,R_T,C_sigma): if (abs(DF1minus(n,V,C_sigma)/(k*T))>1e-12): return -1.0/(e**2*R_T)*DF1minus(n,V,C_sigma)/(1.0-exp(DF1minus(n,V,C_sigma)/(k*T))) else: return -k*T/(e**2*R_T)*1.0 #return -1.0/(e**2*R_T)*DF1minus(n,V,C_sigma)/(1.0-exp(DF1minus(n,V,C_sigma)/(k*T))) def gamma2plus(n,V,T,R_T,C_sigma): if (abs(DF2plus(n,V,C_sigma)/(k*T))>1e-12): return -1.0/(e**2*R_T)*DF2plus(n,V,C_sigma)/(1.0-exp(DF2plus(n,V,C_sigma)/(k*T))) else: return -k*T/(e**2*R_T)*1.0 #return -1.0/(e**2*R_T)*DF2plus(n,V,C_sigma)/(1.0-exp(DF2plus(n,V,C_sigma)/(k*T))) def gamma2minus(n,V,T,R_T,C_sigma): #print abs(DF2minus(n,V,C_sigma)/(k*T)) if (abs(DF2minus(n,V,C_sigma)/(k*T))>1e-12): return -1.0/(e**2*R_T)*DF2minus(n,V,C_sigma)/(1.0-exp(DF2minus(n,V,C_sigma)/(k*T))) else: return -k*T/(e**2*R_T)*1.0 #return -1.0/(e**2*R_T)*DF2minus(n,V,C_sigma)/(1.0-exp(DF2minus(n,V,C_sigma)/(k*T))) def calc_current_1(V,T,R_T,C_sigma): """ calculates current when voltage V is over 2 (two) junctions """ sigma=array([1.0]) sigma2 = 1.0/((gamma1plus(-1,V,T,R_T,C_sigma)+gamma2minus(-1,V,T,R_T,C_sigma)+gamma1minus(1,V,T,R_T,C_sigma)+gamma2plus(1,V,T,R_T,C_sigma))/(gamma1plus(0,V,T,R_T,C_sigma)+gamma1minus(0,V,T,R_T,C_sigma)+gamma2plus(0,V,T,R_T,C_sigma)+gamma2minus(0,V,T,R_T,C_sigma))) sigma=append(sigma,sigma2) #print sigma n_real=1 ref_current=1 # will be calculated below stop_calculation = False # stop further calculation for n in range(1,n_max+1): if stop_calculation==False: sigma2 = -((gamma1plus(n-1,V,T,R_T,C_sigma)+gamma2minus(n-1,V,T,R_T,C_sigma))*sigma[-2]-(gamma1plus(n,V,T,R_T,C_sigma)+gamma1minus(n,V,T,R_T,C_sigma)+gamma2plus(n,V,T,R_T,C_sigma)+gamma2minus(n,V,T,R_T,C_sigma))*sigma[-1])/(gamma1minus(n+1,V,T,R_T,C_sigma)+gamma2plus(n+1,V,T,R_T,C_sigma)) sigma=append(sigma,sigma2) n_real=n_real+1 if n==1: ref_curr = sigma[0]*(gamma1plus(0,V,T,R_T,C_sigma)-gamma1minus(0,V,T,R_T,C_sigma)) if n>1: current_curr = sigma[n]*(gamma1plus(n,V,T,R_T,C_sigma)-gamma1minus(n,V,T,R_T,C_sigma)) print sigma print "N:%g current_curr:%g ref_curr:%g"%(n,current_curr,ref_curr) if abs(current_curr/ref_curr)<1e-10: # criteria for stopping calculation stop_calculation=True print "stopped calculation at n = %g"%n if False: # for debug print "------N = %i------"%n print gamma1plus(n,V,T,R_T,C_sigma) print gamma1minus(n,V,T,R_T,C_sigma) print gamma2plus(n,V,T,R_T,C_sigma) print gamma2minus(n,V,T,R_T,C_sigma) sigma_sum = sigma[0]+2*sum(sigma[1:]) #print sigma_sum sigma=sigma/sigma_sum #print sigma current = sigma[0]*(gamma1plus(0,V,T,R_T,C_sigma)-gamma1minus(0,V,T,R_T,C_sigma)) # for n in range(1,n_max+1): for n in range(1,n_real+1): current = current + sigma[n]*(gamma1plus(n,V,T,R_T,C_sigma)-gamma1minus(n,V,T,R_T,C_sigma)) current = current + sigma[n]*(gamma1plus(-n,V,T,R_T,C_sigma)-gamma1minus(-n,V,T,R_T,C_sigma)) current = current*e return current #print current #print current*2*R_T # tests def calc_current(V,T,R_T,C_sigma): """ calculates current when voltage V is over 2 (two) junctions """ sigma=array([1.0]) #sigma[1] = 1.0/((gamma1plus(-1,V,T,R_T,C_sigma)+gamma2minus(-1,V,T,R_T,C_sigma)+gamma1minus(1,V,T,R_T,C_sigma)+gamma2plus(1,V,T,R_T,C_sigma))/(gamma1plus(0,V,T,R_T,C_sigma)+gamma1minus(0,V,T,R_T,C_sigma)+gamma2plus(0,V,T,R_T,C_sigma)+gamma2minus(0,V,T,R_T,C_sigma))); sigma2 = 1.0/((gamma1plus(-1,V,T,R_T,C_sigma)+gamma2minus(-1,V,T,R_T,C_sigma)+gamma1minus(1,V,T,R_T,C_sigma)+gamma2plus(1,V,T,R_T,C_sigma))/(gamma1plus(0,V,T,R_T,C_sigma)+gamma1minus(0,V,T,R_T,C_sigma)+gamma2plus(0,V,T,R_T,C_sigma)+gamma2minus(0,V,T,R_T,C_sigma))) sigma=append(sigma,sigma2) #print sigma #ref_current=1 # will be calculated below ref_curr = sigma[0]*(gamma1plus(0,V,T,R_T,C_sigma)-gamma1minus(0,V,T,R_T,C_sigma)) current = ref_curr + sigma[1]*((gamma1plus(1,V,T,R_T,C_sigma)-gamma1minus(1,V,T,R_T,C_sigma))+(gamma1plus(-1,V,T,R_T,C_sigma)-gamma1minus(-1,V,T,R_T,C_sigma))) stop_calculation = False # stop further calculation #if False: for n in range(2,n_max+1): if stop_calculation==False: #sigma2 = -((gamma1plus(n-1,V,T,R_T,C_sigma)+gamma2minus(n-1,V,T,R_T,C_sigma))*sigma[-2]-(gamma1plus(n,V,T,R_T,C_sigma)+gamma1minus(n,V,T,R_T,C_sigma)+gamma2plus(n,V,T,R_T,C_sigma)+gamma2minus(n,V,T,R_T,C_sigma))*sigma[-1])/(gamma1minus(n+1,V,T,R_T,C_sigma)+gamma2plus(n+1,V,T,R_T,C_sigma)) sigma2 = -((gamma1plus(n-2,V,T,R_T,C_sigma)+gamma2minus(n-2,V,T,R_T,C_sigma))*sigma[n-2]-(gamma1plus(n-1,V,T,R_T,C_sigma)+gamma1minus(n-1,V,T,R_T,C_sigma)+gamma2plus(n-1,V,T,R_T,C_sigma)+gamma2minus(n-1,V,T,R_T,C_sigma))*sigma[n-1])/(gamma1minus(n,V,T,R_T,C_sigma)+gamma2plus(n,V,T,R_T,C_sigma)) sigma=append(sigma,sigma2) current_curr_plus = sigma[n]*(gamma1plus(n,V,T,R_T,C_sigma)-gamma1minus(n,V,T,R_T,C_sigma)) current_curr_minus = sigma[n]*(gamma1plus(-n,V,T,R_T,C_sigma)-gamma1minus(-n,V,T,R_T,C_sigma)) if abs((abs(current_curr_plus+current_curr_minus))/ref_curr)<1e-10: # criteria for stopping calculation stop_calculation=True #print "MAIN: stopped calculation at n = %g"%n #print sigma #print "ref_curr %g"%ref_curr #print "current_curr_plus %g"%current_curr_plus #print "current_curr_minus %g"%current_curr_minus #print abs((abs(current_curr_plus+current_curr_minus))/ref_curr) #print n if False: # for debug print "------N = %i------"%n print gamma1plus(n,V,T,R_T,C_sigma) print gamma1minus(n,V,T,R_T,C_sigma) print gamma2plus(n,V,T,R_T,C_sigma) print gamma2minus(n,V,T,R_T,C_sigma) current += current_curr_plus + current_curr_minus sigma_sum = sigma[0]+2*sum(sigma[1:]) #print sigma_sum ##sigma=sigma/sigma_sum #print sigma current = current/sigma_sum*e return current def calc_current_full(sigma,N,V,R_T,C_sigma,T_p,island_volume,const_P=0.1e-15): """ calculates current with given parameters sigma: electron phonon coupling constant N: junctions V: voltage R_T: tunnel resistance C_sigma: total island capacitance T_p: phonon (bath) temperature island_volume: island volume for e-p coupling """ #<<<<<<< .mine # T_e = (4*(V/N)**2/(R_T*sigma*island_volume)+T_p**5.0)**(1.0/5.0) #print "V %g"%V #print "T_e %g"%T_e #print "T_p %g"%T_p #======= #T_e = (4*(V/N)**2/(R_T*sigma*island_volume)+T_p**5.0)**(1.0/5.0) P_per_junc = pow(V/N,2.0)/R_T+const_P #T_e = (1*(V/N)**2/(R_T*sigma*island_volume)+T_p**5.0)**(1.0/5.0) T_e = (P_per_junc/(sigma*island_volume)+T_p**5.0)**(1.0/5.0) if False: print "V %g"%V print "T_e %g"%T_e print "T_p %g"%T_p #>>>>>>> .r1091 #print "T_e = %g"%T_e current = calc_current(V/(N/2.0),T_e,R_T,C_sigma) return current def calc_temp(sigma,N,V,R_T,C_sigma,T_p,island_volume,const_P=0.1e-15): """ calculates electron temperature sigma: electron phonon coupling constant N: junctions V: voltage R_T: tunnel resistance C_sigma: total island capacitance T_p: phonon (bath) temperature island_volume: island volume for e-p coupling """ P_per_junc = pow(V/N,2.0)/R_T+const_P T_e = (P_per_junc/(sigma*island_volume)+T_p**5.0)**(1.0/5.0) return T_e def calc_conductance_curve(V_list,T,R_T,C_sigma): #test_voltages = arange(-v_max,v_max,v_step) test_currents = [] for V in V_list: test_currents.append(calc_current(V,T,R_T,C_sigma)) #print "V: %g, current %g"%(V,test_currents[-1]) ## calc conductances manually #test_conductances = [] #for idx,V in enumerate (test_currents[1:-2]): # if idx==0: # print idx # test_conductances.append((test_currents[idx+2]-test_currents[idx])/(2.0*v_step)) # #test_voltages_G = test_voltages[1:-2] # # SPLINE # spline = UnivariateSpline(V_list,test_currents,s=0) #print "test_conductances" #indices = [x for x, y in enumerate(col1) if (y >0.7 or y<-0.7)] test_conductances = [] for v_iter in V_list: test_conductances.append(spline.derivatives(v_iter)[1]) return test_conductances #print test_conductances ''' extern double calc_G(double sigma,double N,double V,double R_T,double C_sigma,double T_p,double island_volume, double const_P,double eps) { double curr[4]; double eps2 = eps/2.0; /* then differential is calculated in given range */ if (eps2==0) { /* 0.1 nanovolts if zero */ eps2=1e-10; } curr[0] = calc_current_full(sigma,N,V+2*eps2,R_T,C_sigma,T_p,island_volume,const_P); curr[1] = calc_current_full(sigma,N,V+1*eps2,R_T,C_sigma,T_p,island_volume,const_P); curr[2] = calc_current_full(sigma,N,V-1*eps2,R_T,C_sigma,T_p,island_volume,const_P); curr[3] = calc_current_full(sigma,N,V-2*eps2,R_T,C_sigma,T_p,island_volume,const_P); double R = (-curr[0]+8*curr[1]-8*curr[2]+curr[3])/(12.0*eps2); return R; ''' def calc_G(sigma,N,V,R_T,C_sigma,T_p,island_volume, const_P, eps=1e-9): curr=[0.0,0.0,0.0,0.0] eps2 = eps/2.0 # then differential is calculated in given range */ if (eps2==0): # 0.1 nanovolts if zero */ eps2=1e-10 curr[0] = calc_current_full(sigma,N,V+2.0*eps2,R_T,C_sigma,T_p,island_volume,const_P) curr[1] = calc_current_full(sigma,N,V+1.0*eps2,R_T,C_sigma,T_p,island_volume,const_P) curr[2] = calc_current_full(sigma,N,V-1.0*eps2,R_T,C_sigma,T_p,island_volume,const_P) curr[3] = calc_current_full(sigma,N,V-2.0*eps2,R_T,C_sigma,T_p,island_volume,const_P) R = (-curr[0]+8.0*curr[1]-8.0*curr[2]+curr[3])/(12.0*eps2) return R def calc_conductance_curve_full(sigma,N,V_list,R_T,C_sigma,T_p,island_volume): """ Calculates full conductance curve taking into account self-heating """ test_currents = [] for V in V_list: test_currents.append(calc_current_full(sigma,N,V,R_T,C_sigma,T_p,island_volume)) # SPLINE spline = UnivariateSpline(V_list,test_currents,s=0) test_conductances = [] for v_iter in V_list: test_conductances.append(spline.derivatives(v_iter)[1]) return test_conductances def calc_conductance_curve_basic(sigma,N,V_list,R_T,C_sigma,T_p,island_volume, const_P=1e-18, eps=1e-9): """ Calculates conductance curve without any spline or other tricks """ conductances=[] for point in V_list: conductances.append(calc_G(sigma,N,point,R_T,C_sigma,T_p,island_volume, const_P, eps)) return conductances def calc_conductance_curve_few_points(sigma,N,V_list,R_T,C_sigma,T_p,island_volume): """ When only few points extra points are added in order to make spline approximation correct """ extra_points = [] for point in V_list: extra_points.append(0.99001*point) extra_points.append(0.95001*point) extra_points.append(1.01001*point) extra_points.append(1.05001*point) all_V_points = sort(V_list + extra_points).tolist() test_conductances = calc_conductance_curve_full(sigma,N,all_V_points,R_T,C_sigma,T_p,island_volume) # get the results in original order sparse_conductances=[] for point in V_list: sparse_conductances.append(test_conductances[all_V_points.index(point)]) return sparse_conductances def calc_conductance_curve_full_spline(sigma,N,meas_V,R_T,C_sigma,T_p,island_volume): v_min = min(meas_V) v_max = max(meas_V) v_step = (v_max-v_min)/201.0 test_voltages = arange(v_min,v_max+v_step,v_step) calc_G_few = calc_conductance_curve_full(sigma,N,test_voltages,R_T,C_sigma,T_p,island_volume) interpolator = interpolate.interp1d(test_voltages, calc_G_few, kind='cubic') calc_G = [] for V in meas_V: calc_G.append(interpolator(V)) return calc_G
13,472
42.46129
318
py
pyCBT
pyCBT-master/src/CBT_plot_data_pyx.py
# -*- coding: utf-8 -*- """ Created on Tue Aug 06 14:03:31 2013 @author: Leif """ from pyx import * from numpy import * class CBT_plot_data_pyx: def __init__(self,fitters): self.fitters=fitters def plot_data_given_params(self,T,R_T,C_sigma,filename="result_pfit.pdf"): """ Plots data with given params. T: array of temperatures R_T: scalar tunnelling resistance C_sigma: scalar island capacitance """ datas=[] v_min=0.0 v_max=0.0 for i,fitter in enumerate(self.fitters): datas.append({}) datas[i]['V_data'] = (array(fitter.original_V())*1e6*fitter.junctions_in_series) datas[i]['G_orig'] = (array(fitter.original_G())*1e6) datas[i]['G_tuned'] = (array(fitter.G_curve(R_T, C_sigma,T[i]))*1e6) datas[i]['T_tuned'] = T[i] v_min_0 =datas[i]['V_data'].min() v_max_0 =datas[i]['V_data'].max() if (v_min_0<v_min): v_min=v_min_0 if (v_max_0>v_max): v_max=v_max_0 #plot datas g = graph.graphxy(width=8,y=graph.axis.linear(title="$G$ ($\mu$S)"), x=graph.axis.linear(title="$V$($\mu$V)", min=v_min,max=v_max)) for data in datas: g.plot(graph.data.values(x=data['V_data'],y=data['G_tuned'], title="$T_{fit}$ = %g"%data['T_tuned']), [graph.style.line(lineattrs=[style.linewidth.thick, style.linestyle.solid, color.rgb.red])]) g.plot(graph.data.values(x=data['V_data'],y=data['G_orig']), [graph.style.symbol(symbol=graph.style.symbol.circle,size=0.05*unit.v_cm)]) #g.plot(graph.data.values(x=data['V_data'],y=data['G_orig']), # [graph.style.line(lineattrs=[style.linewidth.thin, style.linestyle.dotted, # color.rgb.blue])]) g.dolayout() # or provide one list containing the whole points g.writePDFfile(filename) def plot_data(self,filename='result.pdf'): """ plots fit result """ datas=[] v_min=0.0 v_max=0.0 for i,fitter in enumerate(self.fitters): datas.append({}) datas[i]['V_data'] = (array(fitter.original_V())*1e6*fitter.junctions_in_series) datas[i]['G_orig'] = (array(fitter.original_G())*1e6) datas[i]['G_fit'] = (array(fitter.nonlinfit_G())*1e6) datas[i]['T_fit'] = fitter.T_fit v_min_0 =datas[i]['V_data'].min() v_max_0 =datas[i]['V_data'].max() if (v_min_0<v_min): v_min=v_min_0 if (v_max_0>v_max): v_max=v_max_0 #plot datas g = graph.graphxy(width=8,y=graph.axis.linear(title="$G$ ($\mu$S)"), x=graph.axis.linear(title="$V$($\mu$V)", min=v_min,max=v_max), key=graph.key.key(pos="tr", dist=0.1)) for data in datas: g.plot(graph.data.values(x=data['V_data'],y=data['G_fit'], title="$T_{fit}$ = %3.1f"%data['T_fit']), [graph.style.line(lineattrs=[style.linewidth.thick, style.linestyle.solid, color.rgb.red])]) g.plot(graph.data.values(x=data['V_data'],y=data['G_orig'], title="meas data"), [graph.style.symbol(symbol=graph.style.symbol.circle,size=0.05*unit.v_cm)]) #g.plot(graph.data.values(x=data['V_data'],y=data['G_orig']), # [graph.style.line(lineattrs=[style.linewidth.thin, style.linestyle.dotted, # color.rgb.blue])]) g.dolayout() g.writePDFfile(filename) def plot_multi_data(self,filename='result.pdf'): """ plots data """ datas=[] for i,fitter in enumerate(self.fitters): datas.append({}) datas[i]['V_data'] = (array(fitter.original_V())*1e6*fitter.junctions_in_series) datas[i]['G_orig'] = (array(fitter.original_G())*1e6) datas[i]['G_fit'] = (array(fitter.G_curve(fitter.R_T_multi, fitter.C_sigma_multi,fitter.T_multi))*1e6) datas[i]['T_fit'] = fitter.T_fit v_min =datas[i]['V_data'].min() v_max =datas[i]['V_data'].max() #print datas g = graph.graphxy(width=8,y=graph.axis.linear(title=r"$G$ ($\mu$S)"), x=graph.axis.linear(title=r"$V$($\mu$V)", min=v_min,max=v_max)) for data in datas: g.plot(graph.data.values(x=data['V_data'],y=data['G_fit'], title="$T_{fit}$ = %g"%data['T_fit']), [graph.style.line(lineattrs=[style.linewidth.thick, style.linestyle.solid, color.rgb.red])]) g.plot(graph.data.values(x=data['V_data'],y=data['G_orig']), [graph.style.symbol(symbol=graph.style.symbol.circle,size=0.05*unit.v_cm)]) #g.plot(graph.data.values(x=data['V_data'],y=data['G_orig']), # [graph.style.line(lineattrs=[style.linewidth.thin, style.linestyle.dotted, # color.rgb.blue])]) g.dolayout() # or provide one list containing the whole points g.writePDFfile(filename) def plot_data_1(self,filename='result1.pdf'): datas=[] for i,fitter in enumerate(self.fitters): datas.append({}) datas[i]['V_data'] = (array(fitter.original_V())*1e6*fitter.junctions_in_series) datas[i]['G_orig'] = (array(fitter.original_G())*1e6) datas[i]['G_fit'] = (array(fitter.nonlinfit_G())*1e6) datas[i]['T_fit'] = fitter.T_fit v_min =datas[i]['V_data'].min() v_max =datas[i]['V_data'].max() g = graph.graphxy(width=8, key=graph.key.key()) As = [0.3, 0.6, 0.9] d = [graph.data.join([graph.data.values(x_a=datas[i]['V_data'],y_a=datas[i]['G_fit'],context=dict(A=A)), graph.data.values(x_b=datas[i]['V_data'],y_b=datas[i]['G_orig'])], title=r"$A=%g$" % A) for i, A in enumerate(As)] attrs = [color.gradient.RedBlue] g.plot(d, [graph.style.pos(usenames=dict(x="x_a", y="y_a")), graph.style.line(attrs), graph.style.pos(usenames=dict(x="x_b", y="y_b")), graph.style.symbol(graph.style.symbol.changesquare, symbolattrs=attrs, size=0.1)])
7,069
44.320513
112
py
pyCBT
pyCBT-master/src/CBT_secondary_temp.py
# -*- coding: utf-8 -*- """ Created on Wed Oct 09 15:45:21 2013 @author: Leif Roschier/Aivon Oy This class CBT_secondary_temp is used as interpolator to find temperature from conductance minimum. List of resistances is calculated from temperatures and interpolation function is generated. """ from CBT_lib import * from scipy import interpolate from numpy import * import matplotlib.pyplot as plt class CBT_secondary_temp(): def __init__(self,C_sigma,R_T,sigma=0.2e9,island_vol=200e-15, T_min=5e-3,T_max=200e-3,T_step=0.5e-3, N_parallel=20, N_series=33, const_P=0.5e-15, excitation=10e-6): """ C_sigma: sum capacitance per island R_T: tunnelling resistance sigma: electron-phonon coupling island_vol: island volume T_min, T_max, T_step: params for interpolating function calc N_parallel: junctions in parallel N_series: junctions in series const_P: constant power heating per junction excitation: measurement AC voltage, used in numerical derivative """ G=[] R=[] T=[] T_list_1=arange(5.0e-3,20.0e-3,0.5e-3) T_list_2=arange(21.0e-3,100.0e-3,1.0e-3) T_list_3=arange(100.0e-3,200.0e-3,5e-3) T_list_4=arange(200.0e-3,1.0,50e-3) T_list_5=arange(1.0,10.0,0.5) T_list=concatenate((T_list_1,T_list_2,T_list_3,T_list_4,T_list_5)) #for t in arange(T_min, T_max+T_step,T_step): for t in T_list: T.append(t) #sigma,N,V,R_T,C_sigma,T_p,island_volume, const_P, eps=1e-9 this_G = (calc_G(sigma,N_series,1e-9,R_T,C_sigma,t,island_vol, const_P,excitation/N_series))*N_parallel #print "T:%g,R.%g"%(t,1.0/this_G) G.append(this_G) R.append(1.0/this_G) #z = polyfit(G, T, 20) #p = poly1d(z) #GG = p(T) if 0: plt.figure(8) #plt.plot(T,G,'ro',T,GG,'b-') plt.plot(T,G,'ro') R.reverse() T.reverse() if 0: plt.figure(18) plt.plot(T,R,'ro') self.T_func = interpolate.interp1d(array(R), array(T),bounds_error=False) if __name__ == '__main__': C_sigma = 231.033e-15 R_T = 25.4083e3 sigma=0.2e9 island_vol=200e-15 cbt_secondary = CBT_secondary_temp(C_sigma,R_T) R_test=48687.271436 print "temp at %g kOhm = %g mK"%(R_test,cbt_secondary.T_func(R_test)*1000)
2,551
32.578947
85
py
pyCBT
pyCBT-master/src/example_fit_and_plot.py
# -*- coding: utf-8 -*- """ Created on Fri Aug 09 12:28:35 2013 @author: Leif """ from CBT_lib import * from CBT_fit_lib import * from CBT_plot_data_pyx import * parallel_arrays = 20.0 N_junctions=33.0 excitation = 30e-6/N_junctions T_init = 10e-3 # K island_size_init=400.0 #x 1e-15 m3 R_tunnel_init=28.0 # kOhm #R_tunnel_init=1.0 # kOhm TEC_init=5e-3 # K #R,C,T,vol #bounds = [(1.0,200.0),(1.0,200.0),(5.0,100.0),(0.2,200.0)] #bounds = [(1.0,100.0),(100.0,920.0),(5.0,250.0)] bounds = [(1.0,100.0),(230.0,240.0),(5.0,250.0)] #bounds = None filenames = ["data/test_meas_data.txt"] fitters=[] for i,filename in enumerate(filenames): fitter=CBT_fitter(filename=filename,T_init=T_init,island_size_init=island_size_init, R_tunnel_init=R_tunnel_init,TEC_init=TEC_init, bounds=bounds,const_P=500e-18, excitation=excitation,parallel_arrays=parallel_arrays, junctions_in_series = N_junctions) fitter.find_offset(5) fitter.print_offset_curve() fitter.fit_classic_curve() fitter.plot_result_initial() fitter.fit_full_curve() fitter.print_elapset_time() fitter.plot_nonlin_results() fitters.append(fitter) #fitter.plot_all_results() cc = CBT_plot_data_pyx(fitters) cc.plot_data(filename="res_8p5_50_100")
1,336
25.74
88
py
pyCBT
pyCBT-master/src/example_multi_fit.py
# -*- coding: utf-8 -*- """ Created on Tue Oct 22 13:56:30 2013 @author: Leif Roschier/Aivon Oy """ """ This is example script to fit CBT R-V curves at different temperatures simultaneously in order to find C_sigma and R_T. Script fits first all separate curves with class CBT_fitter to get initial values for final fitting using class CBT_multi_fitter. """ from CBT_lib import * from CBT_fit_lib import * from CBT_plot_data_pyx import * from CBT_fit_multi_T import * import time start = time.time() # start taking time parallel_arrays = 20.0 # arrays parallel N_junctions=33.0 # junctions in each array excitation = 30e-6/N_junctions # excitation of measurement island_size_init=400.0 #x 1e-15 m3, island size for heating calculations # initial values for optimization T_init = 10e-3 # K, initial guess for temperature R_tunnel_init=28.0 # kOhm TEC_init=5e-3 # K # If bounds given, they are used to limit optimization #R,C,T bounds = [(1.0,100.0),(230.0,240.0),(5.0,250.0)] #(min,max) #bounds = None # actual measurement files to be fitted filenames = [ "data/sample_T2.txt", "data/sample_T3.txt", "data/sample_T4.txt", "data/sample_T5.txt", "data/sample_T6.txt", ] """ filenames = [ "data/sample_T2.txt", "data/sample_T5.txt", ] """ results_txt_file = "mfit_results_41A4_t.txt" # C_sigma and R_T of fit result_pdf_1="41A4_multifit1.pdf" # conductance curves and fits result_pdf_2="41A4_multifit2.pdf" interpolation_filename="41A4_interpolation_table.txt" # separate fitting of each curve fitters=[] # list of classes CBT_fitter that also store results for i,filename in enumerate(filenames): fitter=CBT_fitter(filename=filename,T_init=T_init,island_size_init=island_size_init, R_tunnel_init=R_tunnel_init,TEC_init=TEC_init, bounds=bounds,const_P=500e-18, excitation=excitation,parallel_arrays=parallel_arrays, junctions_in_series = N_junctions) fitter.find_offset(5) # finds offset with 5 points from minimum each direction #fitter.print_offset_curve() fitter.fit_classic_curve() # fit analytic curve to get starting point for nonlin fit #fitter.plot_result_initial() fitter.fit_full_curve() # nonlin fitting fitter.print_elapset_time() #fitter.plot_nonlin_results() fitters.append(fitter) # save results #fitter.plot_all_results() # fitting all together multi_fitter = CBT_multi_fitter(fitters, result_text_filename=results_txt_file, interpolation_table_file=interpolation_filename) # plot results cc = CBT_plot_data_pyx(fitters) cc.plot_multi_data(filename=result_pdf_1) cc.plot_data(filename=result_pdf_2) print "it took", time.time() - start, "seconds."
2,792
30.738636
88
py
pyCBT
pyCBT-master/src/readme.md
### Source code Files: * ``CBT_fit_lib.py``: encapsulates fitting of curve into class CBT_fitter * ``CBT_lib.py``: library for calculating I,V,G * ``CBT_lib.pyx``: cythonized (for cython) version of ``CBT_lib.py`` * ``CBT_plot_data_pyx.py`` : plotting with pyx library (do not mix with .pyx cython files) * ``example_fit_and_plot.py``: example script * ``example_multi_fit.py``: example script for fitting multiple curves simultaneously to get C_sigma and R_T
464
45.5
109
md
pyCBT
pyCBT-master/src/setup_CBT_lib.py
# -*- coding: utf-8 -*- """ Created on Wed May 15 14:54:55 2013 @author: Leif Roschier Copyright Aivon Oy (C) 2013 """ import pyximport pyximport.install(setup_args={"script_args":["--compiler=mingw32"]}, reload_support=True) from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext setup( cmdclass = {'build_ext': build_ext}, ext_modules = [Extension("CBT_lib", ["CBT_lib.pyx"])] )
451
22.789474
89
py
filebench
filebench-master/aslr.c
/* * mmap() call with MAP_FIXED flag does not guarantee that the allocated memory * region is not overlapped with the previously existant mappings. According to * POSIX, old mappings are silently discarded. There is no generic way to * detect overlap. If a silent overlap occurs, strange runtime errors might * happen, because we might overlap stack, libraries, anything else. * * Since we always fork+exec same binary (filebench), theoretically all the * mappings should be the same, so no overlap should happen. However, if * virtual Address Space Layout Randomization (ASLR) is enabled on the target * machine - overlap is very likely (especially if workload defines a lot of * processes). We observed numerous segmentation faults on CentOS because of * that. * * The function below disables ASLR in Linux. In future, more platform-specific * functions should be added. */ #include "config.h" #if defined(HAVE_SYS_PERSONALITY_H) #include <sys/personality.h> #endif #include "filebench.h" #include "aslr.h" #if defined(HAVE_SYS_PERSONALITY_H) && defined(HAVE_ADDR_NO_RANDOMIZE) void linux_disable_aslr() { int r; (void) personality(0xffffffff); r = personality(0xffffffff | ADDR_NO_RANDOMIZE); if (r == -1) filebench_log(LOG_ERROR, "Could not disable ASLR"); } #else /* HAVE_SYS_PERSONALITY_H && HAVE_ADDR_NO_RANDOMIZE */ void other_disable_aslr() { filebench_log(LOG_INFO, "Per-process disabling of ASLR is not " "supported on this system. " "For Filebench to work properly, " "disable ASLR manually for the whole system. " "On Linux it can be achieved by " "\"sysctl kernel.randomize_va_space=0\" command. " "(the change does not persist across reboots)"); } #endif /* HAVE_SYS_PERSONALITY_H && HAVE_ADDR_NO_RANDOMIZE */
1,777
33.862745
79
c
filebench
filebench-master/aslr.h
#ifndef _ASLR_H #define _ASLR_H #include <filebench.h> #if defined(HAVE_SYS_PERSONALITY_H) && defined(HAVE_ADDR_NO_RANDOMIZE) extern void linux_disable_aslr(); static inline void disable_aslr() { return linux_disable_aslr(); } #else /* HAVE_SYS_PERSONALITY_H && HAVE_ADDR_NO_RANDOMIZE */ extern void other_disable_aslr(); static inline void disable_aslr() { return other_disable_aslr(); } #endif /* HAVE_SYS_PERSONALITY_H && HAVE_ADDR_NO_RANDOMIZE */ #endif /* _ASLR_H */
479
17.461538
70
h
filebench
filebench-master/eventgen.c
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * Portions Copyright 2008 Denis Cheng */ /* * The event generator in this module is the producer half of a metering system * which blocks flowops using consumer routines in the flowop_library.c module. * Four routines in that module can limit rates by event rate * (flowoplib_eventlimit), by I/O operations rate (flowoplib_iopslimit()), by * operations rate (flowoplib_opslimit), or by I/O bandwidth limit * (flowoplib_bwlimit). By setting appropriate event generation rates, required * calls per second, I/O ops per second, file system ops per second, or I/O * bandwidth per second limits can be set. Note, the generated events are * shared with all consumer flowops, of which their will be one for each * process / thread instance which has a consumer flowop defined in it. */ #include <sys/time.h> #include "filebench.h" #include "vars.h" #include "eventgen.h" #include "flowop.h" #include "ipc.h" #define FB_SEC2NSEC 1000000000UL /* * The producer side of the event system. Once eventgen_hz has been set by * eventgen_setrate(), the routine sends eventgen_hz events per second until * the program terminates. Events are posted by incrementing * filebench_shm->shm_eventgen_q by the number of generated events then * signalling the condition variable filebench_shm->shm_eventgen_cv to indicate * to event consumers that more events are available. * * Eventgen_thread attempts to sleep for 10 event periods, then, once awakened, * determines how many periods actually passed since sleeping, and issues a set * of events equal to the number of periods that it slept, thus keeping the * average rate at the requested rate. */ static void eventgen_thread(void) { hrtime_t last; last = gethrtime(); filebench_shm->shm_eventgen_enabled = FALSE; while (1) { struct timespec sleeptime; hrtime_t delta; int count, rate; if (filebench_shm->shm_eventgen_hz == NULL) { (void) sleep(1); continue; } else { rate = avd_get_int(filebench_shm->shm_eventgen_hz); if (rate > 0) filebench_shm->shm_eventgen_enabled = TRUE; else continue; } /* Sleep for [10 x period] */ sleeptime.tv_sec = 0; sleeptime.tv_nsec = FB_SEC2NSEC / rate; sleeptime.tv_nsec *= 10; if (sleeptime.tv_nsec < 1000UL) sleeptime.tv_nsec = 1000UL; sleeptime.tv_sec = sleeptime.tv_nsec / FB_SEC2NSEC; if (sleeptime.tv_sec > 0) sleeptime.tv_nsec -= (sleeptime.tv_sec * FB_SEC2NSEC); (void)nanosleep(&sleeptime, NULL); delta = gethrtime() - last; last = gethrtime(); count = (rate * delta) / FB_SEC2NSEC; filebench_log(LOG_DEBUG_SCRIPT, "delta %lluns count %d", (u_longlong_t)delta, count); /* Send 'count' events */ (void)ipc_mutex_lock(&filebench_shm->shm_eventgen_lock); /* * Keep the producer with a max of 5 second depth. * Events accumulate in shm_eventgen_cv even before * worker threads are created. But eventgen_reset() * drops shm_eventgen_q to zero after the worker threads * are created. */ if (filebench_shm->shm_eventgen_q < (5 * rate)) filebench_shm->shm_eventgen_q += count; (void)pthread_cond_signal(&filebench_shm->shm_eventgen_cv); (void)ipc_mutex_unlock(&filebench_shm->shm_eventgen_lock); } } /* * Creates a thread to run the event generator eventgen_thread routine. */ void eventgen_init(void) { pthread_t tid; if (pthread_create(&tid, NULL, (void *(*)(void *))eventgen_thread, 0) != 0) { filebench_log(LOG_ERROR, "create timer thread failed: %s", strerror(errno)); exit(1); } } /* * Sets the event generator rate to that supplied by * var_t *rate. */ void eventgen_setrate(avd_t rate) { filebench_shm->shm_eventgen_hz = rate; if (rate == NULL) { filebench_log(LOG_ERROR, "eventgen_setrate() called without a rate"); return; } } /* * Clears the event queue so we have a clean start */ void eventgen_reset(void) { filebench_shm->shm_eventgen_q = 0; }
4,841
27.650888
79
c
filebench
filebench-master/eventgen.h
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _FB_EVENTGEN_H #define _FB_EVENTGEN_H #include "filebench.h" void eventgen_init(void); void eventgen_setrate(avd_t rate); void eventgen_reset(void); #endif /* _FB_EVENTGEN_H */
1,115
30
70
h
filebench
filebench-master/fb_avl.c
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ /* * Generic AVL tree implementation for Filebench use. * Adapted from the avl.c open source code used in the Solaris kernel. * * A complete description of AVL trees can be found in many CS textbooks. * * Here is a very brief overview. An AVL tree is a binary search tree that is * almost perfectly balanced. By "almost" perfectly balanced, we mean that at * any given node, the left and right subtrees are allowed to differ in height * by at most 1 level. * * This relaxation from a perfectly balanced binary tree allows doing * insertion and deletion relatively efficiently. Searching the tree is * still a fast operation, roughly O(log(N)). * * The key to insertion and deletion is a set of tree maniuplations called * rotations, which bring unbalanced subtrees back into the semi-balanced state. * * This implementation of AVL trees has the following peculiarities: * * - The AVL specific data structures are physically embedded as fields * in the "using" data structures. To maintain generality the code * must constantly translate between "avl_node_t *" and containing * data structure "void *"s by adding/subracting the avl_offset. * * - Since the AVL data is always embedded in other structures, there is * no locking or memory allocation in the AVL routines. This must be * provided for by the enclosing data structure's semantics. Typically, * avl_insert()/_add()/_remove()/avl_insert_here() require some kind of * exclusive write lock. Other operations require a read lock. * * - The implementation uses iteration instead of explicit recursion, * since it is intended to run on limited size kernel stacks. Since * there is no recursion stack present to move "up" in the tree, * there is an explicit "parent" link in the avl_node_t. * * - The left/right children pointers of a node are in an array. * In the code, variables (instead of constants) are used to represent * left and right indices. The implementation is written as if it only * dealt with left handed manipulations. By changing the value assigned * to "left", the code also works for right handed trees. The * following variables/terms are frequently used: * * int left; // 0 when dealing with left children, * // 1 for dealing with right children * * int left_heavy; // -1 when left subtree is taller at some node, * // +1 when right subtree is taller * * int right; // will be the opposite of left (0 or 1) * int right_heavy;// will be the opposite of left_heavy (-1 or 1) * * int direction; // 0 for "<" (ie. left child); 1 for ">" (right) * * Though it is a little more confusing to read the code, the approach * allows using half as much code (and hence cache footprint) for tree * manipulations and eliminates many conditional branches. * * - The avl_index_t is an opaque "cookie" used to find nodes at or * adjacent to where a new value would be inserted in the tree. The value * is a modified "avl_node_t *". The bottom bit (normally 0 for a * pointer) is set to indicate if that the new node has a value greater * than the value of the indicated "avl_node_t *". */ #include "filebench.h" #include "fb_avl.h" /* * Small arrays to translate between balance (or diff) values and child indeces. * * Code that deals with binary tree data structures will randomly use * left and right children when examining a tree. C "if()" statements * which evaluate randomly suffer from very poor hardware branch prediction. * In this code we avoid some of the branch mispredictions by using the * following translation arrays. They replace random branches with an * additional memory reference. Since the translation arrays are both very * small the data should remain efficiently in cache. */ static const int avl_child2balance[2] = {-1, 1}; static const int avl_balance2child[] = {0, 0, 1}; /* * Walk from one node to the previous valued node (ie. an infix walk * towards the left). At any given node we do one of 2 things: * * - If there is a left child, go to it, then to it's rightmost descendant. * * - otherwise we return thru parent nodes until we've come from a right child. * * Return Value: * NULL - if at the end of the nodes * otherwise next node */ void * avl_walk(avl_tree_t *tree, void *oldnode, int left) { size_t off = tree->avl_offset; avl_node_t *node = AVL_DATA2NODE(oldnode, off); int right = 1 - left; int was_child; /* * nowhere to walk to if tree is empty */ if (node == NULL) return (NULL); /* * Visit the previous valued node. There are two possibilities: * * If this node has a left child, go down one left, then all * the way right. */ if (node->avl_child[left] != NULL) { for (node = node->avl_child[left]; node->avl_child[right] != NULL; node = node->avl_child[right]) ; /* * Otherwise, return thru left children as far as we can. */ } else { for (;;) { was_child = AVL_XCHILD(node); node = AVL_XPARENT(node); if (node == NULL) return (NULL); if (was_child == right) break; } } return (AVL_NODE2DATA(node, off)); } /* * Return the lowest valued node in a tree or NULL. * (leftmost child from root of tree) */ void * avl_first(avl_tree_t *tree) { avl_node_t *node; avl_node_t *prev = NULL; size_t off = tree->avl_offset; for (node = tree->avl_root; node != NULL; node = node->avl_child[0]) prev = node; if (prev != NULL) return (AVL_NODE2DATA(prev, off)); return (NULL); } /* * Return the highest valued node in a tree or NULL. * (rightmost child from root of tree) */ void * avl_last(avl_tree_t *tree) { avl_node_t *node; avl_node_t *prev = NULL; size_t off = tree->avl_offset; for (node = tree->avl_root; node != NULL; node = node->avl_child[1]) prev = node; if (prev != NULL) return (AVL_NODE2DATA(prev, off)); return (NULL); } /* * Access the node immediately before or after an insertion point. * * "avl_index_t" is a (avl_node_t *) with the bottom bit indicating a child * * Return value: * NULL: no node in the given direction * "void *" of the found tree node */ void * avl_nearest(avl_tree_t *tree, avl_index_t where, int direction) { int child = AVL_INDEX2CHILD(where); avl_node_t *node = AVL_INDEX2NODE(where); void *data; size_t off = tree->avl_offset; if (node == NULL) { if (tree->avl_root != NULL) filebench_log(LOG_ERROR, "Null Node Pointer Supplied"); return (NULL); } data = AVL_NODE2DATA(node, off); if (child != direction) return (data); return (avl_walk(tree, data, direction)); } /* * Search for the node which contains "value". The algorithm is a * simple binary tree search. * * return value: * NULL: the value is not in the AVL tree * *where (if not NULL) is set to indicate the insertion point * "void *" of the found tree node */ void * avl_find(avl_tree_t *tree, void *value, avl_index_t *where) { avl_node_t *node; avl_node_t *prev = NULL; int child = 0; int diff; size_t off = tree->avl_offset; for (node = tree->avl_root; node != NULL; node = node->avl_child[child]) { prev = node; diff = tree->avl_compar(value, AVL_NODE2DATA(node, off)); if (!((-1 <= diff) && (diff <= 1))) { filebench_log(LOG_ERROR, "avl compare error"); return (NULL); } if (diff == 0) { if (where != NULL) *where = 0; return (AVL_NODE2DATA(node, off)); } child = avl_balance2child[1 + diff]; } if (where != NULL) *where = AVL_MKINDEX(prev, child); return (NULL); } /* * Perform a rotation to restore balance at the subtree given by depth. * * This routine is used by both insertion and deletion. The return value * indicates: * 0 : subtree did not change height * !0 : subtree was reduced in height * * The code is written as if handling left rotations, right rotations are * symmetric and handled by swapping values of variables right/left[_heavy] * * On input balance is the "new" balance at "node". This value is either * -2 or +2. */ static int avl_rotation(avl_tree_t *tree, avl_node_t *node, int balance) { int left = !(balance < 0); /* when balance = -2, left will be 0 */ int right = 1 - left; int left_heavy = balance >> 1; int right_heavy = -left_heavy; avl_node_t *parent = AVL_XPARENT(node); avl_node_t *child = node->avl_child[left]; avl_node_t *cright; avl_node_t *gchild; avl_node_t *gright; avl_node_t *gleft; int which_child = AVL_XCHILD(node); int child_bal = AVL_XBALANCE(child); /* BEGIN CSTYLED */ /* * case 1 : node is overly left heavy, the left child is balanced or * also left heavy. This requires the following rotation. * * (node bal:-2) * / \ * / \ * (child bal:0 or -1) * / \ * / \ * cright * * becomes: * * (child bal:1 or 0) * / \ * / \ * (node bal:-1 or 0) * / \ * / \ * cright * * we detect this situation by noting that child's balance is not * right_heavy. */ /* END CSTYLED */ if (child_bal != right_heavy) { /* * compute new balance of nodes * * If child used to be left heavy (now balanced) we reduced * the height of this sub-tree -- used in "return...;" below */ child_bal += right_heavy; /* adjust towards right */ /* * move "cright" to be node's left child */ cright = child->avl_child[right]; node->avl_child[left] = cright; if (cright != NULL) { AVL_SETPARENT(cright, node); AVL_SETCHILD(cright, left); } /* * move node to be child's right child */ child->avl_child[right] = node; AVL_SETBALANCE(node, -child_bal); AVL_SETCHILD(node, right); AVL_SETPARENT(node, child); /* * update the pointer into this subtree */ AVL_SETBALANCE(child, child_bal); AVL_SETCHILD(child, which_child); AVL_SETPARENT(child, parent); if (parent != NULL) parent->avl_child[which_child] = child; else tree->avl_root = child; return (child_bal == 0); } /* BEGIN CSTYLED */ /* * case 2 : When node is left heavy, but child is right heavy we use * a different rotation. * * (node b:-2) * / \ * / \ * / \ * (child b:+1) * / \ * / \ * (gchild b: != 0) * / \ * / \ * gleft gright * * becomes: * * (gchild b:0) * / \ * / \ * / \ * (child b:?) (node b:?) * / \ / \ * / \ / \ * gleft gright * * computing the new balances is more complicated. As an example: * if gchild was right_heavy, then child is now left heavy * else it is balanced */ /* END CSTYLED */ gchild = child->avl_child[right]; gleft = gchild->avl_child[left]; gright = gchild->avl_child[right]; /* * move gright to left child of node and * * move gleft to right child of node */ node->avl_child[left] = gright; if (gright != NULL) { AVL_SETPARENT(gright, node); AVL_SETCHILD(gright, left); } child->avl_child[right] = gleft; if (gleft != NULL) { AVL_SETPARENT(gleft, child); AVL_SETCHILD(gleft, right); } /* * move child to left child of gchild and * * move node to right child of gchild and * * fixup parent of all this to point to gchild */ balance = AVL_XBALANCE(gchild); gchild->avl_child[left] = child; AVL_SETBALANCE(child, (balance == right_heavy ? left_heavy : 0)); AVL_SETPARENT(child, gchild); AVL_SETCHILD(child, left); gchild->avl_child[right] = node; AVL_SETBALANCE(node, (balance == left_heavy ? right_heavy : 0)); AVL_SETPARENT(node, gchild); AVL_SETCHILD(node, right); AVL_SETBALANCE(gchild, 0); AVL_SETPARENT(gchild, parent); AVL_SETCHILD(gchild, which_child); if (parent != NULL) parent->avl_child[which_child] = gchild; else tree->avl_root = gchild; return (1); /* the new tree is always shorter */ } /* * Insert a new node into an AVL tree at the specified (from avl_find()) place. * * Newly inserted nodes are always leaf nodes in the tree, since avl_find() * searches out to the leaf positions. The avl_index_t indicates the node * which will be the parent of the new node. * * After the node is inserted, a single rotation further up the tree may * be necessary to maintain an acceptable AVL balance. */ void avl_insert(avl_tree_t *tree, void *new_data, avl_index_t where) { avl_node_t *node; avl_node_t *parent = AVL_INDEX2NODE(where); int old_balance; int new_balance; int which_child = AVL_INDEX2CHILD(where); size_t off = tree->avl_offset; if (tree == NULL) { filebench_log(LOG_ERROR, "No Tree Supplied"); return; } #if defined(_LP64) || (__WORDSIZE == 64) if (((uintptr_t)new_data & 0x7) != 0) { filebench_log(LOG_ERROR, "Missaligned pointer to new data"); return; } #endif node = AVL_DATA2NODE(new_data, off); /* * First, add the node to the tree at the indicated position. */ ++tree->avl_numnodes; node->avl_child[0] = NULL; node->avl_child[1] = NULL; AVL_SETCHILD(node, which_child); AVL_SETBALANCE(node, 0); AVL_SETPARENT(node, parent); if (parent != NULL) { if (parent->avl_child[which_child] != NULL) filebench_log(LOG_DEBUG_IMPL, "Overwriting existing pointer"); parent->avl_child[which_child] = node; } else { if (tree->avl_root != NULL) filebench_log(LOG_DEBUG_IMPL, "Overwriting existing pointer"); tree->avl_root = node; } /* * Now, back up the tree modifying the balance of all nodes above the * insertion point. If we get to a highly unbalanced ancestor, we * need to do a rotation. If we back out of the tree we are done. * If we brought any subtree into perfect balance (0), we are also done. */ for (;;) { node = parent; if (node == NULL) return; /* * Compute the new balance */ old_balance = AVL_XBALANCE(node); new_balance = old_balance + avl_child2balance[which_child]; /* * If we introduced equal balance, then we are done immediately */ if (new_balance == 0) { AVL_SETBALANCE(node, 0); return; } /* * If both old and new are not zero we went * from -1 to -2 balance, do a rotation. */ if (old_balance != 0) break; AVL_SETBALANCE(node, new_balance); parent = AVL_XPARENT(node); which_child = AVL_XCHILD(node); } /* * perform a rotation to fix the tree and return */ (void) avl_rotation(tree, node, new_balance); } /* * Insert "new_data" in "tree" in the given "direction" either after or * before (AVL_AFTER, AVL_BEFORE) the data "here". * * Insertions can only be done at empty leaf points in the tree, therefore * if the given child of the node is already present we move to either * the AVL_PREV or AVL_NEXT and reverse the insertion direction. Since * every other node in the tree is a leaf, this always works. * * To help developers using this interface, we assert that the new node * is correctly ordered at every step of the way in DEBUG kernels. */ void avl_insert_here( avl_tree_t *tree, void *new_data, void *here, int direction) { avl_node_t *node; int child = direction; /* rely on AVL_BEFORE == 0, AVL_AFTER == 1 */ if ((tree == NULL) || (new_data == NULL) || (here == NULL) || !((direction == AVL_BEFORE) || (direction == AVL_AFTER))) { filebench_log(LOG_ERROR, "avl_insert_here: Bad Parameters Passed"); return; } /* * If corresponding child of node is not NULL, go to the neighboring * node and reverse the insertion direction. */ node = AVL_DATA2NODE(here, tree->avl_offset); if (node->avl_child[child] != NULL) { node = node->avl_child[child]; child = 1 - child; while (node->avl_child[child] != NULL) node = node->avl_child[child]; } if (node->avl_child[child] != NULL) filebench_log(LOG_DEBUG_IMPL, "Overwriting existing pointer"); avl_insert(tree, new_data, AVL_MKINDEX(node, child)); } /* * Add a new node to an AVL tree. */ void avl_add(avl_tree_t *tree, void *new_node) { avl_index_t where; /* * This is unfortunate. Give up. */ if (avl_find(tree, new_node, &where) != NULL) { filebench_log(LOG_ERROR, "Attempting to insert already inserted node"); return; } avl_insert(tree, new_node, where); } /* * Delete a node from the AVL tree. Deletion is similar to insertion, but * with 2 complications. * * First, we may be deleting an interior node. Consider the following subtree: * * d c c * / \ / \ / \ * b e b e b e * / \ / \ / * a c a a * * When we are deleting node (d), we find and bring up an adjacent valued leaf * node, say (c), to take the interior node's place. In the code this is * handled by temporarily swapping (d) and (c) in the tree and then using * common code to delete (d) from the leaf position. * * Secondly, an interior deletion from a deep tree may require more than one * rotation to fix the balance. This is handled by moving up the tree through * parents and applying rotations as needed. The return value from * avl_rotation() is used to detect when a subtree did not change overall * height due to a rotation. */ void avl_remove(avl_tree_t *tree, void *data) { avl_node_t *delete; avl_node_t *parent; avl_node_t *node; avl_node_t tmp; int old_balance; int new_balance; int left; int right; int which_child; size_t off = tree->avl_offset; if (tree == NULL) { filebench_log(LOG_ERROR, "No Tree Supplied"); return; } delete = AVL_DATA2NODE(data, off); /* * Deletion is easiest with a node that has at most 1 child. * We swap a node with 2 children with a sequentially valued * neighbor node. That node will have at most 1 child. Note this * has no effect on the ordering of the remaining nodes. * * As an optimization, we choose the greater neighbor if the tree * is right heavy, otherwise the left neighbor. This reduces the * number of rotations needed. */ if (delete->avl_child[0] != NULL && delete->avl_child[1] != NULL) { /* * choose node to swap from whichever side is taller */ old_balance = AVL_XBALANCE(delete); left = avl_balance2child[old_balance + 1]; right = 1 - left; /* * get to the previous value'd node * (down 1 left, as far as possible right) */ for (node = delete->avl_child[left]; node->avl_child[right] != NULL; node = node->avl_child[right]) ; /* * create a temp placeholder for 'node' * move 'node' to delete's spot in the tree */ tmp = *node; *node = *delete; if (node->avl_child[left] == node) node->avl_child[left] = &tmp; parent = AVL_XPARENT(node); if (parent != NULL) parent->avl_child[AVL_XCHILD(node)] = node; else tree->avl_root = node; AVL_SETPARENT(node->avl_child[left], node); AVL_SETPARENT(node->avl_child[right], node); /* * Put tmp where node used to be (just temporary). * It always has a parent and at most 1 child. */ delete = &tmp; parent = AVL_XPARENT(delete); parent->avl_child[AVL_XCHILD(delete)] = delete; which_child = (delete->avl_child[1] != 0); if (delete->avl_child[which_child] != NULL) AVL_SETPARENT(delete->avl_child[which_child], delete); } /* * Here we know "delete" is at least partially a leaf node. It can * be easily removed from the tree. */ if (tree->avl_numnodes == 0) { filebench_log(LOG_ERROR, "Deleting Node from already empty tree"); return; } --tree->avl_numnodes; parent = AVL_XPARENT(delete); which_child = AVL_XCHILD(delete); if (delete->avl_child[0] != NULL) node = delete->avl_child[0]; else node = delete->avl_child[1]; /* * Connect parent directly to node (leaving out delete). */ if (node != NULL) { AVL_SETPARENT(node, parent); AVL_SETCHILD(node, which_child); } if (parent == NULL) { tree->avl_root = node; return; } parent->avl_child[which_child] = node; /* * Since the subtree is now shorter, begin adjusting parent balances * and performing any needed rotations. */ do { /* * Move up the tree and adjust the balance * * Capture the parent and which_child values for the next * iteration before any rotations occur. */ node = parent; old_balance = AVL_XBALANCE(node); new_balance = old_balance - avl_child2balance[which_child]; parent = AVL_XPARENT(node); which_child = AVL_XCHILD(node); /* * If a node was in perfect balance but isn't anymore then * we can stop, since the height didn't change above this point * due to a deletion. */ if (old_balance == 0) { AVL_SETBALANCE(node, new_balance); break; } /* * If the new balance is zero, we don't need to rotate * else * need a rotation to fix the balance. * If the rotation doesn't change the height * of the sub-tree we have finished adjusting. */ if (new_balance == 0) AVL_SETBALANCE(node, new_balance); else if (!avl_rotation(tree, node, new_balance)) break; } while (parent != NULL); } #define AVL_REINSERT(tree, obj) \ avl_remove((tree), (obj)); \ avl_add((tree), (obj)) boolean_t avl_update_lt(avl_tree_t *t, void *obj) { void *neighbor; if (!(((neighbor = AVL_NEXT(t, obj)) == NULL) || (t->avl_compar(obj, neighbor) <= 0))) { filebench_log(LOG_ERROR, "avl_update_lt: Neighbor miss compare"); return (B_FALSE); } neighbor = AVL_PREV(t, obj); if ((neighbor != NULL) && (t->avl_compar(obj, neighbor) < 0)) { AVL_REINSERT(t, obj); return (B_TRUE); } return (B_FALSE); } boolean_t avl_update_gt(avl_tree_t *t, void *obj) { void *neighbor; if (!(((neighbor = AVL_PREV(t, obj)) == NULL) || (t->avl_compar(obj, neighbor) >= 0))) { filebench_log(LOG_ERROR, "avl_update_gt: Neighbor miss compare"); return (B_FALSE); } neighbor = AVL_NEXT(t, obj); if ((neighbor != NULL) && (t->avl_compar(obj, neighbor) > 0)) { AVL_REINSERT(t, obj); return (B_TRUE); } return (B_FALSE); } boolean_t avl_update(avl_tree_t *t, void *obj) { void *neighbor; neighbor = AVL_PREV(t, obj); if ((neighbor != NULL) && (t->avl_compar(obj, neighbor) < 0)) { AVL_REINSERT(t, obj); return (B_TRUE); } neighbor = AVL_NEXT(t, obj); if ((neighbor != NULL) && (t->avl_compar(obj, neighbor) > 0)) { AVL_REINSERT(t, obj); return (B_TRUE); } return (B_FALSE); } /* * initialize a new AVL tree */ void avl_create(avl_tree_t *tree, int (*compar) (const void *, const void *), size_t size, size_t offset) { if ((tree == NULL) || (compar == NULL) || (size == 0) || (size < (offset + sizeof (avl_node_t)))) { filebench_log(LOG_ERROR, "avl_create: Bad Parameters Passed"); return; } ; #if defined(_LP64) || (__WORDSIZE == 64) if ((offset & 0x7) != 0) { filebench_log(LOG_ERROR, "Missaligned pointer to new data"); return; } #endif tree->avl_compar = compar; tree->avl_root = NULL; tree->avl_numnodes = 0; tree->avl_size = size; tree->avl_offset = offset; } /* * Delete a tree. */ /* ARGSUSED */ void avl_destroy(avl_tree_t *tree) { if ((tree == NULL) || (tree->avl_numnodes != 0) || (tree->avl_root != NULL)) filebench_log(LOG_DEBUG_IMPL, "avl_tree: Tree not destroyed"); } /* * Return the number of nodes in an AVL tree. */ unsigned long avl_numnodes(avl_tree_t *tree) { if (tree == NULL) { filebench_log(LOG_ERROR, "avl_numnodes: Null tree pointer"); return (0); } return (tree->avl_numnodes); } boolean_t avl_is_empty(avl_tree_t *tree) { if (tree == NULL) { filebench_log(LOG_ERROR, "avl_is_empty: Null tree pointer"); return (0); } return (tree->avl_numnodes == 0); } #define CHILDBIT (1L) /* * Post-order tree walk used to visit all tree nodes and destroy the tree * in post order. This is used for destroying a tree w/o paying any cost * for rebalancing it. * * example: * * void *cookie = NULL; * my_data_t *node; * * while ((node = avl_destroy_nodes(tree, &cookie)) != NULL) * free(node); * avl_destroy(tree); * * The cookie is really an avl_node_t to the current node's parent and * an indication of which child you looked at last. * * On input, a cookie value of CHILDBIT indicates the tree is done. */ void * avl_destroy_nodes(avl_tree_t *tree, void **cookie) { avl_node_t *node; avl_node_t *parent; int child; void *first; size_t off = tree->avl_offset; /* * Initial calls go to the first node or it's right descendant. */ if (*cookie == NULL) { first = avl_first(tree); /* * deal with an empty tree */ if (first == NULL) { *cookie = (void *)CHILDBIT; return (NULL); } node = AVL_DATA2NODE(first, off); parent = AVL_XPARENT(node); goto check_right_side; } /* * If there is no parent to return to we are done. */ parent = (avl_node_t *)((uintptr_t)(*cookie) & ~CHILDBIT); if (parent == NULL) { if (tree->avl_root != NULL) { if (tree->avl_numnodes != 1) { filebench_log(LOG_DEBUG_IMPL, "avl_destroy_nodes:" " number of nodes wrong"); } tree->avl_root = NULL; tree->avl_numnodes = 0; } return (NULL); } /* * Remove the child pointer we just visited from the parent and tree. */ child = (uintptr_t)(*cookie) & CHILDBIT; parent->avl_child[child] = NULL; if (tree->avl_numnodes <= 1) filebench_log(LOG_DEBUG_IMPL, "avl_destroy_nodes: number of nodes wrong"); --tree->avl_numnodes; /* * If we just did a right child or there isn't one, go up to parent. */ if (child == 1 || parent->avl_child[1] == NULL) { node = parent; parent = AVL_XPARENT(parent); goto done; } /* * Do parent's right child, then leftmost descendent. */ node = parent->avl_child[1]; while (node->avl_child[0] != NULL) { parent = node; node = node->avl_child[0]; } /* * If here, we moved to a left child. It may have one * child on the right (when balance == +1). */ check_right_side: if (node->avl_child[1] != NULL) { if (AVL_XBALANCE(node) != 1) filebench_log(LOG_DEBUG_IMPL, "avl_destroy_nodes: Tree inconsistency"); parent = node; node = node->avl_child[1]; if (node->avl_child[0] != NULL || node->avl_child[1] != NULL) filebench_log(LOG_DEBUG_IMPL, "avl_destroy_nodes: Destroying non leaf node"); } else { if (AVL_XBALANCE(node) > 0) filebench_log(LOG_DEBUG_IMPL, "avl_destroy_nodes: Tree inconsistency"); } done: if (parent == NULL) { *cookie = (void *)CHILDBIT; if (node != tree->avl_root) filebench_log(LOG_DEBUG_IMPL, "avl_destroy_nodes: Dangling last node"); } else { *cookie = (void *)((uintptr_t)parent | AVL_XCHILD(node)); } return (AVL_NODE2DATA(node, off)); }
27,911
25.183865
80
c
filebench
filebench-master/fb_avl.h
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _FB_AVL_H #define _FB_AVL_H #include "filebench.h" /* * Derived from Solaris' sys/avl.h and sys/avl_impl.h files. */ /* * Generic AVL tree implementation for Filebench use. * * The interfaces provide an efficient way of implementing an ordered set of * data structures. * * AVL trees provide an alternative to using an ordered linked list. Using AVL * trees will usually be faster, however they requires more storage. An ordered * linked list in general requires 2 pointers in each data structure. The * AVL tree implementation uses 3 pointers. The following chart gives the * approximate performance of operations with the different approaches: * * Operation Link List AVL tree * --------- -------- -------- * lookup O(n) O(log(n)) * * insert 1 node constant constant * * delete 1 node constant between constant and O(log(n)) * * delete all nodes O(n) O(n) * * visit the next * or prev node constant between constant and O(log(n)) * * * There are 5 pieces of information stored for each node in an AVL tree * * pointer to less than child * pointer to greater than child * a pointer to the parent of this node * which child [left(0) or right(1)] this node is for its parent * a "balance" (-1, 0, +1) indicating which child tree is taller * * Since they only need 3 bits, the last two fields are packed into the * bottom bits of the parent pointer on 64 bit machines to save on space. */ #if !defined(_LP64) && !(__WORDSIZE == 64) struct avl_node { struct avl_node *avl_child[2]; /* left/right children */ struct avl_node *avl_parent; /* this node's parent */ unsigned short avl_child_index; /* my index in parent's avl_child[] */ short avl_balance; /* balance value: -1, 0, +1 */ }; #define AVL_XPARENT(n) ((n)->avl_parent) #define AVL_SETPARENT(n, p) ((n)->avl_parent = (p)) #define AVL_XCHILD(n) ((n)->avl_child_index) #define AVL_SETCHILD(n, c) ((n)->avl_child_index = (unsigned short)(c)) #define AVL_XBALANCE(n) ((n)->avl_balance) #define AVL_SETBALANCE(n, b) ((n)->avl_balance = (short)(b)) #else /* !defined(_LP64) && !(__WORDSIZE == 64) */ /* * for 64 bit machines, avl_pcb contains parent pointer, balance and child_index * values packed in the following manner: * * |63 3| 2 |1 0 | * |-------------------------------------|-----------------|-------------| * | avl_parent hi order bits | avl_child_index | avl_balance | * | | | + 1 | * |-------------------------------------|-----------------|-------------| * */ struct avl_node { struct avl_node *avl_child[2]; /* left/right children nodes */ uintptr_t avl_pcb; /* parent, child_index, balance */ }; /* * macros to extract/set fields in avl_pcb * * pointer to the parent of the current node is the high order bits */ #define AVL_XPARENT(n) ((struct avl_node *)((n)->avl_pcb & ~7)) #define AVL_SETPARENT(n, p) \ ((n)->avl_pcb = (((n)->avl_pcb & 7) | (uintptr_t)(p))) /* * index of this node in its parent's avl_child[]: bit #2 */ #define AVL_XCHILD(n) (((n)->avl_pcb >> 2) & 1) #define AVL_SETCHILD(n, c) \ ((n)->avl_pcb = (uintptr_t)(((n)->avl_pcb & ~4) | ((c) << 2))) /* * balance indication for a node, lowest 2 bits. A valid balance is * -1, 0, or +1, and is encoded by adding 1 to the value to get the * unsigned values of 0, 1, 2. */ #define AVL_XBALANCE(n) ((int)(((n)->avl_pcb & 3) - 1)) #define AVL_SETBALANCE(n, b) \ ((n)->avl_pcb = (uintptr_t)((((n)->avl_pcb & ~3) | ((b) + 1)))) #endif /* !defined(_LP64) && !(__WORDSIZE == 64) */ /* * switch between a node and data pointer for a given tree * the value of "o" is tree->avl_offset */ #define AVL_NODE2DATA(n, o) ((void *)((uintptr_t)(n) - (o))) #define AVL_DATA2NODE(d, o) ((struct avl_node *)((uintptr_t)(d) + (o))) /* * macros used to create/access an avl_index_t */ #define AVL_INDEX2NODE(x) ((avl_node_t *)((x) & ~1)) #define AVL_INDEX2CHILD(x) ((x) & 1) #define AVL_MKINDEX(n, c) ((avl_index_t)(n) | (c)) /* * The tree structure. The fields avl_root, avl_compar, and avl_offset come * first since they are needed for avl_find(). We want them to fit into * a single 64 byte cache line to make avl_find() as fast as possible. */ struct avl_tree { struct avl_node *avl_root; /* root node in tree */ int (*avl_compar)(const void *, const void *); size_t avl_offset; /* offsetof(type, avl_link_t field) */ unsigned long avl_numnodes; /* number of nodes in the tree */ size_t avl_size; /* sizeof user type struct */ }; /* * This will only by used via AVL_NEXT() or AVL_PREV() */ extern void *avl_walk(struct avl_tree *, void *, int); /* * The data structure nodes are anchored at an "avl_tree_t" (the equivalent * of a list header) and the individual nodes will have a field of * type "avl_node_t" (corresponding to list pointers). * * The type "avl_index_t" is used to indicate a position in the list for * certain calls. * * The usage scenario is generally: * * 1. Create the list/tree with: avl_create() * * followed by any mixture of: * * 2a. Insert nodes with: avl_add(), or avl_find() and avl_insert() * * 2b. Visited elements with: * avl_first() - returns the lowest valued node * avl_last() - returns the highest valued node * AVL_NEXT() - given a node go to next higher one * AVL_PREV() - given a node go to previous lower one * * 2c. Find the node with the closest value either less than or greater * than a given value with avl_nearest(). * * 2d. Remove individual nodes from the list/tree with avl_remove(). * * and finally when the list is being destroyed * * 3. Use avl_destroy_nodes() to quickly process/free up any remaining nodes. * Note that once you use avl_destroy_nodes(), you can no longer * use any routine except avl_destroy_nodes() and avl_destoy(). * * 4. Use avl_destroy() to destroy the AVL tree itself. * * Any locking for multiple thread access is up to the user to provide, just * as is needed for any linked list implementation. */ /* * Type used for the root of the AVL tree. */ typedef struct avl_tree avl_tree_t; /* * The data nodes in the AVL tree must have a field of this type. */ typedef struct avl_node avl_node_t; /* * An opaque type used to locate a position in the tree where a node * would be inserted. */ typedef uintptr_t avl_index_t; /* * Direction constants used for avl_nearest(). */ #define AVL_BEFORE (0) #define AVL_AFTER (1) /* * Prototypes * * Where not otherwise mentioned, "void *" arguments are a pointer to the * user data structure which must contain a field of type avl_node_t. * * Also assume the user data structures looks like: * stuct my_type { * ... * avl_node_t my_link; * ... * }; */ /* * Initialize an AVL tree. Arguments are: * * tree - the tree to be initialized * compar - function to compare two nodes, it must return exactly: -1, 0, or +1 * -1 for <, 0 for ==, and +1 for > * size - the value of sizeof(struct my_type) * offset - the value of OFFSETOF(struct my_type, my_link) */ extern void avl_create(avl_tree_t *tree, int (*compar) (const void *, const void *), size_t size, size_t offset); /* * Find a node with a matching value in the tree. Returns the matching node * found. If not found, it returns NULL and then if "where" is not NULL it sets * "where" for use with avl_insert() or avl_nearest(). * * node - node that has the value being looked for * where - position for use with avl_nearest() or avl_insert(), may be NULL */ extern void *avl_find(avl_tree_t *tree, void *node, avl_index_t *where); /* * Insert a node into the tree. * * node - the node to insert * where - position as returned from avl_find() */ extern void avl_insert(avl_tree_t *tree, void *node, avl_index_t where); /* * Insert "new_data" in "tree" in the given "direction" either after * or before the data "here". * * This might be usefull for avl clients caching recently accessed * data to avoid doing avl_find() again for insertion. * * new_data - new data to insert * here - existing node in "tree" * direction - either AVL_AFTER or AVL_BEFORE the data "here". */ extern void avl_insert_here(avl_tree_t *tree, void *new_data, void *here, int direction); /* * Return the first or last valued node in the tree. Will return NULL * if the tree is empty. * */ extern void *avl_first(avl_tree_t *tree); extern void *avl_last(avl_tree_t *tree); /* * Return the next or previous valued node in the tree. * AVL_NEXT() will return NULL if at the last node. * AVL_PREV() will return NULL if at the first node. * * node - the node from which the next or previous node is found */ #define AVL_NEXT(tree, node) avl_walk(tree, node, AVL_AFTER) #define AVL_PREV(tree, node) avl_walk(tree, node, AVL_BEFORE) /* * Find the node with the nearest value either greater or less than * the value from a previous avl_find(). Returns the node or NULL if * there isn't a matching one. * * where - position as returned from avl_find() * direction - either AVL_BEFORE or AVL_AFTER * * EXAMPLE get the greatest node that is less than a given value: * * avl_tree_t *tree; * struct my_data look_for_value = {....}; * struct my_data *node; * struct my_data *less; * avl_index_t where; * * node = avl_find(tree, &look_for_value, &where); * if (node != NULL) * less = AVL_PREV(tree, node); * else * less = avl_nearest(tree, where, AVL_BEFORE); */ extern void *avl_nearest(avl_tree_t *tree, avl_index_t where, int direction); /* * Add a single node to the tree. * The node must not be in the tree, and it must not * compare equal to any other node already in the tree. * * node - the node to add */ extern void avl_add(avl_tree_t *tree, void *node); /* * Remove a single node from the tree. The node must be in the tree. * * node - the node to remove */ extern void avl_remove(avl_tree_t *tree, void *node); /* * Reinsert a node only if its order has changed relative to its nearest * neighbors. To optimize performance avl_update_lt() checks only the previous * node and avl_update_gt() checks only the next node. Use avl_update_lt() and * avl_update_gt() only if you know the direction in which the order of the * node may change. */ extern boolean_t avl_update(avl_tree_t *, void *); extern boolean_t avl_update_lt(avl_tree_t *, void *); extern boolean_t avl_update_gt(avl_tree_t *, void *); /* * Return the number of nodes in the tree */ extern unsigned long avl_numnodes(avl_tree_t *tree); /* * Return B_TRUE if there are zero nodes in the tree, B_FALSE otherwise. */ extern boolean_t avl_is_empty(avl_tree_t *tree); /* * Used to destroy any remaining nodes in a tree. The cookie argument should * be initialized to NULL before the first call. Returns a node that has been * removed from the tree and may be free()'d. Returns NULL when the tree is * empty. * * Once you call avl_destroy_nodes(), you can only continuing calling it and * finally avl_destroy(). No other AVL routines will be valid. * * cookie - a "void *" used to save state between calls to avl_destroy_nodes() * * EXAMPLE: * avl_tree_t *tree; * struct my_data *node; * void *cookie; * * cookie = NULL; * while ((node = avl_destroy_nodes(tree, &cookie)) != NULL) * free(node); * avl_destroy(tree); */ extern void *avl_destroy_nodes(avl_tree_t *tree, void **cookie); /* * Final destroy of an AVL tree. Arguments are: * * tree - the empty tree to destroy */ extern void avl_destroy(avl_tree_t *tree); #endif /* _FB_AVL_H */
12,596
29.575243
80
h
filebench
filebench-master/fb_cvar.c
/* * fb_cvar.c * * Support for custom variables in Filebench. * * @Author Santhosh Kumar Koundinya (santhosh@fsl.cs.sunysb.edu) */ #include <sys/types.h> #include <dirent.h> #include <limits.h> #include <dlfcn.h> #include "ipc.h" #include "fb_cvar.h" /* Some helpers. */ static int alloc_cvar_lib_info(const char *filename); static char *gettype(const char *filename); static cvar_library_t *init_cvar_library(cvar_library_info_t *cvar_lib_info); static void *load_library(const char *filename); static void free_cvar_library(cvar_library_t *c); static int init_cvar_library_ops(cvar_library_t *c); /* Points to the head of an array of pointers to cvar_library_t. */ cvar_library_t **cvar_libraries; /* * Allocate space for a new custom variable in the shared memory location. */ cvar_t * cvar_alloc(void) { cvar_t *cvar; if ((cvar = (cvar_t *)ipc_malloc(FILEBENCH_CVAR)) == NULL) { filebench_log(LOG_ERROR, "Out of memory for custom variable"); return (NULL); } /* place on the head of the global list */ cvar->next = filebench_shm->shm_cvar_list; filebench_shm->shm_cvar_list = cvar; return (cvar); } /* * Initialize cvar_library_info structures in the shared memory. * Return 0 on success and a non zero error code on failure. */ int init_cvar_library_info(const char *dirpath) { DIR *libdir = NULL; struct dirent *dirent; char *filename = NULL; int ret = -1; int dirpath_len = strlen(dirpath); int direntlen; filename = (char *) malloc(dirpath_len + 1 + NAME_MAX + 1); if (!filename) { filebench_log(LOG_ERROR, "Out of memory"); goto out; } strcpy(filename, dirpath); filename[dirpath_len] = '/'; filename[dirpath_len + NAME_MAX] = '\0'; libdir = opendir(dirpath); if (!libdir) { filebench_log(LOG_ERROR, "Failed to open cvar directory"); ret = 0; goto out; } while ((dirent = readdir(libdir)) != NULL) { if (!strcmp(".", dirent->d_name) || !strcmp("..", dirent->d_name)) continue; direntlen = strlen(dirent->d_name); if (strcmp(".so", dirent->d_name + direntlen - 3)) continue; strncpy(filename + dirpath_len + 1, dirent->d_name, NAME_MAX); ret = alloc_cvar_lib_info(filename); if (ret) goto out; } ret = 0; out: if (filename) free(filename); if (libdir) closedir(libdir); return ret; } /* * Return 0 on success and a non zero error code on failure. */ static int alloc_cvar_lib_info(const char *filename) { int ret = -1; cvar_library_info_t *cli = NULL; cvar_library_info_t *t; cli = (cvar_library_info_t *) ipc_malloc(FILEBENCH_CVAR_LIB_INFO); if (!cli) goto out; cli->filename = ipc_stralloc(filename); if (!cli->filename) goto out; cli->type = ipc_stralloc(gettype(filename)); if (!cli->type) goto out; cli->next = NULL; if (filebench_shm->shm_cvar_lib_info_list) { for (t = filebench_shm->shm_cvar_lib_info_list; t->next != NULL; t = t->next); /* Seek to the last entry. */ cli->index = t->index + 1; t->next = cli; } else { cli->index = 0; filebench_shm->shm_cvar_lib_info_list = cli; } ret = 0; out: if (ret && cli) { /* NOTE: There is no mechanism to free cli->filename and cli->type. */ ipc_free(FILEBENCH_CVAR_LIB_INFO, (char *) cli); } return ret; } /* * Returns the 'type' name from the library. */ static char *gettype(const char *filename) { char libprefix[] = "lib"; const char *libname; char *type; int type_len; const char *t; libname = strrchr(filename, '/'); if (!libname) libname = filename; /* filename is not a fully qualified path. */ else { libname++; /* Check for a malformed filename string. */ if (!libname) { filebench_log(LOG_ERROR, "Malformed cvar library filename"); return NULL; } } /* Strip the leading "lib". */ if (!strncmp(libprefix, libname, sizeof(libprefix) - 1)) libname += sizeof(char) * (sizeof(libprefix) - 1); if (!libname) { filebench_log(LOG_ERROR, "Malformed cvar library filename"); return NULL; } /* Look for the first '.'. */ type_len = 0; for (t = libname; *t != '\0' && *t != '.'; t++) type_len++; type = (char *) malloc(type_len + 1); if (!type) { filebench_log(LOG_ERROR, "Out of memory"); return NULL; } strncpy(type, libname, type_len); type[type_len] = '\0'; return type; } /* * Load shared objects. * Returns 0 on success and non-zero on error. */ int init_cvar_libraries() { int count; int ret = -1; int i; cvar_library_info_t *t; if (!filebench_shm->shm_cvar_lib_info_list) { /* Nothing to do. */ return 0; } count = 0; for (t = filebench_shm->shm_cvar_lib_info_list; t != NULL; t = t->next) count++; cvar_libraries = (cvar_library_t **) malloc(sizeof(cvar_library_t *) * count); if (!cvar_libraries) { filebench_log(LOG_ERROR, "Out of memory"); goto out; } for (t = filebench_shm->shm_cvar_lib_info_list, i = 0; t != NULL; t = t->next, i++) { if ((cvar_libraries[i] = init_cvar_library(t)) == NULL) { goto out; } } ret = 0; out: return ret; } static cvar_library_t *init_cvar_library(cvar_library_info_t *cvar_lib_info) { cvar_library_t *c = NULL; int ret; c = (cvar_library_t *) malloc(sizeof(cvar_library_t)); if (!c) { filebench_log(LOG_ERROR, "Out of memory"); goto out; } c->cvar_lib_info = cvar_lib_info; c->lib_handle = load_library(cvar_lib_info->filename); if (!c->lib_handle) goto cleanup; ret = init_cvar_library_ops(c); if (ret) goto cleanup; if (c->cvar_op.cvar_module_init) { ret = c->cvar_op.cvar_module_init(); if (ret) { filebench_log(LOG_ERROR, "Failed to initialize custom variable of type" " %s. cvar_module_init failed with error %d", cvar_lib_info->type, ret); goto cleanup; } } out: return c; cleanup: if (c) { free_cvar_library(c); free(c); c = NULL; } goto out; } static void *load_library(const char *filename) { void *lib_handle = dlopen(filename, RTLD_LOCAL | RTLD_NOW); if (!lib_handle) filebench_log(LOG_ERROR, "Unable to load library %s: %s", filename, dlerror()); return lib_handle; } static void free_cvar_library(cvar_library_t *c) { if (c) { if (c->lib_handle) { dlclose(c->lib_handle); } } } static int init_cvar_library_ops(cvar_library_t *c) { int ret = -1; c->cvar_op.cvar_module_init = dlsym(c->lib_handle, FB_CVAR_MODULE_INIT); c->cvar_op.cvar_alloc_handle = dlsym(c->lib_handle, FB_CVAR_ALLOC_HANDLE); if (!c->cvar_op.cvar_alloc_handle) { filebench_log(LOG_ERROR, "Unable to find " FB_CVAR_ALLOC_HANDLE ": %s.", dlerror()); goto out; } c->cvar_op.cvar_revalidate_handle = dlsym(c->lib_handle, FB_CVAR_REVALIDATE_HANDLE); if (!c->cvar_op.cvar_revalidate_handle) { filebench_log(LOG_ERROR, "Unable to find " FB_CVAR_REVALIDATE_HANDLE ": %s", dlerror()); } c->cvar_op.cvar_next_value = dlsym(c->lib_handle, FB_CVAR_NEXT_VALUE); if (!c->cvar_op.cvar_next_value) { filebench_log(LOG_ERROR, "Unable to find " FB_CVAR_NEXT_VALUE ": %s.", dlerror()); goto out; } c->cvar_op.cvar_free_handle = dlsym(c->lib_handle, FB_CVAR_FREE_HANDLE); if (!c->cvar_op.cvar_free_handle) { filebench_log(LOG_ERROR, "Unable to find " FB_CVAR_FREE_HANDLE ": %s.", dlerror()); goto out; } c->cvar_op.cvar_module_exit = dlsym(c->lib_handle, FB_CVAR_MODULE_EXIT); c->cvar_op.cvar_usage = dlsym(c->lib_handle, FB_CVAR_USAGE); c->cvar_op.cvar_version = dlsym(c->lib_handle, FB_CVAR_VERSION); ret = 0; out: return ret; } int init_cvar_handle(cvar_t *cvar, const char *type, const char *parameters) { int ret = -1; cvar_library_t *cvar_lib; cvar_library_info_t *t; for (t = filebench_shm->shm_cvar_lib_info_list; t != NULL; t = t->next) { if (!strcmp(type, t->type)) break; } if (!t) { filebench_log(LOG_ERROR, "Undefined custom variable %s", type); goto out; } cvar->cvar_lib_info = t; cvar_lib = cvar_libraries[cvar->cvar_lib_info->index]; cvar->cvar_handle = cvar_lib->cvar_op.cvar_alloc_handle(parameters, ipc_cvar_heapalloc, ipc_cvar_heapfree); if (!cvar->cvar_handle) goto out; ret = 0; out: return ret; } double get_cvar_value(cvar_t *cvar) { int ret; double value = 0.0; fbint_t round = cvar->round; ipc_mutex_lock(&cvar->cvar_lock); cvar_library_t *cvar_lib = cvar_libraries[cvar->cvar_lib_info->index]; ret = cvar_lib->cvar_op.cvar_next_value(cvar->cvar_handle, &value); ipc_mutex_unlock(&cvar->cvar_lock); if (ret) { filebench_log(LOG_ERROR, "Unable to get next_value from custom variable" " of type %s", cvar->cvar_lib_info->type); filebench_shutdown(1); } if (round) { fbint_t num, lower, upper; num = (fbint_t) value; lower = num - (num % round); upper = lower + round; value = (num - lower) > (upper - num) ? upper : lower; } if (value < cvar->min) value = cvar->min; else if (value > cvar->max) value = cvar->max; return value; } /* * Return 0 on success and a non-zero error code on failure. */ int revalidate_cvar_handles() { cvar_t *t; cvar_library_t *cvar_lib; int ret; if (!filebench_shm->shm_cvar_list) return 0; /* Nothing to do. */ for (t = filebench_shm->shm_cvar_list; t != NULL; t = t->next) { cvar_lib = cvar_libraries[t->cvar_lib_info->index]; if (cvar_lib->cvar_op.cvar_revalidate_handle) { ipc_mutex_lock(&t->cvar_lock); ret = cvar_lib->cvar_op.cvar_revalidate_handle(t->cvar_handle); ipc_mutex_unlock(&t->cvar_lock); if (ret) { filebench_log(LOG_ERROR, "Revalidation failed for cvar_handle " "of type %s with error code %d", t->cvar_lib_info->type, ret); return ret; } } } return 0; }
9,532
19.951648
77
c
filebench
filebench-master/fb_cvar.h
/* * fb_cvar.h * * Include file for code using custom variables. * * @Author Santhosh Kumar Koundinya (santhosh@fsl.cs.sunysb.edu) */ #ifndef _FB_CVAR_H #define _FB_CVAR_H #include <stdint.h> #include <sys/types.h> /* Function (symbol) names within custom variable libraries. */ #define FB_CVAR_MODULE_INIT "cvar_module_init" #define FB_CVAR_ALLOC_HANDLE "cvar_alloc_handle" #define FB_CVAR_REVALIDATE_HANDLE "cvar_revalidate_handle" #define FB_CVAR_NEXT_VALUE "cvar_next_value" #define FB_CVAR_FREE_HANDLE "cvar_free_handle" #define FB_CVAR_MODULE_EXIT "cvar_module_exit" #define FB_CVAR_USAGE "cvar_usage" #define FB_CVAR_VERSION "cvar_version" /* Information about each library supporting a custom variable. This structure * is rooted in the shared memory segment. */ typedef struct cvar_library_info { char *filename; /* The fully qualified path to the library. */ /* The type name of the library is the soname without the "lib" prefix and * the ".so.XXX.XXX" suffix. */ char *type; /* The index is a sequentially increasing count. It helps seek within global * variable cvar_library_array. */ int index; struct cvar_library_info *next; } cvar_library_info_t; /* Structure that encapsulates access to a custom variable. A var_t points to a * cvar_t (and not vice versa). */ typedef struct cvar { /* Used to provide exclusive access to this custom variable across threads * and processes. */ pthread_mutex_t cvar_lock; /* The custom variable handle returned by cvar_alloc() */ void *cvar_handle; double min; double max; uint64_t round; cvar_library_info_t *cvar_lib_info; struct cvar *next; } cvar_t; /* The operations vector for a library. Each member is populated by a call to * dlsym(). */ typedef struct cvar_operations { int (*cvar_module_init)(void); void *(*cvar_alloc_handle)(const char *cvar_parameters, void *(*cvar_malloc)(size_t size), void (*cvar_free)(void *ptr)); int (*cvar_revalidate_handle)(void *cvar_handle); int (*cvar_next_value)(void *cvar_handle, double *value); void (*cvar_free_handle)(void *cvar_handle, void (*cvar_free)(void *ptr)); void (*cvar_module_exit)(); const char *(*cvar_usage)(void); const char *(*cvar_version)(void); } cvar_operations_t; /* Structure that represents a library. This structure is "per-process" and * "per-library" (and not in the shared memory). There is a one to one mapping * between cvar_library_t and cvar_library_info_t. */ typedef struct cvar_library { cvar_library_info_t *cvar_lib_info; void *lib_handle; /* The handle returned by dlopen(). */ cvar_operations_t cvar_op; /* The operations vector of the library. */ } cvar_library_t; /* Points to the head of an array of pointers to cvar_library_t. */ extern cvar_library_t **cvar_libraries; cvar_t * cvar_alloc(void); int init_cvar_library_info(const char *dirpath); int init_cvar_libraries(); int init_cvar_handle(cvar_t *cvar, const char *type, const char *parameters); double get_cvar_value(cvar_t *cvar); int revalidate_cvar_handles(); #endif /* _FB_CVAR_H */
3,054
34.114943
79
h
filebench
filebench-master/fb_localfs.c
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * Portions Copyright 2008 Denis Cheng */ #include "config.h" #include "filebench.h" #include "flowop.h" #include "threadflow.h" /* For aiolist definition */ #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <libgen.h> #include <sys/mman.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/param.h> #include <sys/resource.h> #include <strings.h> #include "filebench.h" #include "fsplug.h" #ifdef HAVE_AIO #include <aio.h> #endif /* HAVE_AIO */ /* * These routines implement local file access. They are placed into a * vector of functions that are called by all I/O operations in fileset.c * and flowop_library.c. This represents the default file system plug-in, * and may be replaced by vectors for other file system plug-ins. */ static int fb_lfs_freemem(fb_fdesc_t *fd, off64_t size); static int fb_lfs_open(fb_fdesc_t *, char *, int, int); static int fb_lfs_pread(fb_fdesc_t *, caddr_t, fbint_t, off64_t); static int fb_lfs_read(fb_fdesc_t *, caddr_t, fbint_t); static int fb_lfs_pwrite(fb_fdesc_t *, caddr_t, fbint_t, off64_t); static int fb_lfs_write(fb_fdesc_t *, caddr_t, fbint_t); static int fb_lfs_lseek(fb_fdesc_t *, off64_t, int); static int fb_lfs_truncate(fb_fdesc_t *, off64_t); static int fb_lfs_rename(const char *, const char *); static int fb_lfs_close(fb_fdesc_t *); static int fb_lfs_link(const char *, const char *); static int fb_lfs_symlink(const char *, const char *); static int fb_lfs_unlink(char *); static ssize_t fb_lfs_readlink(const char *, char *, size_t); static int fb_lfs_mkdir(char *, int); static int fb_lfs_rmdir(char *); static DIR *fb_lfs_opendir(char *); static struct dirent *fb_lfs_readdir(DIR *); static int fb_lfs_closedir(DIR *); static int fb_lfs_fsync(fb_fdesc_t *); static int fb_lfs_stat(char *, struct stat64 *); static int fb_lfs_fstat(fb_fdesc_t *, struct stat64 *); static int fb_lfs_access(const char *, int); static void fb_lfs_recur_rm(char *); static fsplug_func_t fb_lfs_funcs = { "locfs", fb_lfs_freemem, /* flush page cache */ fb_lfs_open, /* open */ fb_lfs_pread, /* pread */ fb_lfs_read, /* read */ fb_lfs_pwrite, /* pwrite */ fb_lfs_write, /* write */ fb_lfs_lseek, /* lseek */ fb_lfs_truncate, /* ftruncate */ fb_lfs_rename, /* rename */ fb_lfs_close, /* close */ fb_lfs_link, /* link */ fb_lfs_symlink, /* symlink */ fb_lfs_unlink, /* unlink */ fb_lfs_readlink, /* readlink */ fb_lfs_mkdir, /* mkdir */ fb_lfs_rmdir, /* rmdir */ fb_lfs_opendir, /* opendir */ fb_lfs_readdir, /* readdir */ fb_lfs_closedir, /* closedir */ fb_lfs_fsync, /* fsync */ fb_lfs_stat, /* stat */ fb_lfs_fstat, /* fstat */ fb_lfs_access, /* access */ fb_lfs_recur_rm /* recursive rm */ }; #ifdef HAVE_AIO /* * Local file system asynchronous IO flowops are in this module, as * they have a number of local file system specific features. */ static int fb_lfsflow_aiowrite(threadflow_t *threadflow, flowop_t *flowop); static int fb_lfsflow_aiowait(threadflow_t *threadflow, flowop_t *flowop); static flowop_proto_t fb_lfsflow_funcs[] = { {FLOW_TYPE_AIO, FLOW_ATTR_WRITE, "aiowrite", flowop_init_generic, fb_lfsflow_aiowrite, flowop_destruct_generic}, {FLOW_TYPE_AIO, 0, "aiowait", flowop_init_generic, fb_lfsflow_aiowait, flowop_destruct_generic} }; #endif /* HAVE_AIO */ /* * Initialize file system functions vector to point to the vector of local file * system functions. This function will be called for the master process and * every created worker process. */ void fb_lfs_funcvecinit(void) { fs_functions_vec = &fb_lfs_funcs; } /* * Initialize those flowops which implementation is file system specific. It is * called only once in the master process. */ void fb_lfs_newflowops(void) { #ifdef HAVE_AIO int nops; nops = sizeof (fb_lfsflow_funcs) / sizeof (flowop_proto_t); flowop_add_from_proto(fb_lfsflow_funcs, nops); #endif /* HAVE_AIO */ } /* * Frees up memory mapped file region of supplied size. The * file descriptor "fd" indicates which memory mapped file. * If successful, returns 0. Otherwise returns -1 if "size" * is zero, or -1 times the number of times msync() failed. */ static int fb_lfs_freemem(fb_fdesc_t *fd, off64_t size) { off64_t left; int ret = 0; for (left = size; left > 0; left -= MMAP_SIZE) { off64_t thismapsize; caddr_t addr; thismapsize = MIN(MMAP_SIZE, left); addr = mmap64(0, thismapsize, PROT_READ|PROT_WRITE, MAP_SHARED, fd->fd_num, size - left); ret += msync(addr, thismapsize, MS_INVALIDATE); (void) munmap(addr, thismapsize); } return (ret); } /* * Does a posix pread. Returns what the pread() returns. */ static int fb_lfs_pread(fb_fdesc_t *fd, caddr_t iobuf, fbint_t iosize, off64_t fileoffset) { return (pread64(fd->fd_num, iobuf, iosize, fileoffset)); } /* * Does a posix read. Returns what the read() returns. */ static int fb_lfs_read(fb_fdesc_t *fd, caddr_t iobuf, fbint_t iosize) { return (read(fd->fd_num, iobuf, iosize)); } #ifdef HAVE_AIO /* * Asynchronous write section. An Asynchronous IO element * (aiolist_t) is used to associate the asynchronous write request with * its subsequent completion. This element includes a aiocb64 struct * that is used by posix aio_xxx calls to track the asynchronous writes. * The flowops aiowrite and aiowait result in calls to these posix * aio_xxx system routines to do the actual asynchronous write IO * operations. */ /* * Allocates an asynchronous I/O list (aio, of type * aiolist_t) element. Adds it to the flowop thread's * threadflow aio list. Returns a pointer to the element. */ static aiolist_t * aio_allocate(flowop_t *flowop) { aiolist_t *aiolist; if ((aiolist = malloc(sizeof (aiolist_t))) == NULL) { filebench_log(LOG_ERROR, "malloc aiolist failed"); filebench_shutdown(1); } bzero(aiolist, sizeof(*aiolist)); /* Add to list */ if (flowop->fo_thread->tf_aiolist == NULL) { flowop->fo_thread->tf_aiolist = aiolist; aiolist->al_next = NULL; } else { aiolist->al_next = flowop->fo_thread->tf_aiolist; flowop->fo_thread->tf_aiolist = aiolist; } return (aiolist); } /* * Searches for the aiolist element that has a matching * completion block, aiocb. If none found returns FILEBENCH_ERROR. If * found, removes the aiolist element from flowop thread's * list and returns FILEBENCH_OK. */ static int aio_deallocate(flowop_t *flowop, struct aiocb64 *aiocb) { aiolist_t *aiolist = flowop->fo_thread->tf_aiolist; aiolist_t *previous = NULL; aiolist_t *match = NULL; if (aiocb == NULL) { filebench_log(LOG_ERROR, "null aiocb deallocate"); return (FILEBENCH_OK); } while (aiolist) { if (aiocb == &(aiolist->al_aiocb)) { match = aiolist; break; } previous = aiolist; aiolist = aiolist->al_next; } if (match == NULL) return (FILEBENCH_ERROR); /* Remove from the list */ if (previous) previous->al_next = match->al_next; else flowop->fo_thread->tf_aiolist = match->al_next; return (FILEBENCH_OK); } /* * Emulate posix aiowrite(). Determines which file to use, * either one file of a fileset, or the file associated * with a fileobj, allocates and fills an aiolist_t element * for the write, and issues the asynchronous write. This * operation is only valid for random IO, and returns an * error if the flowop is set for sequential IO. Returns * FILEBENCH_OK on success, FILEBENCH_NORSC if iosetup can't * obtain a file to open, and FILEBENCH_ERROR on any * encountered error. */ static int fb_lfsflow_aiowrite(threadflow_t *threadflow, flowop_t *flowop) { caddr_t iobuf; fbint_t wss; fbint_t iosize; fb_fdesc_t *fdesc; int ret; iosize = avd_get_int(flowop->fo_iosize); if ((ret = flowoplib_iosetup(threadflow, flowop, &wss, &iobuf, &fdesc, iosize)) != FILEBENCH_OK) return (ret); if (avd_get_bool(flowop->fo_random)) { uint64_t fileoffset; struct aiocb64 *aiocb; aiolist_t *aiolist; if (wss < iosize) { filebench_log(LOG_ERROR, "file size smaller than IO size for thread %s", flowop->fo_name); return (FILEBENCH_ERROR); } fb_random64(&fileoffset, wss, iosize, NULL); aiolist = aio_allocate(flowop); aiolist->al_type = AL_WRITE; aiocb = &aiolist->al_aiocb; aiocb->aio_fildes = fdesc->fd_num; aiocb->aio_buf = iobuf; aiocb->aio_nbytes = (size_t)iosize; aiocb->aio_offset = (off64_t)fileoffset; aiocb->aio_reqprio = 0; filebench_log(LOG_DEBUG_IMPL, "aio fd=%d, bytes=%llu, offset=%llu", fdesc->fd_num, (u_longlong_t)iosize, (u_longlong_t)fileoffset); flowop_beginop(threadflow, flowop); if (aio_write64(aiocb) < 0) { filebench_log(LOG_ERROR, "aiowrite failed: %s", strerror(errno)); filebench_shutdown(1); } flowop_endop(threadflow, flowop, iosize); } else { return (FILEBENCH_ERROR); } return (FILEBENCH_OK); } #define MAXREAP 4096 /* * Emulate posix aiowait(). Waits for the completion of half the * outstanding asynchronous IOs, or a single IO, which ever is * larger. The routine will return after a sufficient number of * completed calls issued by any thread in the procflow have * completed, or a 1 second timout elapses. All completed * IO operations are deleted from the thread's aiolist. */ static int fb_lfsflow_aiowait(threadflow_t *threadflow, flowop_t *flowop) { struct aiocb64 **worklist; aiolist_t *aio = flowop->fo_thread->tf_aiolist; int uncompleted = 0; #ifdef HAVE_AIOWAITN int i; #endif worklist = calloc(MAXREAP, sizeof (struct aiocb64 *)); /* Count the list of pending aios */ while (aio) { uncompleted++; aio = aio->al_next; } do { uint_t ncompleted = 0; uint_t todo; int inprogress; #ifdef HAVE_AIOWAITN struct timespec timeout; /* Wait for half of the outstanding requests */ timeout.tv_sec = 1; timeout.tv_nsec = 0; #endif if (uncompleted > MAXREAP) todo = MAXREAP; else todo = uncompleted / 2; if (todo == 0) todo = 1; flowop_beginop(threadflow, flowop); #ifdef HAVE_AIOWAITN if (((aio_waitn64((struct aiocb64 **)worklist, MAXREAP, &todo, &timeout)) == -1) && errno && (errno != ETIME)) { filebench_log(LOG_ERROR, "aiowait failed: %s, outstanding = %d, " "ncompleted = %d ", strerror(errno), uncompleted, todo); } ncompleted = todo; /* Take the completed I/Os from the list */ inprogress = 0; for (i = 0; i < ncompleted; i++) { if ((aio_return64(worklist[i]) == -1) && (errno == EINPROGRESS)) { inprogress++; continue; } if (aio_deallocate(flowop, worklist[i]) == FILEBENCH_ERROR) { filebench_log(LOG_ERROR, "Could not remove " "aio from list "); flowop_endop(threadflow, flowop, 0); return (FILEBENCH_ERROR); } } uncompleted -= ncompleted; uncompleted += inprogress; #else for (ncompleted = 0, inprogress = 0, aio = flowop->fo_thread->tf_aiolist; ncompleted < todo && aio != NULL; aio = aio->al_next) { int result = aio_error64(&aio->al_aiocb); if (result == EINPROGRESS) { inprogress++; continue; } if ((aio_return64(&aio->al_aiocb) == -1) || result) { filebench_log(LOG_ERROR, "aio failed: %s", strerror(result)); continue; } ncompleted++; if (aio_deallocate(flowop, &aio->al_aiocb) < 0) { filebench_log(LOG_ERROR, "Could not remove " "aio from list "); flowop_endop(threadflow, flowop, 0); return (FILEBENCH_ERROR); } } uncompleted -= ncompleted; #endif filebench_log(LOG_DEBUG_SCRIPT, "aio2 completed %d ios, uncompleted = %d, inprogress = %d", ncompleted, uncompleted, inprogress); } while (uncompleted > MAXREAP); flowop_endop(threadflow, flowop, 0); free(worklist); return (FILEBENCH_OK); } #endif /* HAVE_AIO */ /* * Does an open64 of a file. Inserts the file descriptor number returned * by open() into the supplied filebench fd. Returns FILEBENCH_OK on * successs, and FILEBENCH_ERROR on failure. */ static int fb_lfs_open(fb_fdesc_t *fd, char *path, int flags, int perms) { if ((fd->fd_num = open64(path, flags, perms)) < 0) return (FILEBENCH_ERROR); else return (FILEBENCH_OK); } /* * Does an unlink (delete) of a file. */ static int fb_lfs_unlink(char *path) { return (unlink(path)); } /* * Does a readlink of a symbolic link. */ static ssize_t fb_lfs_readlink(const char *path, char *buf, size_t buf_size) { return (readlink(path, buf, buf_size)); } /* * Does fsync of a file. Returns with fsync return info. */ static int fb_lfs_fsync(fb_fdesc_t *fd) { return (fsync(fd->fd_num)); } /* * Do a posix lseek of a file. Return what lseek() returns. */ static int fb_lfs_lseek(fb_fdesc_t *fd, off64_t offset, int whence) { return (lseek64(fd->fd_num, offset, whence)); } /* * Do a posix rename of a file. Return what rename() returns. */ static int fb_lfs_rename(const char *old, const char *new) { return (rename(old, new)); } /* * Do a posix close of a file. Return what close() returns. */ static int fb_lfs_close(fb_fdesc_t *fd) { return (close(fd->fd_num)); } /* * Use mkdir to create a directory. */ static int fb_lfs_mkdir(char *path, int perm) { return (mkdir(path, perm)); } /* * Use rmdir to delete a directory. Returns what rmdir() returns. */ static int fb_lfs_rmdir(char *path) { return (rmdir(path)); } /* * does a recursive rm to remove an entire directory tree (i.e. a fileset). * Supplied with the path to the root of the tree. */ static void fb_lfs_recur_rm(char *path) { char cmd[MAXPATHLEN]; (void) snprintf(cmd, sizeof (cmd), "rm -rf %s", path); /* We ignore system()'s return value */ if (system(cmd)); return; } /* * Does a posix opendir(), Returns a directory handle on success, * NULL on failure. */ static DIR * fb_lfs_opendir(char *path) { return (opendir(path)); } /* * Does a readdir() call. Returns a pointer to a table of directory * information on success, NULL on failure. */ static struct dirent * fb_lfs_readdir(DIR *dirp) { return (readdir(dirp)); } /* * Does a closedir() call. */ static int fb_lfs_closedir(DIR *dirp) { return (closedir(dirp)); } /* * Does an fstat of a file. */ static int fb_lfs_fstat(fb_fdesc_t *fd, struct stat64 *statbufp) { return (fstat64(fd->fd_num, statbufp)); } /* * Does a stat of a file. */ static int fb_lfs_stat(char *path, struct stat64 *statbufp) { return (stat64(path, statbufp)); } /* * Do a pwrite64 to a file. */ static int fb_lfs_pwrite(fb_fdesc_t *fd, caddr_t iobuf, fbint_t iosize, off64_t offset) { return (pwrite64(fd->fd_num, iobuf, iosize, offset)); } /* * Do a write to a file. */ static int fb_lfs_write(fb_fdesc_t *fd, caddr_t iobuf, fbint_t iosize) { return (write(fd->fd_num, iobuf, iosize)); } /* * Does a truncate operation and returns the result */ static int fb_lfs_truncate(fb_fdesc_t *fd, off64_t fse_size) { #ifdef HAVE_FTRUNCATE64 return (ftruncate64(fd->fd_num, fse_size)); #else filebench_log(LOG_ERROR, "Converting off64_t to off_t in ftruncate," " might be a possible problem"); return (ftruncate(fd->fd_num, (off_t)fse_size)); #endif } /* * Does a link operation and returns the result */ static int fb_lfs_link(const char *existing, const char *new) { return (link(existing, new)); } /* * Does a symlink operation and returns the result */ static int fb_lfs_symlink(const char *existing, const char *new) { return (symlink(existing, new)); } /* * Does an access() check on a file. */ static int fb_lfs_access(const char *path, int amode) { return (access(path, amode)); }
16,441
22.96793
79
c
filebench
filebench-master/fb_random.c
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #include <stdio.h> #include <fcntl.h> /* this definition prevents warning about using undefined round() function */ #include <math.h> #include "filebench.h" #include "ipc.h" #include "gamma_dist.h" #include "cvars/mtwist/mtwist.h" /* * Generates a 64-bit random number using mtwist or from a provided random * variable "avd". * * Returned random number "randp" is clipped by the "max" value and rounded off * by the "round" value. Returns 0 on success, shuts down Filebench on * failure. */ void fb_random64(uint64_t *randp, uint64_t max, uint64_t round, avd_t avd) { double random_normalized; uint64_t random = 0; if (avd) { /* get it from the random variable */ if (!AVD_IS_RANDOM(avd)) { /* trying to get random value not from random variable. That's a clear error. */ filebench_log(LOG_ERROR, "filebench_randomno64: trying" " to get a random value from not a random variable"); filebench_shutdown(1); /* NOT REACHABLE */ } else { random = avd_get_int(avd); } } else { random = mt_llrand(); } /* * If round is not zero, then caller will get a random number in the * range [0; max - round]. This allows the caller to use this * function, for example, to obtain a pointer in an allocated memory * region of [0; max] and read/write round bytes safely starting * at this pointer. */ max = max - round; random_normalized = (double)random / UINT64_MAX; random = random_normalized * max; if (round) { random = random / round; random = random * round; } *randp = random; } /* * Same as filebench_randomno64, but for 32 bit integers. */ void fb_random32(uint32_t *randp, uint32_t max, uint32_t round, avd_t avd) { uint64_t rand64; fb_random64(&rand64, max, round, avd); /* rand64 always fits uint32, since "max" above was 32 bit */ *randp = (uint32_t)rand64; } /* * Same as filebench_randomno64, but for probability [0-1]. */ static double fb_random_probability() { uint64_t randnum; fb_random64(&randnum, UINT64_MAX, 0, NULL); /* convert to 0-1 probability */ return (double)randnum / (double)(UINT64_MAX); } /**************************************** * * * randist related functions * * * ****************************************/ static double fb_rand_src_rand48(unsigned short *xi) { return (erand48(xi)); } static double fb_rand_src_random(unsigned short *xi) { return fb_random_probability(); } /* * fetch a uniformly distributed random number from the supplied * random object. */ static double rand_uniform_get(randdist_t *rndp) { double dprob, dmin, dres, dround; dmin = (double)rndp->rnd_vint_min; dround = (double)rndp->rnd_vint_round; dprob = (*rndp->rnd_src)(rndp->rnd_xi); dres = (dprob * (2.0 * (rndp->rnd_dbl_mean - dmin))) + dmin; if (dround == 0.0) return (dres); else return (round(dres / dround) * dround); } /* * fetch a gamma distributed random number from the supplied * random object. */ static double rand_gamma_get(randdist_t *rndp) { double dmult, dres, dmin, dround; dmin = (double)rndp->rnd_vint_min; dround = (double)rndp->rnd_vint_round; dmult = (rndp->rnd_dbl_mean - dmin) / rndp->rnd_dbl_gamma; dres = gamma_dist_knuth_src(rndp->rnd_dbl_gamma, dmult, rndp->rnd_src, rndp->rnd_xi) + dmin; if (dround == 0.0) return (dres); else return (round(dres / dround) * dround); } /* * fetch a table driven random number from the supplied * random object. */ static double rand_table_get(randdist_t *rndp) { double dprob, dprcnt, dtabres, dsclres, dmin, dround; int idx; dmin = (double)rndp->rnd_vint_min; dround = (double)rndp->rnd_vint_round; dprob = (*rndp->rnd_src)(rndp->rnd_xi); dprcnt = (dprob * (double)(PF_TAB_SIZE)); idx = (int)dprcnt; dtabres = (rndp->rnd_rft[idx].rf_base + (rndp->rnd_rft[idx].rf_range * (dprcnt - (double)idx))); dsclres = (dtabres * (rndp->rnd_dbl_mean - dmin)) + dmin; if (dround == 0.0) return (dsclres); else return (round(dsclres / dround) * dround); } /* * Set the random seed in the supplied random object. */ static void rand_seed_set(randdist_t *rndp) { union { uint64_t ll; uint16_t w[4]; } temp1; int idx; temp1.ll = (uint64_t)avd_get_int(rndp->rnd_seed); for (idx = 0; idx < 3; idx++) { #ifdef _BIG_ENDIAN rndp->rnd_xi[idx] = temp1.w[3-idx]; #else rndp->rnd_xi[idx] = temp1.w[idx]; #endif } } /* * Define a random entity which will contain the parameters of a random * distribution. */ randdist_t * randdist_alloc(void) { randdist_t *rndp; if ((rndp = (randdist_t *)ipc_malloc(FILEBENCH_RANDDIST)) == NULL) { filebench_log(LOG_ERROR, "Out of memory for random dist"); return (NULL); } /* place on global list */ rndp->rnd_next = filebench_shm->shm_rand_list; filebench_shm->shm_rand_list = rndp; return (rndp); } /* * Initializes a random distribution entity, converting avd_t parameters to * doubles, and converting the list of probability density function table * entries, if supplied, into a probablilty function table. */ void randdist_init(randdist_t *rndp) { probtabent_t *rdte_hdp, *ptep; double tablemean, tablemin = 0; int pteidx; /* convert parameters to doubles */ rndp->rnd_dbl_gamma = (double)avd_get_int(rndp->rnd_gamma) / 1000.0; if (rndp->rnd_mean != NULL) rndp->rnd_dbl_mean = (double)avd_get_int(rndp->rnd_mean); else rndp->rnd_dbl_mean = rndp->rnd_dbl_gamma; /* de-reference min and round amounts for later use */ rndp->rnd_vint_min = avd_get_int(rndp->rnd_min); rndp->rnd_vint_round = avd_get_int(rndp->rnd_round); filebench_log(LOG_DEBUG_IMPL, "init random var: Mean = %6.0llf, Gamma = %6.3llf, Min = %llu", rndp->rnd_dbl_mean, rndp->rnd_dbl_gamma, (u_longlong_t)rndp->rnd_vint_min); /* initialize distribution to apply */ switch (rndp->rnd_type & RAND_TYPE_MASK) { case RAND_TYPE_UNIFORM: rndp->rnd_get = rand_uniform_get; break; case RAND_TYPE_GAMMA: rndp->rnd_get = rand_gamma_get; break; case RAND_TYPE_TABLE: rndp->rnd_get = rand_table_get; break; default: filebench_log(LOG_DEBUG_IMPL, "Random Type not Specified"); filebench_shutdown(1); return; } /* initialize source of random numbers */ if (rndp->rnd_type & RAND_SRC_GENERATOR) { rndp->rnd_src = fb_rand_src_rand48; rand_seed_set(rndp); } else { rndp->rnd_src = fb_rand_src_random; } /* any random distribution table to convert? */ if ((rdte_hdp = rndp->rnd_probtabs) == NULL) return; /* determine random distribution max and mins and initialize table */ pteidx = 0; tablemean = 0.0; for (ptep = rdte_hdp; ptep; ptep = ptep->pte_next) { double dmin, dmax; int entcnt; dmax = (double)avd_get_int(ptep->pte_segmax); dmin = (double)avd_get_int(ptep->pte_segmin); /* initialize table minimum on first pass */ if (pteidx == 0) tablemin = dmin; /* update table minimum */ if (tablemin > dmin) tablemin = dmin; entcnt = (int)avd_get_int(ptep->pte_percent); tablemean += (((dmin + dmax)/2.0) * (double)entcnt); /* populate the lookup table */ for (; entcnt > 0; entcnt--) { rndp->rnd_rft[pteidx].rf_base = dmin; rndp->rnd_rft[pteidx].rf_range = dmax - dmin; pteidx++; } } /* check to see if probability equals 100% */ if (pteidx != PF_TAB_SIZE) filebench_log(LOG_ERROR, "Prob table only totals %d%%", pteidx); /* If table is not supplied with a mean value, set it to table mean */ if (rndp->rnd_dbl_mean == 0.0) rndp->rnd_dbl_mean = (double)tablemean / (double)PF_TAB_SIZE; /* now normalize the entries for a min value of 0, mean of 1 */ tablemean = (tablemean / 100.0) - tablemin; /* special case if really a constant value */ if (tablemean == 0.0) { for (pteidx = 0; pteidx < PF_TAB_SIZE; pteidx++) { rndp->rnd_rft[pteidx].rf_base = 0.0; rndp->rnd_rft[pteidx].rf_range = 0.0; } return; } for (pteidx = 0; pteidx < PF_TAB_SIZE; pteidx++) { rndp->rnd_rft[pteidx].rf_base = ((rndp->rnd_rft[pteidx].rf_base - tablemin) / tablemean); rndp->rnd_rft[pteidx].rf_range = (rndp->rnd_rft[pteidx].rf_range / tablemean); } }
9,001
23.198925
79
c
filebench
filebench-master/fb_random.h
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _FB_RANDOM_H #define _FB_RANDOM_H #pragma ident "%Z%%M% %I% %E% SMI" #include "filebench.h" /* * probability table entry, used while parsing the supplied * probability table */ typedef struct probtabent { struct probtabent *pte_next; avd_t pte_percent; avd_t pte_segmin; avd_t pte_segmax; } probtabent_t; /* * The supplied probability table is converted into a probability funtion * lookup table at initialization time. This is the definition for each * entry in the table. */ typedef struct randfunc { double rf_base; double rf_range; } randfunc_t; /* Number of entries in the probability function table */ #define PF_TAB_SIZE 100 /* * Random Distribution definition object. Includes a pointer to the * appropriate function to access the distribution defined by the object, * as well as a function pointer to the specified source of random * numbers. */ typedef struct randdist { double (*rnd_get)(struct randdist *); double (*rnd_src)(unsigned short *); struct randdist *rnd_next; avd_t rnd_seed; avd_t rnd_mean; avd_t rnd_gamma; avd_t rnd_min; avd_t rnd_round; double rnd_dbl_mean; double rnd_dbl_gamma; fbint_t rnd_vint_min; fbint_t rnd_vint_round; probtabent_t *rnd_probtabs; randfunc_t rnd_rft[PF_TAB_SIZE]; uint16_t rnd_xi[3]; uint16_t rnd_type; } randdist_t; #define RAND_TYPE_UNIFORM 0x1 #define RAND_TYPE_GAMMA 0x2 #define RAND_TYPE_TABLE 0x3 #define RAND_TYPE_MASK 0x0fff #define RAND_SRC_URANDOM 0x0000 #define RAND_SRC_GENERATOR 0x1000 #define RAND_PARAM_TYPE 1 #define RAND_PARAM_SRC 2 #define RAND_PARAM_SEED 3 #define RAND_PARAM_MIN 4 #define RAND_PARAM_MEAN 5 #define RAND_PARAM_GAMMA 6 #define RAND_PARAM_ROUND 7 /* Function declarations */ extern void fb_random64(uint64_t *, uint64_t, uint64_t, avd_t); extern void fb_random32(uint32_t *, uint32_t, uint32_t, avd_t); extern randdist_t *randdist_alloc(void); extern void randdist_init(randdist_t *rndp); #endif /* _FB_RANDOM_H */
2,906
26.685714
73
h
filebench
filebench-master/fbtime.c
#include <sys/time.h> #include <stdlib.h> #include <stdio.h> #include "fbtime.h" #include "config.h" #include "filebench.h" /* * If we don't have gethrtime() function provided by the environment (which is * usually provided only by Solaris) then we use gettimeofdate(). */ #ifndef HAVE_GETHRTIME hrtime_t gethrtime(void) { struct timeval tv; hrtime_t hrt; gettimeofday(&tv, NULL); hrt = (hrtime_t)tv.tv_sec * 1000000000UL + (hrtime_t)tv.tv_usec * 1000UL; return hrt; } #endif /* HAVE_GETHRTIME */
517
17.5
78
c
filebench
filebench-master/fbtime.h
#ifndef _FBTIME_H #define _FBTIME_H #include "config.h" #ifdef HAVE_STDINT_H #include <stdint.h> #endif #ifndef HAVE_GETHRTIME typedef uint64_t hrtime_t; hrtime_t gethrtime(void); #endif #define SEC2NS_FLOAT (double)1000000000.0 #define SEC2MS_FLOAT (double)1000000.0 #endif /* _FBTIME_H*/
295
14.578947
41
h
filebench
filebench-master/filebench.h
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * Portions Copyright 2008 Denis Cheng */ #ifndef _FB_FILEBENCH_H #define _FB_FILEBENCH_H #include "config.h" #include <stdlib.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/param.h> #include <sys/resource.h> #include <pthread.h> #include <signal.h> #ifndef HAVE_SYSV_SEM #include <semaphore.h> #endif #include <stdio.h> #include <string.h> #include <errno.h> #include <sys/times.h> #ifdef HAVE_STDINT_H #include <stdint.h> #endif /* We use __STDC__ to determine how to handle functions with variable number of arguments in filbench_log function */ #ifdef __STDC__ #include <stdarg.h> #define __V(x) x #ifndef __P #define __P(x) x #endif #else #include <varargs.h> #define __V(x) (va_alist) va_dcl #define __P(x) () #define const #endif #ifdef HAVE_AIO #include <aio.h> #endif #include <dirent.h> /* Defining our internal types */ typedef uint64_t fbint_t; #ifndef HAVE_BOOLEAN_T typedef enum { B_FALSE, B_TRUE } boolean_t; #endif #define TRUE 1 #define FALSE 0 #ifndef HAVE_U_LONGLONG_T typedef unsigned long long u_longlong_t; #endif #ifndef HAVE_UINT_T typedef unsigned int uint_t; #endif #ifndef MIN /* not defined on OpenSolaris */ #define MIN(a,b) (((a)<(b))?(a):(b)) #endif /* change 64-postfixed defininition to the regular: on FreeBSD all these function are already 64bit */ #ifndef HAVE_OFF64_T #define off64_t off_t #endif #ifndef HAVE_STAT64 /* this will replace both: struct stat64 and function stat64 */ #define stat64 stat #endif #ifndef HAVE_AIO_ERROR64 #define aio_error64 aio_error #endif #ifndef HAVE_AIO_WRITE64 #define aio_write64 aio_write #define aiocb64 aiocb #endif #ifndef HAVE_AIO_RETURN64 #define aio_return64 aio_return #endif #ifndef HAVE_OPEN64 #define open64 open #endif #ifndef HAVE_MMAP64 #define mmap64 mmap #endif #ifndef HAVE_FSTAT64 #define fstat64 fstat #endif #ifndef HAVE_LSEEK64 #define lseek64 lseek #endif #ifndef HAVE_PWRITE64 #define pwrite64 pwrite #endif #ifndef HAVE_PREAD64 #define pread64 pread #endif #include "flag.h" #include "vars.h" #include "fb_cvar.h" #include "fb_avl.h" #include "stats.h" #include "procflow.h" #include "misc.h" #include "fsplug.h" #include "fileset.h" #include "threadflow.h" #include "flowop.h" #include "fb_random.h" #include "ipc.h" extern pid_t my_pid; /* this process' process id */ extern procflow_t *my_procflow; /* if slave process, procflow pointer */ extern int errno; extern char *execname; void filebench_log __V((int level, const char *fmt, ...)); void filebench_shutdown(int error); void filebench_plugin_funcvecinit(void); #define FILEBENCH_RANDMAX64 UINT64_MAX #define FILEBENCH_RANDMAX32 UINT32_MAX #if defined(_LP64) || (__WORDSIZE == 64) #define fb_random fb_random64 #define FILEBENCH_RANDMAX FILEBENCH_RANDMAX64 #else #define fb_random fb_random32 #define FILEBENCH_RANDMAX FILEBENCH_RANDMAX32 #endif #ifndef HAVE_SIGIGNORE /* No sigignore on FreeBSD */ static inline int sigignore(int sig) { struct sigaction sa; bzero(&sa, sizeof(sa)); sa.sa_handler = SIG_IGN; return (sigaction(sig, &sa, NULL)); } #endif #define KB (1024LL) #define MB (KB * KB) #define GB (KB * MB) #define KB_FLOAT ((double)1024.0) #define MB_FLOAT (KB_FLOAT * KB_FLOAT) #define GB_FLOAT (KB_FLOAT * MB_FLOAT) #define MMAP_SIZE (1024UL * 1024UL * 1024UL) #define FILEBENCH_VERSION VERSION #define FILEBENCH_PROMPT "filebench> " #define MAX_LINE_LEN 1024 #define MAX_CMD_HIST 128 #define SHUTDOWN_WAIT_SECONDS 3 /* time to wait for proc / thrd to quit */ #define FILEBENCH_DONE 1 #define FILEBENCH_OK 0 #define FILEBENCH_ERROR -1 #define FILEBENCH_NORSC -2 #endif /* _FB_FILEBENCH_H */
4,589
22.782383
74
h
filebench
filebench-master/fileset.c
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * Portions Copyright 2008 Denis Cheng */ #include <fcntl.h> #include <pthread.h> #include <errno.h> #include <math.h> #include <libgen.h> #include <sys/mman.h> #include <sys/shm.h> #include "filebench.h" #include "fileset.h" #include "gamma_dist.h" #include "utils.h" #include "fsplug.h" static int filecreate_done; /* * File sets, of type fileset_t, are entities which contain * information about collections of files and subdirectories in Filebench. * The fileset, once populated, consists of a tree of fileset entries of * type filesetentry_t which specify files and directories. The fileset * is rooted in a directory specified by fileset_path, and once the populated * fileset has been created, has a tree of directories and files * corresponding to the fileset's filesetentry tree. * * Fileset entities are allocated by fileset_define() which is called from * parser_gram.y: parser_fileset_define(). The filesetentry tree corrseponding * to the eventual directory and file tree to be instantiated on the storage * medium is built by fileset_populate(), which is This routine is called * from fileset_createset(), which is in turn called by fileset_createset(). * After calling fileset_populate(), fileset_createset() will call * fileset_create() to pre-allocate designated files and directories. * * Fileset_createset() is called from parser_gram.y: parser_create_fileset() * when a "create fileset" or "run" command is encountered. When the * "create fileset" command is used, it is generally paired with * a "create processes" command, and must appear first, in order to * instantiate all the files in the fileset before trying to use them. */ /* maximum parallel allocation control */ #define MAX_PARALLOC_THREADS 32 /* * returns pointer to file or fileset * string, as appropriate */ static char * fileset_entity_name(fileset_t *fileset) { if (fileset->fs_attrs & FILESET_IS_FILE) return ("file"); else return ("fileset"); } /* * Removes the last file or directory name from a pathname. * Basically removes characters from the end of the path by * setting them to \0 until a forward slash '/' is * encountered. It also removes the forward slash. */ static char * trunc_dirname(char *dir) { char *s = dir + strlen(dir); while (s != dir) { int c = *s; *s = 0; if (c == '/') break; s--; } return (dir); } /* * Creates a path string from the filesetentry_t "*entry" * and all of its parent's path names. The resulting path * is a concatination of all the individual parent paths. * Allocates memory for the path string and returns a * pointer to it. */ char * fileset_resolvepath(filesetentry_t *entry) { filesetentry_t *fsep = entry; char path[MAXPATHLEN]; char pathtmp[MAXPATHLEN]; char *s; path[0] = '\0'; while (fsep->fse_parent) { (void) strcpy(pathtmp, "/"); (void) fb_strlcat(pathtmp, fsep->fse_path, MAXPATHLEN); (void) fb_strlcat(pathtmp, path, MAXPATHLEN); (void) fb_strlcpy(path, pathtmp, MAXPATHLEN); fsep = fsep->fse_parent; } s = malloc(strlen(path) + 1); (void) fb_strlcpy(s, path, MAXPATHLEN); return (s); } /* * Creates multiple nested directories as required by the * supplied path. Starts at the end of the path, creating * a list of directories to mkdir, up to the root of the * path, then mkdirs them one at a time from the root on down. */ static int fileset_mkdir(char *path, int mode) { char *p; char *dirs[65536]; int i = 0; if ((p = strdup(path)) == NULL) goto null_str; /* * Fill an array of subdirectory path names until either we * reach the root or encounter an already existing subdirectory */ /* CONSTCOND */ while (1) { struct stat64 sb; if (stat64(p, &sb) == 0) break; if (strlen(p) < 3) break; if ((dirs[i] = strdup(p)) == NULL) { free(p); goto null_str; } (void) trunc_dirname(p); i++; } /* Make the directories, from closest to root downwards. */ for (--i; i >= 0; i--) { (void) FB_MKDIR(dirs[i], mode); free(dirs[i]); } free(p); return (FILEBENCH_OK); null_str: /* clean up */ for (--i; i >= 0; i--) free(dirs[i]); filebench_log(LOG_ERROR, "Failed to create directory path %s: Out of memory", path); return (FILEBENCH_ERROR); } /* * creates the subdirectory tree for a fileset. */ static int fileset_create_subdirs(fileset_t *fileset, char *filesetpath) { filesetentry_t *direntry; char full_path[MAXPATHLEN]; char *part_path; /* walk the subdirectory list, enstanciating subdirs */ direntry = fileset->fs_dirlist; while (direntry) { (void) fb_strlcpy(full_path, filesetpath, MAXPATHLEN); part_path = fileset_resolvepath(direntry); (void) fb_strlcat(full_path, part_path, MAXPATHLEN); free(part_path); /* now create this portion of the subdirectory tree */ if (fileset_mkdir(full_path, 0755) == FILEBENCH_ERROR) return (FILEBENCH_ERROR); direntry = direntry->fse_nextoftype; } return (FILEBENCH_OK); } /* * move filesetentry between exist tree and non-exist tree, source_tree * to destination tree. */ static void fileset_move_entry(avl_tree_t *src_tree, avl_tree_t *dst_tree, filesetentry_t *entry) { avl_remove(src_tree, entry); avl_add(dst_tree, entry); } /* * given a fileset entry, determines if the associated leaf directory * needs to be made or not, and if so does the mkdir. */ static int fileset_alloc_leafdir(filesetentry_t *entry) { fileset_t *fileset; char path[MAXPATHLEN]; struct stat64 sb; char *pathtmp; fileset = entry->fse_fileset; (void) fb_strlcpy(path, avd_get_str(fileset->fs_path), MAXPATHLEN); (void) fb_strlcat(path, "/", MAXPATHLEN); (void) fb_strlcat(path, avd_get_str(fileset->fs_name), MAXPATHLEN); pathtmp = fileset_resolvepath(entry); (void) fb_strlcat(path, pathtmp, MAXPATHLEN); free(pathtmp); filebench_log(LOG_DEBUG_IMPL, "Populated %s", entry->fse_path); /* see if not reusing and this directory does not exist */ if (!((entry->fse_flags & FSE_REUSING) && (stat64(path, &sb) == 0))) { /* No file or not reusing, so create */ if (FB_MKDIR(path, 0755) < 0) { filebench_log(LOG_ERROR, "Failed to pre-allocate leaf directory %s: %s", path, strerror(errno)); fileset_unbusy(entry, TRUE, FALSE, 0); return (FILEBENCH_ERROR); } } /* unbusy the allocated entry */ fileset_unbusy(entry, TRUE, TRUE, 0); return (FILEBENCH_OK); } /* * given a fileset entry, determines if the associated file * needs to be allocated or not, and if so does the allocation. */ static int fileset_alloc_file(filesetentry_t *entry) { fileset_t *fileset; char path[MAXPATHLEN]; char *buf; struct stat64 sb; char *pathtmp; off64_t seek; fb_fdesc_t fdesc; int trust_tree; int fs_readonly; fileset = entry->fse_fileset; (void) fb_strlcpy(path, avd_get_str(fileset->fs_path), MAXPATHLEN); (void) fb_strlcat(path, "/", MAXPATHLEN); (void) fb_strlcat(path, avd_get_str(fileset->fs_name), MAXPATHLEN); pathtmp = fileset_resolvepath(entry); (void) fb_strlcat(path, pathtmp, MAXPATHLEN); free(pathtmp); filebench_log(LOG_DEBUG_IMPL, "Populated %s", entry->fse_path); /* see if fileset is readonly */ fs_readonly = avd_get_bool(fileset->fs_readonly) == TRUE; /* see if reusing and this file exists */ trust_tree = avd_get_bool(fileset->fs_trust_tree); if ((entry->fse_flags & FSE_REUSING) && (trust_tree || (FB_STAT(path, &sb) == 0))) { if (FB_OPEN(&fdesc, path, fs_readonly ? O_RDONLY : O_RDWR, 0) == FILEBENCH_ERROR) { filebench_log(LOG_INFO, "Attempted but failed to Re-use file %s", path); fileset_unbusy(entry, TRUE, FALSE, 0); return (FILEBENCH_ERROR); } if (trust_tree || (sb.st_size == (off64_t)entry->fse_size)) { filebench_log(LOG_DEBUG_IMPL, "Reusing file %s", path); (void) FB_CLOSE(&fdesc); /* unbusy the allocated entry */ fileset_unbusy(entry, TRUE, TRUE, 0); return (FILEBENCH_OK); } else if (sb.st_size > (off64_t)entry->fse_size) { /* reuse, but too large */ filebench_log(LOG_DEBUG_IMPL, "Truncating & re-using file %s", path); (void) FB_FTRUNC(&fdesc, (off64_t)entry->fse_size); (void) FB_CLOSE(&fdesc); /* unbusy the allocated entry */ fileset_unbusy(entry, TRUE, TRUE, 0); return (FILEBENCH_OK); } } else { /* No file or not reusing, so create */ if (FB_OPEN(&fdesc, path, O_RDWR | O_CREAT, 0644) == FILEBENCH_ERROR) { filebench_log(LOG_ERROR, "Failed to pre-allocate file %s: %s", path, strerror(errno)); /* unbusy the unallocated entry */ fileset_unbusy(entry, TRUE, FALSE, 0); return (FILEBENCH_ERROR); } } if ((buf = (char *)malloc(FILE_ALLOC_BLOCK)) == NULL) { /* unbusy the unallocated entry */ fileset_unbusy(entry, TRUE, FALSE, 0); return (FILEBENCH_ERROR); } for (seek = 0; seek < entry->fse_size; ) { off64_t wsize; int ret = 0; /* * Write FILE_ALLOC_BLOCK's worth, * except on last write */ wsize = MIN(entry->fse_size - seek, FILE_ALLOC_BLOCK); ret = FB_WRITE(&fdesc, buf, wsize); if (ret != wsize) { filebench_log(LOG_ERROR, "Failed to pre-allocate file %s: %s", path, strerror(errno)); (void) FB_CLOSE(&fdesc); free(buf); fileset_unbusy(entry, TRUE, FALSE, 0); return (FILEBENCH_ERROR); } seek += wsize; } (void) FB_CLOSE(&fdesc); free(buf); /* unbusy the allocated entry */ fileset_unbusy(entry, TRUE, TRUE, 0); filebench_log(LOG_DEBUG_IMPL, "Pre-allocated file %s size %llu", path, (u_longlong_t)entry->fse_size); return (FILEBENCH_OK); } /* * given a fileset entry, determines if the associated file * needs to be allocated or not, and if so does the allocation. * Sets shm_fsparalloc_count to -1 on error. */ static void * fileset_alloc_thread(filesetentry_t *entry) { if (fileset_alloc_file(entry) == FILEBENCH_ERROR) { (void) pthread_mutex_lock(&filebench_shm->shm_fsparalloc_lock); filebench_shm->shm_fsparalloc_count = -1; } else { (void) pthread_mutex_lock(&filebench_shm->shm_fsparalloc_lock); filebench_shm->shm_fsparalloc_count--; } (void) pthread_cond_signal(&filebench_shm->shm_fsparalloc_cv); (void) pthread_mutex_unlock(&filebench_shm->shm_fsparalloc_lock); pthread_exit(NULL); return (NULL); } /* * First creates the parent directories of the file using * fileset_mkdir(). Then Optionally sets the O_DSYNC flag * and opens the file with open64(). It unlocks the fileset * entry lock, sets the DIRECTIO_ON or DIRECTIO_OFF flags * as requested, and returns the file descriptor integer * for the opened file in the supplied filebench file descriptor. * Returns FILEBENCH_ERROR on error, and FILEBENCH_OK on success. */ int fileset_openfile(fb_fdesc_t *fdesc, fileset_t *fileset, filesetentry_t *entry, int flag, int filemode, int attrs) { char path[MAXPATHLEN]; char dir[MAXPATHLEN]; char *pathtmp; struct stat64 sb; int open_attrs = 0; (void) fb_strlcpy(path, avd_get_str(fileset->fs_path), MAXPATHLEN); (void) fb_strlcat(path, "/", MAXPATHLEN); (void) fb_strlcat(path, avd_get_str(fileset->fs_name), MAXPATHLEN); pathtmp = fileset_resolvepath(entry); (void) fb_strlcat(path, pathtmp, MAXPATHLEN); (void) fb_strlcpy(dir, path, MAXPATHLEN); free(pathtmp); (void) trunc_dirname(dir); /* If we are going to create a file, create the parent dirs */ if ((flag & O_CREAT) && (stat64(dir, &sb) != 0)) { if (fileset_mkdir(dir, 0755) == FILEBENCH_ERROR) return (FILEBENCH_ERROR); } if (attrs & FLOW_ATTR_DSYNC) open_attrs |= O_SYNC; #ifdef HAVE_O_DIRECT if (attrs & FLOW_ATTR_DIRECTIO) open_attrs |= O_DIRECT; #endif /* HAVE_O_DIRECT */ if (FB_OPEN(fdesc, path, flag | open_attrs, filemode) == FILEBENCH_ERROR) { filebench_log(LOG_ERROR, "Failed to open file %d, %s, with status %x: %s", entry->fse_index, path, entry->fse_flags, strerror(errno)); fileset_unbusy(entry, FALSE, FALSE, 0); return (FILEBENCH_ERROR); } #ifdef HAVE_DIRECTIO if (attrs & FLOW_ATTR_DIRECTIO) (void)directio(fdesc->fd_num, DIRECTIO_ON); #endif /* HAVE_DIRECTIO */ #ifdef HAVE_NOCACHE_FCNTL if (attrs & FLOW_ATTR_DIRECTIO) (void)fcntl(fdesc->fd_num, F_NOCACHE, 1); #endif /* HAVE_NOCACHE_FCNTL */ /* Disable read ahead with the help of fadvise, if asked for */ if (attrs & FLOW_ATTR_FADV_RANDOM) { #ifdef HAVE_FADVISE if (posix_fadvise(fdesc->fd_num, 0, 0, POSIX_FADV_RANDOM) != FILEBENCH_OK) { filebench_log(LOG_ERROR, "Failed to disable read ahead for file %s, with status %s", path, strerror(errno)); fileset_unbusy(entry, FALSE, FALSE, 0); return (FILEBENCH_ERROR); } filebench_log(LOG_INFO, "** Read ahead disabled **"); #else filebench_log(LOG_INFO, "** Read ahead was NOT disabled: not supported on this platform! **"); #endif } if (flag & O_CREAT) fileset_unbusy(entry, TRUE, TRUE, 1); else fileset_unbusy(entry, FALSE, FALSE, 1); return (FILEBENCH_OK); } /* * removes all filesetentries from their respective btrees, and puts them * on the free list. The supplied argument indicates which free list to * use. */ static void fileset_pickreset(fileset_t *fileset, int entry_type) { filesetentry_t *entry; switch (entry_type & FILESET_PICKMASK) { case FILESET_PICKFILE: entry = (filesetentry_t *)avl_first(&fileset->fs_noex_files); /* make sure non-existing files are marked free */ while (entry) { entry->fse_flags |= FSE_FREE; entry->fse_open_cnt = 0; fileset_move_entry(&fileset->fs_noex_files, &fileset->fs_free_files, entry); entry = AVL_NEXT(&fileset->fs_noex_files, entry); } /* free up any existing files */ entry = (filesetentry_t *)avl_first(&fileset->fs_exist_files); while (entry) { entry->fse_flags |= FSE_FREE; entry->fse_open_cnt = 0; fileset_move_entry(&fileset->fs_exist_files, &fileset->fs_free_files, entry); entry = AVL_NEXT(&fileset->fs_exist_files, entry); } break; case FILESET_PICKDIR: /* nothing to reset, as all (sub)dirs always exist */ break; case FILESET_PICKLEAFDIR: entry = (filesetentry_t *) avl_first(&fileset->fs_noex_leaf_dirs); /* make sure non-existing leaf dirs are marked free */ while (entry) { entry->fse_flags |= FSE_FREE; entry->fse_open_cnt = 0; fileset_move_entry(&fileset->fs_noex_leaf_dirs, &fileset->fs_free_leaf_dirs, entry); entry = AVL_NEXT(&fileset->fs_noex_leaf_dirs, entry); } /* free up any existing leaf dirs */ entry = (filesetentry_t *) avl_first(&fileset->fs_exist_leaf_dirs); while (entry) { entry->fse_flags |= FSE_FREE; entry->fse_open_cnt = 0; fileset_move_entry(&fileset->fs_exist_leaf_dirs, &fileset->fs_free_leaf_dirs, entry); entry = AVL_NEXT(&fileset->fs_exist_leaf_dirs, entry); } break; } } /* * find a filesetentry from the fileset using the supplied index */ static filesetentry_t * fileset_find_entry(avl_tree_t *atp, uint_t index) { avl_index_t found_loc; filesetentry_t desired_fse, *found_fse; /* find the file with the desired index, if it is in the tree */ desired_fse.fse_index = index; found_fse = avl_find(atp, (void *)(&desired_fse), &found_loc); if (found_fse != NULL) return (found_fse); /* if requested node not found, find next higher node */ found_fse = avl_nearest(atp, found_loc, AVL_AFTER); if (found_fse != NULL) return (found_fse); /* might have hit the end, return lowest available index node */ found_fse = avl_first(atp); return (found_fse); } /* * Selects a fileset entry from a fileset. If the * FILESET_PICKLEAFDIR flag is set it will pick a leaf directory entry, * if the FILESET_PICKDIR flag is set it will pick a non leaf directory * entry, otherwise a file entry. The FILESET_PICKUNIQUE * flag will take an entry off of one of the free (unused) * lists (file or directory), otherwise the entry will be * picked off of one of the rotor lists (file or directory). * The FILESET_PICKEXISTS will insure that only extant * (FSE_EXISTS) state files are selected, while * FILESET_PICKNOEXIST insures that only non extant * (not FSE_EXISTS) state files are selected. * Note that the selected fileset entry (file) is returned * with its FSE_BUSY flag (in fse_flags) set. */ filesetentry_t * fileset_pick(fileset_t *fileset, int flags, int tid, int index) { filesetentry_t *entry = NULL; filesetentry_t *start_point; avl_tree_t *atp = NULL; fbint_t max_entries = 0; (void) ipc_mutex_lock(&fileset->fs_pick_lock); /* see if we have to wait for available files or directories */ switch (flags & FILESET_PICKMASK) { case FILESET_PICKFILE: filebench_log(LOG_DEBUG_SCRIPT, "Picking file"); if (fileset->fs_filelist == NULL) goto empty; while (fileset->fs_idle_files == 0) { (void) pthread_cond_wait(&fileset->fs_idle_files_cv, &fileset->fs_pick_lock); } max_entries = fileset->fs_constentries; if (flags & FILESET_PICKUNIQUE) { filebench_log(LOG_DEBUG_SCRIPT, "Picking unique"); atp = &fileset->fs_free_files; } else if (flags & FILESET_PICKNOEXIST) { filebench_log(LOG_DEBUG_SCRIPT, "Picking not existing"); atp = &fileset->fs_noex_files; } else { filebench_log(LOG_DEBUG_SCRIPT, "Picking existing"); atp = &fileset->fs_exist_files; } break; case FILESET_PICKDIR: filebench_log(LOG_DEBUG_SCRIPT, "Picking directory"); if (fileset->fs_dirlist == NULL) goto empty; while (fileset->fs_idle_dirs == 0) { (void) pthread_cond_wait(&fileset->fs_idle_dirs_cv, &fileset->fs_pick_lock); } max_entries = 1; atp = &fileset->fs_dirs; break; case FILESET_PICKLEAFDIR: filebench_log(LOG_DEBUG_SCRIPT, "Picking leaf directory"); if (fileset->fs_leafdirlist == NULL) goto empty; while (fileset->fs_idle_leafdirs == 0) { (void) pthread_cond_wait(&fileset->fs_idle_leafdirs_cv, &fileset->fs_pick_lock); } max_entries = fileset->fs_constleafdirs; if (flags & FILESET_PICKUNIQUE) { atp = &fileset->fs_free_leaf_dirs; } else if (flags & FILESET_PICKNOEXIST) { atp = &fileset->fs_noex_leaf_dirs; } else { atp = &fileset->fs_exist_leaf_dirs; } break; } /* see if asking for impossible */ if (avl_is_empty(atp)) { filebench_log(LOG_DEBUG_SCRIPT, "atp is empty"); goto empty; } if (flags & FILESET_PICKUNIQUE) { uint64_t index64; /* * pick at random from free list in order to * distribute initially allocated files more * randomly on storage media. Use uniform * random number generator to select index * if it is not supplied with pick call. */ if (index) { index64 = index; } else { fb_random64(&index64, max_entries, 0, NULL); } entry = fileset_find_entry(atp, (int)index64); if (entry == NULL) goto empty; } else if (flags & FILESET_PICKBYINDEX) { /* pick by supplied index */ entry = fileset_find_entry(atp, index); } else { /* pick in rotation */ switch (flags & FILESET_PICKMASK) { case FILESET_PICKFILE: if (flags & FILESET_PICKNOEXIST) { entry = fileset_find_entry(atp, fileset->fs_file_nerotor); fileset->fs_file_nerotor = entry->fse_index + 1; } else { entry = fileset_find_entry(atp, fileset->fs_file_exrotor[tid]); fileset->fs_file_exrotor[tid] = entry->fse_index + 1; } break; case FILESET_PICKDIR: entry = fileset_find_entry(atp, fileset->fs_dirrotor); fileset->fs_dirrotor = entry->fse_index + 1; break; case FILESET_PICKLEAFDIR: if (flags & FILESET_PICKNOEXIST) { entry = fileset_find_entry(atp, fileset->fs_leafdir_nerotor); fileset->fs_leafdir_nerotor = entry->fse_index + 1; } else { entry = fileset_find_entry(atp, fileset->fs_leafdir_exrotor); fileset->fs_leafdir_exrotor = entry->fse_index + 1; } break; } } if (entry == NULL) goto empty; /* see if entry in use */ start_point = entry; while (entry->fse_flags & FSE_BUSY) { /* it is, so try next */ entry = AVL_NEXT(atp, entry); if (entry == NULL) entry = avl_first(atp); /* see if we have wrapped around */ if ((entry == NULL) || (entry == start_point)) { filebench_log(LOG_DEBUG_SCRIPT, "All %d files are busy", avl_numnodes(atp)); goto empty; } } /* update file or directory idle counts */ switch (flags & FILESET_PICKMASK) { case FILESET_PICKFILE: fileset->fs_idle_files--; break; case FILESET_PICKDIR: fileset->fs_idle_dirs--; break; case FILESET_PICKLEAFDIR: fileset->fs_idle_leafdirs--; break; } /* Indicate that file or directory is now busy */ entry->fse_flags |= FSE_BUSY; (void) ipc_mutex_unlock(&fileset->fs_pick_lock); filebench_log(LOG_DEBUG_SCRIPT, "Picked file %s", entry->fse_path); return (entry); empty: filebench_log(LOG_DEBUG_SCRIPT, "No file found"); (void) ipc_mutex_unlock(&fileset->fs_pick_lock); return (NULL); } /* * Removes a filesetentry from the "FSE_BUSY" state, signaling any threads * that are waiting for a NOT BUSY filesetentry. Also sets whether it is * existant or not, or leaves that designation alone. */ void fileset_unbusy(filesetentry_t *entry, int update_exist, int new_exist_val, int open_cnt_incr) { fileset_t *fileset = NULL; if (entry) fileset = entry->fse_fileset; if (fileset == NULL) { filebench_log(LOG_ERROR, "fileset_unbusy: NO FILESET!"); return; } (void) ipc_mutex_lock(&fileset->fs_pick_lock); /* modify FSE_EXIST flag and actual dirs/files count, if requested */ if (update_exist) { if (new_exist_val == TRUE) { if (entry->fse_flags & FSE_FREE) { /* asked to set and it was free */ entry->fse_flags |= FSE_EXISTS; entry->fse_flags &= (~FSE_FREE); switch (entry->fse_flags & FSE_TYPE_MASK) { case FSE_TYPE_FILE: fileset_move_entry( &fileset->fs_free_files, &fileset->fs_exist_files, entry); break; case FSE_TYPE_DIR: break; case FSE_TYPE_LEAFDIR: fileset_move_entry( &fileset->fs_free_leaf_dirs, &fileset->fs_exist_leaf_dirs, entry); break; } } else if (!(entry->fse_flags & FSE_EXISTS)) { /* asked to set, and it was clear */ entry->fse_flags |= FSE_EXISTS; switch (entry->fse_flags & FSE_TYPE_MASK) { case FSE_TYPE_FILE: fileset_move_entry( &fileset->fs_noex_files, &fileset->fs_exist_files, entry); break; case FSE_TYPE_DIR: break; case FSE_TYPE_LEAFDIR: fileset_move_entry( &fileset->fs_noex_leaf_dirs, &fileset->fs_exist_leaf_dirs, entry); break; } } } else { if (entry->fse_flags & FSE_FREE) { /* asked to clear, and it was free */ entry->fse_flags &= (~(FSE_FREE | FSE_EXISTS)); switch (entry->fse_flags & FSE_TYPE_MASK) { case FSE_TYPE_FILE: fileset_move_entry( &fileset->fs_free_files, &fileset->fs_noex_files, entry); break; case FSE_TYPE_DIR: break; case FSE_TYPE_LEAFDIR: fileset_move_entry( &fileset->fs_free_leaf_dirs, &fileset->fs_noex_leaf_dirs, entry); break; } } else if (entry->fse_flags & FSE_EXISTS) { /* asked to clear, and it was set */ entry->fse_flags &= (~FSE_EXISTS); switch (entry->fse_flags & FSE_TYPE_MASK) { case FSE_TYPE_FILE: fileset_move_entry( &fileset->fs_exist_files, &fileset->fs_noex_files, entry); break; case FSE_TYPE_DIR: break; case FSE_TYPE_LEAFDIR: fileset_move_entry( &fileset->fs_exist_leaf_dirs, &fileset->fs_noex_leaf_dirs, entry); break; } } } } /* update open count */ entry->fse_open_cnt += open_cnt_incr; /* increment idle count, clear FSE_BUSY and signal IF it was busy */ if (entry->fse_flags & FSE_BUSY) { /* unbusy it */ entry->fse_flags &= (~FSE_BUSY); /* release any threads waiting for unbusy */ if (entry->fse_flags & FSE_THRD_WAITNG) { entry->fse_flags &= (~FSE_THRD_WAITNG); (void) pthread_cond_broadcast( &fileset->fs_thrd_wait_cv); } /* increment idle count and signal waiting threads */ switch (entry->fse_flags & FSE_TYPE_MASK) { case FSE_TYPE_FILE: fileset->fs_idle_files++; if (fileset->fs_idle_files >= 1) { (void) pthread_cond_signal( &fileset->fs_idle_files_cv); } break; case FSE_TYPE_DIR: fileset->fs_idle_dirs++; if (fileset->fs_idle_dirs >= 1) { (void) pthread_cond_signal( &fileset->fs_idle_dirs_cv); } break; case FSE_TYPE_LEAFDIR: fileset->fs_idle_leafdirs++; if (fileset->fs_idle_leafdirs >= 1) { (void) pthread_cond_signal( &fileset->fs_idle_leafdirs_cv); } break; } } (void) ipc_mutex_unlock(&fileset->fs_pick_lock); } /* * Given a fileset "fileset", create the associated files as specified in the * attributes of the fileset. The fileset is rooted in a directory whose * pathname is in fileset_path. If the directory exists, meaning that there is * already a fileset, and the fileset_reuse attribute is false, then remove it * and all its contained files and subdirectories. Next, the routine creates a * root directory for the fileset. All the file type filesetentries are cycled * through creating as needed their containing subdirectory trees in the * filesystem and creating actual files for fileset_preallocpercent of them. * The created files are filled with fse_size bytes of unitialized data. The * routine returns FILEBENCH_ERROR on errors, FILEBENCH_OK on success. */ static int fileset_create(fileset_t *fileset) { filesetentry_t *entry; char path[MAXPATHLEN]; struct stat64 sb; hrtime_t start = gethrtime(); char *fileset_path; char *fileset_name; int randno; int preallocated = 0; int reusing; uint64_t preallocpercent; fileset_path = avd_get_str(fileset->fs_path); if (!fileset_path) { filebench_log(LOG_ERROR, "%s path not set", fileset_entity_name(fileset)); return FILEBENCH_ERROR; } fileset_name = avd_get_str(fileset->fs_name); if (!fileset_name) { filebench_log(LOG_ERROR, "%s name not set", fileset_entity_name(fileset)); return FILEBENCH_ERROR; } /* treat raw device as special case */ if (fileset->fs_attrs & FILESET_IS_RAW_DEV) return FILEBENCH_OK; /* XXX Add check to see if there is enough space */ /* set up path to fileset */ (void) fb_strlcpy(path, fileset_path, MAXPATHLEN); (void) fb_strlcat(path, "/", MAXPATHLEN); (void) fb_strlcat(path, fileset_name, MAXPATHLEN); /* if reusing and trusting to exist, just blindly reuse */ if (avd_get_bool(fileset->fs_trust_tree)) { reusing = 1; /* if exists and resusing, then don't create new */ } else if (((stat64(path, &sb) == 0)&& (strlen(path) > 3) && (strlen(avd_get_str(fileset->fs_path)) > 2)) && avd_get_bool(fileset->fs_reuse)) { reusing = 1; } else { reusing = 0; } if (!reusing) { /* Remove existing */ filebench_log(LOG_INFO, "Removing %s tree (if exists)", fileset_name); FB_RECUR_RM(path); } else { /* we are re-using */ filebench_log(LOG_INFO, "Reusing existing %s tree", fileset_name); } /* make the filesets directory tree unless in reuse mode */ if (!reusing) { filebench_log(LOG_INFO, "Pre-allocating directories in %s tree", fileset_name); (void) FB_MKDIR(path, 0755); if (fileset_create_subdirs(fileset, path) == FILEBENCH_ERROR) return (FILEBENCH_ERROR); } start = gethrtime(); filebench_log(LOG_INFO, "Pre-allocating files in %s tree", fileset_name); if (AVD_IS_BOOL(fileset->fs_preallocpercent)) { if (avd_get_bool(fileset->fs_preallocpercent)) preallocpercent = 100; else preallocpercent = 0; } else preallocpercent = avd_get_int(fileset->fs_preallocpercent); randno = ((RAND_MAX * (100 - preallocpercent)) / 100); /* alloc any files, as required */ fileset_pickreset(fileset, FILESET_PICKFILE); while ((entry = fileset_pick(fileset, FILESET_PICKFREE | FILESET_PICKFILE, 0, 0))) { pthread_t tid; int newrand; newrand = rand(); if (randno && newrand <= randno) { /* unbusy the unallocated entry */ fileset_unbusy(entry, TRUE, FALSE, 0); continue; } preallocated++; if (reusing) entry->fse_flags |= FSE_REUSING; else entry->fse_flags &= (~FSE_REUSING); /* fire off allocation threads for each file if paralloc set */ if (avd_get_bool(fileset->fs_paralloc)) { /* limit total number of simultaneous allocations */ (void) pthread_mutex_lock( &filebench_shm->shm_fsparalloc_lock); while (filebench_shm->shm_fsparalloc_count >= MAX_PARALLOC_THREADS) { (void) pthread_cond_wait( &filebench_shm->shm_fsparalloc_cv, &filebench_shm->shm_fsparalloc_lock); } /* quit if any allocation thread reports an error */ if (filebench_shm->shm_fsparalloc_count < 0) { (void) pthread_mutex_unlock( &filebench_shm->shm_fsparalloc_lock); return (FILEBENCH_ERROR); } filebench_shm->shm_fsparalloc_count++; (void) pthread_mutex_unlock( &filebench_shm->shm_fsparalloc_lock); /* * Fire off a detached allocation thread per file. * The thread will self destruct when it finishes * writing pre-allocation data to the file. */ if (pthread_create(&tid, NULL, (void *(*)(void*))fileset_alloc_thread, entry) == 0) { /* * A thread was created; detach it so it can * fully quit when finished. */ (void) pthread_detach(tid); } else { filebench_log(LOG_ERROR, "File prealloc thread create failed"); filebench_shutdown(1); } } else { if (fileset_alloc_file(entry) == FILEBENCH_ERROR) return FILEBENCH_ERROR; } } /* alloc any leaf directories, as required */ fileset_pickreset(fileset, FILESET_PICKLEAFDIR); while ((entry = fileset_pick(fileset, FILESET_PICKFREE | FILESET_PICKLEAFDIR, 0, 0))) { if (rand() < randno) { /* unbusy the unallocated entry */ fileset_unbusy(entry, TRUE, FALSE, 0); continue; } preallocated++; if (reusing) entry->fse_flags |= FSE_REUSING; else entry->fse_flags &= (~FSE_REUSING); if (fileset_alloc_leafdir(entry) == FILEBENCH_ERROR) return (FILEBENCH_ERROR); } filebench_log(LOG_VERBOSE, "Pre-allocated %d of %llu files in %s in %llu seconds", preallocated, (u_longlong_t)fileset->fs_constentries, fileset_name, (u_longlong_t)(((gethrtime() - start) / 1000000000) + 1)); return (FILEBENCH_OK); } /* * Removes all files and directories associated with a fileset * from the storage subsystem. */ static void fileset_delete_storage(fileset_t *fileset) { char path[MAXPATHLEN]; char *fileset_path; char *fileset_name; if ((fileset_path = avd_get_str(fileset->fs_path)) == NULL) return; if ((fileset_name = avd_get_str(fileset->fs_name)) == NULL) return; /* treat raw device as special case */ if (fileset->fs_attrs & FILESET_IS_RAW_DEV) return; /* set up path to file */ (void) fb_strlcpy(path, fileset_path, MAXPATHLEN); (void) fb_strlcat(path, "/", MAXPATHLEN); (void) fb_strlcat(path, fileset_name, MAXPATHLEN); /* now delete any files and directories on the disk */ FB_RECUR_RM(path); } /* * Removes the fileset entity and all of its filesetentry entities. */ static void fileset_delete_fileset(fileset_t *fileset) { filesetentry_t *entry, *next_entry; /* run down the file list, removing and freeing each filesetentry */ for (entry = fileset->fs_filelist; entry; entry = next_entry) { /* free the entry */ next_entry = entry->fse_next; /* return it to the pool */ switch (entry->fse_flags & FSE_TYPE_MASK) { case FSE_TYPE_FILE: case FSE_TYPE_LEAFDIR: case FSE_TYPE_DIR: ipc_free(FILEBENCH_FILESETENTRY, (void *)entry); break; default: filebench_log(LOG_ERROR, "Unallocated filesetentry found on list"); break; } } ipc_free(FILEBENCH_FILESET, (void *)fileset); } void fileset_delete_all_filesets(void) { fileset_t *fileset, *next_fileset; for (fileset = filebench_shm->shm_filesetlist; fileset; fileset = next_fileset) { next_fileset = fileset->fs_next; fileset_delete_storage(fileset); fileset_delete_fileset(fileset); } filebench_shm->shm_filesetlist = NULL; } /* * Adds an entry to the fileset's file list. Single threaded so * no locking needed. */ static void fileset_insfilelist(fileset_t *fileset, filesetentry_t *entry) { entry->fse_flags = FSE_TYPE_FILE | FSE_FREE; avl_add(&fileset->fs_free_files, entry); if (fileset->fs_filelist == NULL) { fileset->fs_filelist = entry; entry->fse_nextoftype = NULL; } else { entry->fse_nextoftype = fileset->fs_filelist; fileset->fs_filelist = entry; } } /* * Adds an entry to the fileset's directory list. Single * threaded so no locking needed. */ static void fileset_insdirlist(fileset_t *fileset, filesetentry_t *entry) { entry->fse_flags = FSE_TYPE_DIR | FSE_EXISTS; avl_add(&fileset->fs_dirs, entry); if (fileset->fs_dirlist == NULL) { fileset->fs_dirlist = entry; entry->fse_nextoftype = NULL; } else { entry->fse_nextoftype = fileset->fs_dirlist; fileset->fs_dirlist = entry; } } /* * Adds an entry to the fileset's leaf directory list. Single * threaded so no locking needed. */ static void fileset_insleafdirlist(fileset_t *fileset, filesetentry_t *entry) { entry->fse_flags = FSE_TYPE_LEAFDIR | FSE_FREE; avl_add(&fileset->fs_free_leaf_dirs, entry); if (fileset->fs_leafdirlist == NULL) { fileset->fs_leafdirlist = entry; entry->fse_nextoftype = NULL; } else { entry->fse_nextoftype = fileset->fs_leafdirlist; fileset->fs_leafdirlist = entry; } } /* * Compares two fileset entries to determine their relative order */ static int fileset_entry_compare(const void *node_1, const void *node_2) { if (((filesetentry_t *)node_1)->fse_index < ((filesetentry_t *)node_2)->fse_index) return (-1); if (((filesetentry_t *)node_1)->fse_index == ((filesetentry_t *)node_2)->fse_index) return (0); return (1); } /* * Obtains a filesetentry entity for a file to be placed in a * (sub)directory of a fileset. The size of the file may be * specified by fileset_meansize, or calculated from a gamma * distribution of parameter fileset_sizegamma and of mean size * fileset_meansize. The filesetentry entity is placed on the file * list in the specified parent filesetentry entity, which may * be a directory filesetentry, or the root filesetentry in the * fileset. It is also placed on the fileset's list of all * contained files. Returns FILEBENCH_OK if successful or FILEBENCH_ERROR * if ipc memory for the path string cannot be allocated. */ static int fileset_populate_file(fileset_t *fileset, filesetentry_t *parent, int serial) { char tmpname[16]; filesetentry_t *entry; uint_t index; if ((entry = (filesetentry_t *)ipc_malloc(FILEBENCH_FILESETENTRY)) == NULL) { filebench_log(LOG_ERROR, "fileset_populate_file: Can't malloc filesetentry"); return (FILEBENCH_ERROR); } /* Another currently idle file */ (void) ipc_mutex_lock(&fileset->fs_pick_lock); index = fileset->fs_idle_files++; (void) ipc_mutex_unlock(&fileset->fs_pick_lock); entry->fse_index = index; entry->fse_parent = parent; entry->fse_fileset = fileset; fileset_insfilelist(fileset, entry); (void) snprintf(tmpname, sizeof (tmpname), "%08d", serial); if ((entry->fse_path = (char *)ipc_pathalloc(tmpname)) == NULL) { filebench_log(LOG_ERROR, "fileset_populate_file: Can't alloc path string"); return (FILEBENCH_ERROR); } entry->fse_size = (off64_t)avd_get_int(fileset->fs_size); fileset->fs_bytes += entry->fse_size; fileset->fs_realfiles++; return (FILEBENCH_OK); } /* * Obtaines a filesetentry entity for a leaf directory to be placed in a * (sub)directory of a fileset. The leaf directory will always be empty so * it can be created and deleted (mkdir, rmdir) at will. The filesetentry * entity is placed on the leaf directory list in the specified parent * filesetentry entity, which may be a (sub) directory filesetentry, or * the root filesetentry in the fileset. It is also placed on the fileset's * list of all contained leaf directories. Returns FILEBENCH_OK if successful * or FILEBENCH_ERROR if ipc memory cannot be allocated. */ static int fileset_populate_leafdir(fileset_t *fileset, filesetentry_t *parent, int serial) { char tmpname[16]; filesetentry_t *entry; uint_t index; if ((entry = (filesetentry_t *)ipc_malloc(FILEBENCH_FILESETENTRY)) == NULL) { filebench_log(LOG_ERROR, "fileset_populate_file: Can't malloc filesetentry"); return (FILEBENCH_ERROR); } /* Another currently idle leaf directory */ (void) ipc_mutex_lock(&fileset->fs_pick_lock); index = fileset->fs_idle_leafdirs++; (void) ipc_mutex_unlock(&fileset->fs_pick_lock); entry->fse_index = index; entry->fse_parent = parent; entry->fse_fileset = fileset; fileset_insleafdirlist(fileset, entry); (void) snprintf(tmpname, sizeof (tmpname), "%08d", serial); if ((entry->fse_path = (char *)ipc_pathalloc(tmpname)) == NULL) { filebench_log(LOG_ERROR, "fileset_populate_file: Can't alloc path string"); return (FILEBENCH_ERROR); } fileset->fs_realleafdirs++; return (FILEBENCH_OK); } /* * Creates a directory node in a fileset, by obtaining a filesetentry entity * for the node and initializing it according to parameters of the fileset. It * determines a directory tree depth and directory width, optionally using a * gamma distribution. If its calculated depth is less then its actual depth in * the directory tree, it becomes a leaf node and files itself with "width" * number of file type filesetentries, otherwise it files itself with "width" * number of directory type filesetentries, using recursive calls to * fileset_populate_subdir. The end result of the initial call to this routine * is a tree of directories of random width and varying depth with sufficient * leaf directories to contain all required files. Returns FILEBENCH_OK on * success. Returns FILEBENCH_ERROR if ipc path string memory cannot be * allocated and returns the error code (currently also FILEBENCH_ERROR) from * calls to fileset_populate_file or recursive calls to * fileset_populate_subdir. */ static int fileset_populate_subdir(fileset_t *fileset, filesetentry_t *parent, int serial, double depth) { double randepth, drand, ranwidth; int isleaf = 0; char tmpname[16]; filesetentry_t *entry; int i; uint_t index; depth += 1; /* Create dir node */ entry = (filesetentry_t *)ipc_malloc(FILEBENCH_FILESETENTRY); if (!entry) { filebench_log(LOG_ERROR, "fileset_populate_subdir: Can't malloc filesetentry"); return (FILEBENCH_ERROR); } /* another idle directory */ (void) ipc_mutex_lock(&fileset->fs_pick_lock); index = fileset->fs_idle_dirs++; (void) ipc_mutex_unlock(&fileset->fs_pick_lock); (void) snprintf(tmpname, sizeof (tmpname), "%08d", serial); if ((entry->fse_path = (char *)ipc_pathalloc(tmpname)) == NULL) { filebench_log(LOG_ERROR, "fileset_populate_subdir: Can't alloc path string"); return (FILEBENCH_ERROR); } entry->fse_index = index; entry->fse_parent = parent; entry->fse_fileset = fileset; fileset_insdirlist(fileset, entry); if (fileset->fs_dirdepthrv) { randepth = (int)avd_get_int(fileset->fs_dirdepthrv); } else { double gamma; gamma = avd_get_int(fileset->fs_dirgamma) / 1000.0; if (gamma > 0) { drand = gamma_dist_knuth(gamma, fileset->fs_meandepth / gamma); randepth = (int)drand; } else { randepth = (int)fileset->fs_meandepth; } } if (fileset->fs_meanwidth == -1) { ranwidth = avd_get_dbl(fileset->fs_dirwidth); } else { double gamma; gamma = avd_get_int(fileset->fs_dirgamma) / 1000.0; if (gamma > 0) { drand = gamma_dist_knuth(gamma, fileset->fs_meanwidth / gamma); ranwidth = drand; } else { ranwidth = fileset->fs_meanwidth; } } if (randepth == 0) randepth = 1; if (ranwidth == 0) ranwidth = 1; if (depth >= randepth) isleaf = 1; /* * Create directory of random width filled with files according * to distribution, or if root directory, continue until #files required */ for (i = 1; ((parent == NULL) || (i < ranwidth + 1)) && (fileset->fs_realfiles < fileset->fs_constentries); i++) { int ret = 0; if (parent && isleaf) ret = fileset_populate_file(fileset, entry, i); else ret = fileset_populate_subdir(fileset, entry, i, depth); if (ret != 0) return (ret); } /* * Create directory of random width filled with leaf directories * according to distribution, or if root directory, continue until * the number of leaf directories required has been generated. */ for (i = 1; ((parent == NULL) || (i < ranwidth + 1)) && (fileset->fs_realleafdirs < fileset->fs_constleafdirs); i++) { int ret = 0; if (parent && isleaf) ret = fileset_populate_leafdir(fileset, entry, i); else ret = fileset_populate_subdir(fileset, entry, i, depth); if (ret != 0) return (ret); } return (FILEBENCH_OK); } /* * Populates a fileset with files and subdirectory entries. Uses the supplied * fileset_dirwidth and fileset_entries (number of files) to calculate the * required fileset_meandepth (of subdirectories) and initialize the * fileset_meanwidth and fileset_meansize variables. Then calls * fileset_populate_subdir() to do the recursive subdirectory entry creation * and leaf file entry creation. All of the above is skipped if the fileset has * already been populated. Returns 0 on success, or an error code from the call * to fileset_populate_subdir if that call fails. */ static int fileset_populate(fileset_t *fileset) { fbint_t entries = avd_get_int(fileset->fs_entries); fbint_t leafdirs = avd_get_int(fileset->fs_leafdirs); int meandirwidth = 0; int ret; /* Skip if already populated */ if (fileset->fs_bytes > 0) goto exists; /* check for raw device */ if (fileset->fs_attrs & FILESET_IS_RAW_DEV) return (FILEBENCH_OK); /* * save value of entries and leaf dirs obtained for later * in case it was random */ fileset->fs_constentries = entries; fileset->fs_constleafdirs = leafdirs; /* initialize idle files and directories condition variables */ (void) pthread_cond_init(&fileset->fs_idle_files_cv, ipc_condattr()); (void) pthread_cond_init(&fileset->fs_idle_dirs_cv, ipc_condattr()); (void) pthread_cond_init(&fileset->fs_idle_leafdirs_cv, ipc_condattr()); /* no files or dirs idle (or busy) yet */ fileset->fs_idle_files = 0; fileset->fs_idle_dirs = 0; fileset->fs_idle_leafdirs = 0; /* initialize locks and other condition variables */ (void) pthread_mutex_init(&fileset->fs_pick_lock, ipc_mutexattr(IPC_MUTEX_NORMAL)); (void) pthread_mutex_init(&fileset->fs_histo_lock, ipc_mutexattr(IPC_MUTEX_NORMAL)); (void) pthread_cond_init(&fileset->fs_thrd_wait_cv, ipc_condattr()); /* Initialize avl btrees */ avl_create(&(fileset->fs_free_files), fileset_entry_compare, sizeof (filesetentry_t), FSE_OFFSETOF(fse_link)); avl_create(&(fileset->fs_noex_files), fileset_entry_compare, sizeof (filesetentry_t), FSE_OFFSETOF(fse_link)); avl_create(&(fileset->fs_exist_files), fileset_entry_compare, sizeof (filesetentry_t), FSE_OFFSETOF(fse_link)); avl_create(&(fileset->fs_free_leaf_dirs), fileset_entry_compare, sizeof (filesetentry_t), FSE_OFFSETOF(fse_link)); avl_create(&(fileset->fs_noex_leaf_dirs), fileset_entry_compare, sizeof (filesetentry_t), FSE_OFFSETOF(fse_link)); avl_create(&(fileset->fs_exist_leaf_dirs), fileset_entry_compare, sizeof (filesetentry_t), FSE_OFFSETOF(fse_link)); avl_create(&(fileset->fs_dirs), fileset_entry_compare, sizeof (filesetentry_t), FSE_OFFSETOF(fse_link)); /* is dirwidth a random variable? */ if (AVD_IS_RANDOM(fileset->fs_dirwidth)) { meandirwidth = (int)fileset->fs_dirwidth->avd_val.randptr->rnd_dbl_mean; fileset->fs_meanwidth = -1; } else { meandirwidth = (int)avd_get_int(fileset->fs_dirwidth); fileset->fs_meanwidth = (double)meandirwidth; } /* * Input params are: * # of files * ave # of files per dir * max size of dir * # ave size of file * max size of file */ fileset->fs_meandepth = log(entries+leafdirs) / log(meandirwidth); /* Has a random variable been supplied for dirdepth? */ if (fileset->fs_dirdepthrv) { /* yes, so set the random variable's mean value to meandepth */ fileset->fs_dirdepthrv->avd_val.randptr->rnd_dbl_mean = fileset->fs_meandepth; } if ((ret = fileset_populate_subdir(fileset, NULL, 1, 0)) != 0) return (ret); exists: if (fileset->fs_attrs & FILESET_IS_FILE) { filebench_log(LOG_VERBOSE, "File %s: %.3lfMB", avd_get_str(fileset->fs_name), (double)fileset->fs_bytes / 1024UL / 1024UL); } else { filebench_log(LOG_INFO, "%s populated: %llu files, " "avg. dir. width = %d, avg. dir. depth = %.1lf, " "%llu leafdirs, %.3lfMB total size", avd_get_str(fileset->fs_name), entries, meandirwidth, fileset->fs_meandepth, leafdirs, (double)fileset->fs_bytes / 1024UL / 1024UL); } return FILEBENCH_OK; } /* * Allocates a fileset instance, initializes fileset_dirgamma and * fileset_sizegamma default values, and sets the fileset name to the * supplied name string. Puts the allocated fileset on the * master fileset list and returns a pointer to it. * * This routine implements the 'define fileset' calls found in a .f * workload, such as in the following example: * define fileset name=drew4ever, entries=$nfiles */ fileset_t * fileset_define(avd_t name, avd_t path) { fileset_t *fileset; fileset = (fileset_t *)ipc_malloc(FILEBENCH_FILESET); if (!fileset) { filebench_log(LOG_ERROR, "can't allocate fileset %s", avd_get_str(name)); return NULL; } filebench_log(LOG_DEBUG_IMPL, "defining file[set] %s", avd_get_str(name)); fileset->fs_name = name; fileset->fs_path = path; /* Add fileset to global list */ (void)ipc_mutex_lock(&filebench_shm->shm_fileset_lock); if (filebench_shm->shm_filesetlist == NULL) { filebench_shm->shm_filesetlist = fileset; fileset->fs_next = NULL; } else { fileset->fs_next = filebench_shm->shm_filesetlist; filebench_shm->shm_filesetlist = fileset; } (void)ipc_mutex_unlock(&filebench_shm->shm_fileset_lock); return fileset; } /* * checks to see if the path/name pair points to a raw device. If * so it sets the raw device flag (FILESET_IS_RAW_DEV) and returns 1. * If RAW is not defined, or it is not a raw device, it clears the * raw device flag and returns 0. */ int fileset_checkraw(fileset_t *fileset) { char path[MAXPATHLEN]; struct stat64 sb; char *pathname; char *setname; fileset->fs_attrs &= (~FILESET_IS_RAW_DEV); if ((pathname = avd_get_str(fileset->fs_path)) == NULL) { filebench_log(LOG_ERROR, "%s path not set", fileset_entity_name(fileset)); filebench_shutdown(1); } if ((setname = avd_get_str(fileset->fs_name)) == NULL) { filebench_log(LOG_ERROR, "%s name not set", fileset_entity_name(fileset)); filebench_shutdown(1); } (void) fb_strlcpy(path, pathname, MAXPATHLEN); (void) fb_strlcat(path, "/", MAXPATHLEN); (void) fb_strlcat(path, setname, MAXPATHLEN); if ((stat64(path, &sb) == 0) && ((sb.st_mode & S_IFMT) == S_IFBLK)) { fileset->fs_attrs |= FILESET_IS_RAW_DEV; if (!(fileset->fs_attrs & FILESET_IS_FILE)) { filebench_log(LOG_ERROR, "WARNING Fileset %s/%s Cannot be RAW device", avd_get_str(fileset->fs_path), avd_get_str(fileset->fs_name)); filebench_shutdown(1); } return 1; } return 0; } /* * Calls fileset_populate() and fileset_create() for all filesets on the * fileset list. Returns when any of fileset_populate() or fileset_create() * fail. */ int fileset_createsets() { fileset_t *list; int ret = 0; if (filecreate_done) { /* XXX: what if user defines a fileset after create? * IMHO, we should have filecreate_done flag per fileset */ filebench_log(LOG_INFO, "Attempting to create fileset more than once, ignoring"); return 0; } filecreate_done = 1; /* Set up for possible parallel pre-allocation */ filebench_shm->shm_fsparalloc_count = 0; (void) pthread_cond_init(&filebench_shm->shm_fsparalloc_cv, ipc_condattr()); filebench_log(LOG_INFO, "Populating and pre-allocating filesets"); list = filebench_shm->shm_filesetlist; while (list) { /* Verify fileset parameters are valid */ if ((avd_get_int(list->fs_entries) == 0) && (avd_get_int(list->fs_leafdirs) == 0)) { filebench_log(LOG_ERROR, "Fileset has no files or leafdirs"); } if (list->fs_dirdepthrv && !AVD_IS_RANDOM(list->fs_dirdepthrv)) { filebench_log(LOG_ERROR, "Define fileset: dirdepthrv must be random var"); filebench_shutdown(1); } if (AVD_IS_RANDOM(list->fs_dirgamma)) { filebench_log(LOG_ERROR, "Define fileset: dirgamma attr cannot be random"); filebench_shutdown(1); } /* check for raw files */ if (fileset_checkraw(list)) { filebench_log(LOG_INFO, "File %s/%s is a RAW device", avd_get_str(list->fs_path), avd_get_str(list->fs_name)); list = list->fs_next; continue; } ret = fileset_populate(list); if (ret) return ret; ret = fileset_create(list); if (ret) return ret; list = list->fs_next; } /* wait for allocation threads to finish */ filebench_log(LOG_INFO, "Waiting for pre-allocation to finish " "(in case of a parallel pre-allocation)"); (void) pthread_mutex_lock(&filebench_shm->shm_fsparalloc_lock); while (filebench_shm->shm_fsparalloc_count > 0) (void) pthread_cond_wait( &filebench_shm->shm_fsparalloc_cv, &filebench_shm->shm_fsparalloc_lock); (void) pthread_mutex_unlock(&filebench_shm->shm_fsparalloc_lock); filebench_log(LOG_INFO, "Population and pre-allocation of filesets completed"); if (filebench_shm->shm_fsparalloc_count < 0) return (FILEBENCH_ERROR); return 0; } /* * Searches through the master fileset list for the named fileset. * If found, returns pointer to same, otherwise returns NULL. */ fileset_t * fileset_find(char *name) { fileset_t *fileset = filebench_shm->shm_filesetlist; (void) ipc_mutex_lock(&filebench_shm->shm_fileset_lock); while (fileset) { if (strcmp(name, avd_get_str(fileset->fs_name)) == 0) { (void) ipc_mutex_unlock( &filebench_shm->shm_fileset_lock); return (fileset); } fileset = fileset->fs_next; } (void) ipc_mutex_unlock(&filebench_shm->shm_fileset_lock); return (NULL); } /* * Iterates over all the file sets in the filesetlist, * executing the supplied command "*cmd()" on them. Also * indicates to the executed command if it is the first * time the command has been executed since the current * call to fileset_iter. */ int fileset_iter(int (*cmd)(fileset_t *fileset, int first)) { fileset_t *fileset = filebench_shm->shm_filesetlist; int count = 0; (void) ipc_mutex_lock(&filebench_shm->shm_fileset_lock); while (fileset) { if (cmd(fileset, count == 0) == FILEBENCH_ERROR) { (void) ipc_mutex_unlock( &filebench_shm->shm_fileset_lock); return (FILEBENCH_ERROR); } fileset = fileset->fs_next; count++; } (void) ipc_mutex_unlock(&filebench_shm->shm_fileset_lock); return (FILEBENCH_OK); } /* * Prints information to the filebench log about the file * object. Also prints a header on the first call. */ int fileset_print(fileset_t *fileset, int first) { int pathlength; char *fileset_path; char *fileset_name; static char pad[] = " "; /* 30 spaces */ if ((fileset_path = avd_get_str(fileset->fs_path)) == NULL) { filebench_log(LOG_ERROR, "%s path not set", fileset_entity_name(fileset)); return (FILEBENCH_ERROR); } if ((fileset_name = avd_get_str(fileset->fs_name)) == NULL) { filebench_log(LOG_ERROR, "%s name not set", fileset_entity_name(fileset)); return (FILEBENCH_ERROR); } pathlength = strlen(fileset_path) + strlen(fileset_name); if (pathlength > 29) pathlength = 29; if (first) { filebench_log(LOG_INFO, "File or Fileset name%20s%12s%10s", "file size", "dir width", "entries"); } if (fileset->fs_attrs & FILESET_IS_FILE) { if (fileset->fs_attrs & FILESET_IS_RAW_DEV) { filebench_log(LOG_INFO, "%s/%s%s (Raw Device)", fileset_path, fileset_name, &pad[pathlength]); } else { filebench_log(LOG_INFO, "%s/%s%s%9llu (Single File)", fileset_path, fileset_name, &pad[pathlength], (u_longlong_t)avd_get_int(fileset->fs_size)); } } else { filebench_log(LOG_INFO, "%s/%s%s%9llu%12llu%10llu", fileset_path, fileset_name, &pad[pathlength], (u_longlong_t)avd_get_int(fileset->fs_size), (u_longlong_t)avd_get_int(fileset->fs_dirwidth), (u_longlong_t)fileset->fs_constentries); } return (FILEBENCH_OK); }
53,805
26.606978
96
c
filebench
filebench-master/fileset.h
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _FB_FILESET_H #define _FB_FILESET_H #include "filebench.h" #define FILE_ALLOC_BLOCK (off64_t)(1024 * 1024) #define FSE_MAXTID 16384 #define FSE_MAXPATHLEN 16 #define FSE_TYPE_FILE 0x00 #define FSE_TYPE_DIR 0x01 #define FSE_TYPE_LEAFDIR 0x02 #define FSE_TYPE_MASK 0x03 #define FSE_FREE 0x04 #define FSE_EXISTS 0x08 #define FSE_BUSY 0x10 #define FSE_REUSING 0x20 #define FSE_THRD_WAITNG 0x40 typedef struct filesetentry { struct filesetentry *fse_next; /* master list of entries */ struct filesetentry *fse_parent; /* link to directory */ avl_node_t fse_link; /* links in avl btree, prot. */ /* by fs_pick_lock */ uint_t fse_index; /* file order number */ struct filesetentry *fse_nextoftype; /* List of specific fse */ struct fileset *fse_fileset; /* Parent fileset */ char *fse_path; int fse_depth; off64_t fse_size; int fse_open_cnt; /* protected by fs_pick_lock */ int fse_flags; /* protected by fs_pick_lock */ } filesetentry_t; #define FSE_OFFSETOF(f) ((size_t)(&(((filesetentry_t *)0)->f))) /* type of fileset entry to obtain */ #define FILESET_PICKFILE 0x00 /* Pick a file from the set */ #define FILESET_PICKDIR 0x01 /* Pick a directory */ #define FILESET_PICKLEAFDIR 0x02 /* Pick a leaf directory */ #define FILESET_PICKMASK 0x03 /* Pick type mask */ /* other pick flags */ #define FILESET_PICKUNIQUE 0x04 /* Pick a unique file or leafdir from the */ /* fileset until empty */ #define FILESET_PICKEXISTS 0x10 /* Pick an existing file */ #define FILESET_PICKNOEXIST 0x20 /* Pick a file that doesn't exist */ #define FILESET_PICKBYINDEX 0x40 /* use supplied index number to select file */ #define FILESET_PICKFREE FILESET_PICKUNIQUE /* fileset attributes */ #define FILESET_IS_RAW_DEV 0x01 /* fileset is a raw device */ #define FILESET_IS_FILE 0x02 /* Fileset is emulating a single file */ typedef struct fileset { struct fileset *fs_next; /* Next in list */ avd_t fs_name; /* Name */ avd_t fs_path; /* Pathname prefix in fileset */ avd_t fs_entries; /* Number of entries attr */ /* (possibly random) */ fbint_t fs_constentries; /* Constant version of enties attr */ avd_t fs_leafdirs; /* Number of leaf directories attr */ /* (possibly random) */ fbint_t fs_constleafdirs; /* Constant version of leafdirs */ /* attr */ avd_t fs_preallocpercent; /* Prealloc size */ int fs_attrs; /* Attributes */ avd_t fs_dirwidth; /* Explicit or mean for distribution */ avd_t fs_dirdepthrv; /* random variable for dir depth */ avd_t fs_size; /* Explicit or mean for distribution */ avd_t fs_dirgamma; /* Dirdepth Gamma distribution */ /* (* 1000) defaults to 1500, set */ /* to 0 for explicit depth */ avd_t fs_create; /* Attr */ avd_t fs_paralloc; /* Attr */ avd_t fs_reuse; /* Attr */ avd_t fs_readonly; /* Attr */ avd_t fs_writeonly; /* Attr */ avd_t fs_trust_tree; /* Attr */ double fs_meandepth; /* Computed mean depth */ double fs_meanwidth; /* Specified mean dir width */ int fs_realfiles; /* Actual files */ int fs_realleafdirs; /* Actual explicit leaf directories */ off64_t fs_bytes; /* Total space consumed by files */ int64_t fs_idle_files; /* number of files NOT busy */ pthread_cond_t fs_idle_files_cv; /* idle files condition variable */ int64_t fs_idle_dirs; /* number of dirs NOT busy */ pthread_cond_t fs_idle_dirs_cv; /* idle dirs condition variable */ int64_t fs_idle_leafdirs; /* number of dirs NOT busy */ pthread_cond_t fs_idle_leafdirs_cv; /* idle dirs condition variable */ pthread_mutex_t fs_pick_lock; /* per fileset "pick" function lock */ pthread_cond_t fs_thrd_wait_cv; /* per fileset file busy wait cv */ avl_tree_t fs_free_files; /* btree of free files */ avl_tree_t fs_exist_files; /* btree of files on device */ avl_tree_t fs_noex_files; /* btree of files NOT on device */ avl_tree_t fs_dirs; /* btree of internal dirs */ avl_tree_t fs_free_leaf_dirs; /* btree of free leaf dirs */ avl_tree_t fs_exist_leaf_dirs; /* btree of leaf dirs on device */ avl_tree_t fs_noex_leaf_dirs; /* btree of leaf dirs NOT */ /* currently on device */ filesetentry_t *fs_filelist; /* List of files */ uint_t fs_file_exrotor[FSE_MAXTID]; /* next file to */ /* select */ uint_t fs_file_nerotor; /* next non existent file */ /* to select for createfile */ filesetentry_t *fs_dirlist; /* List of directories */ uint_t fs_dirrotor; /* index of next directory to select */ filesetentry_t *fs_leafdirlist; /* List of leaf directories */ uint_t fs_leafdir_exrotor; /* Ptr to next existing leaf */ /* directory to select */ uint_t fs_leafdir_nerotor; /* Ptr to next non-existing */ int *fs_filehistop; /* Ptr to access histogram */ pthread_mutex_t fs_histo_lock; /* lock for incr of histo */ } fileset_t; int fileset_createsets(); void fileset_delete_all_filesets(void); int fileset_openfile(fb_fdesc_t *fd, fileset_t *fileset, filesetentry_t *entry, int flag, int mode, int attrs); fileset_t *fileset_define(avd_t name, avd_t path); fileset_t *fileset_find(char *name); filesetentry_t *fileset_pick(fileset_t *fileset, int flags, int tid, int index); char *fileset_resolvepath(filesetentry_t *entry); int fileset_iter(int (*cmd)(fileset_t *fileset, int first)); int fileset_print(fileset_t *fileset, int first); void fileset_unbusy(filesetentry_t *entry, int update_exist, int new_exist_val, int open_cnt_incr); int fileset_dump_histo(fileset_t *fileset, int first); void fileset_attach_all_histos(void); #endif /* _FB_FILESET_H */
6,504
38.907975
79
h
filebench
filebench-master/flag.h
#ifndef _FB_FLAG_H #define _FB_FLAG_H typedef volatile int flag_t; static inline void clear_flag(flag_t *flag) { *flag = 0; } static inline void set_flag(flag_t *flag) { *flag = 1; } static inline int query_flag(flag_t *flag) { return (*flag) != 0; } static inline void wait_flag(flag_t *flag) { while (!query_flag(flag)) ; /* Do nothing */ } #endif /* _FB_FLAG_H */
380
12.137931
43
h
filebench
filebench-master/flowop.c
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #include "config.h" #ifdef HAVE_LWPS #include <sys/lwp.h> #endif #include <fcntl.h> #include "filebench.h" #include "flowop.h" #include "stats.h" #include "ioprio.h" static flowop_t *flowop_define_common(threadflow_t *threadflow, char *name, flowop_t *inherit, flowop_t **flowoplist_hdp, int instance, int type); static int flowop_composite(threadflow_t *threadflow, flowop_t *flowop); static int flowop_composite_init(flowop_t *flowop); static void flowop_composite_destruct(flowop_t *flowop); /* * A collection of flowop support functions. The actual code that * implements the various flowops is in flowop_library.c. * * Routines for defining, creating, initializing and destroying * flowops, cyclically invoking the flowops on each threadflow's flowop * list, collecting statistics about flowop execution, and other * housekeeping duties are included in this file. * * User Defined Composite Flowops * The ability to define new flowops as lists of built-in or previously * defined flowops has been added to Filebench. In a sense they are like * in-line subroutines, which can have default attributes set at definition * time and passed arguments at invocation time. Like other flowops (and * unlike conventional subroutines) you can invoke them with an iteration * count (the "iter" attribute), and they will loop through their associated * list of flowops for "iter" number of times each time they are encountered * in the thread or outer composite flowop which invokes them. * * Composite flowops are created with a "define" command, are given a name, * optional default attributes, and local variable definitions on the * "define" command line, followed by a brace enclosed list of flowops * to execute. The enclosed flowops may include attributes that reference * the local variables, as well as constants and global variables. * * Composite flowops are used pretty much like regular flowops, but you can * also set local variables to constants or global variables ($local_var = * [$var | $random_var | string | boolean | integer | double]) as part of * the invocation. Thus each invocation can pass customized values to its * inner flowops, greatly increasing their generality. * * All flowops are placed on a global, singly linked list, with fo_next * being the link pointer for this list. The are also placed on a private * list for the thread or composite flowop they are part of. The tf_thrd_fops * pointer in the thread will point to the list of top level flowops in the * thread, which are linked together by fo_exec_next. If any of these flowops * are composite flowops, they will have a list of second level flowops rooted * at the composite flowop's fo_comp_fops pointer. So, there is one big list * of all flowops, and an n-arry tree of threads, composite flowops, and * flowops, with composite flowops being the branch nodes in the tree. * * To illustrate, if we have three first level flowops, the first of which is * a composite flowop consisting of two other flowops, we get: * * Thread->tf_thrd_fops -> flowop->fo_exec_next -> flowop->fo_exec_next * flowop->fo_comp_fops | * | V * | flowop->fo_exec_next * | * V * flowop->fo_exec_next -> flowop->fo_exec_next * * And all five flowops (plus others from any other threads) are on a global * list linked with fo_next. */ /* * Prints the name and instance number of each flowop in * the supplied list to the filebench log. */ int flowop_printlist(flowop_t *list) { flowop_t *flowop = list; while (flowop) { filebench_log(LOG_DEBUG_IMPL, "flowop-list %s-%d", flowop->fo_name, flowop->fo_instance); flowop = flowop->fo_exec_next; } return (0); } /* * Prints the name and instance number of all flowops on * the master flowop list to the console and the filebench log. */ void flowop_printall(void) { flowop_t *flowop = filebench_shm->shm_flowoplist; while (flowop) { filebench_log(LOG_INFO, "flowop-list %s-%d", flowop->fo_name, flowop->fo_instance); flowop = flowop->fo_next; } } #define TIMESPEC_TO_HRTIME(s, e) (((e.tv_sec - s.tv_sec) * 1000000000LL) + \ (e.tv_nsec - s.tv_nsec)) /* * Puts current high-resolution time in start time entry for threadflow. */ void flowop_beginop(threadflow_t *threadflow, flowop_t *flowop) { /* Start of op for this thread */ threadflow->tf_stime = gethrtime(); } struct flowstats controlstats; pthread_mutex_t controlstats_lock; static int controlstats_zeroed = 0; static void flowop_populate_distribution(flowop_t *flowop, unsigned long long ll_delay) { unsigned int i; unsigned long long iii; iii = 1; for (i = 0; i < OSPROF_BUCKET_NUMBER; i++) { if (ll_delay < iii) break; iii <<= 1; } flowop->fo_stats.fs_distribution[i]++; } /* * Updates flowop's latency statistics, using saved start * time and current high resolution time. Updates flowop's * io count and transferred bytes statistics. Also updates * threadflow's and flowop's cumulative read or write byte * and io count statistics. */ void flowop_endop(threadflow_t *threadflow, flowop_t *flowop, int64_t bytes) { unsigned long long ll_delay; ll_delay = (gethrtime() - threadflow->tf_stime); /* setting minimum and maximum latencies for this flowop */ if (!flowop->fo_stats.fs_minlat || ll_delay < flowop->fo_stats.fs_minlat) flowop->fo_stats.fs_minlat = ll_delay; if (ll_delay > flowop->fo_stats.fs_maxlat) flowop->fo_stats.fs_maxlat = ll_delay; flowop->fo_stats.fs_total_lat += ll_delay; flowop->fo_stats.fs_count++; flowop->fo_stats.fs_bytes += bytes; (void) ipc_mutex_lock(&controlstats_lock); if ((flowop->fo_type & FLOW_TYPE_IO) || (flowop->fo_type & FLOW_TYPE_AIO)) { controlstats.fs_count++; controlstats.fs_bytes += bytes; } if (flowop->fo_attrs & FLOW_ATTR_READ) { threadflow->tf_stats.fs_rbytes += bytes; threadflow->tf_stats.fs_rcount++; flowop->fo_stats.fs_rcount++; controlstats.fs_rbytes += bytes; controlstats.fs_rcount++; } else if (flowop->fo_attrs & FLOW_ATTR_WRITE) { threadflow->tf_stats.fs_wbytes += bytes; threadflow->tf_stats.fs_wcount++; flowop->fo_stats.fs_wcount++; controlstats.fs_wbytes += bytes; controlstats.fs_wcount++; } if (filebench_shm->lathist_enabled) flowop_populate_distribution(flowop, ll_delay); (void) ipc_mutex_unlock(&controlstats_lock); } /* * Calls the flowop's initialization function, pointed to by * flowop->fo_init. */ static int flowop_initflow(flowop_t *flowop) { /* * save static copies of two items, in case they are supplied * from random variables */ if (flowop->fo_value) flowop->fo_constvalue = avd_get_int(flowop->fo_value); if (flowop->fo_wss) flowop->fo_constwss = avd_get_int(flowop->fo_wss); if ((*flowop->fo_init)(flowop) < 0) { filebench_log(LOG_ERROR, "flowop %s-%d init failed", flowop->fo_name, flowop->fo_instance); return (-1); } return (0); } static int flowop_create_runtime_flowops(threadflow_t *threadflow, flowop_t **ops_list_ptr) { flowop_t *flowop = *ops_list_ptr; char *name; while (flowop) { flowop_t *newflowop; if (flowop == *ops_list_ptr) *ops_list_ptr = NULL; newflowop = flowop_define_common(threadflow, flowop->fo_name, flowop, ops_list_ptr, 1, 0); if (newflowop == NULL) return (FILEBENCH_ERROR); /* check for fo_filename attribute, and resolve if present */ if (flowop->fo_filename) { name = avd_get_str(flowop->fo_filename); newflowop->fo_fileset = fileset_find(name); if (newflowop->fo_fileset == NULL) { filebench_log(LOG_ERROR, "flowop %s: file %s not found", newflowop->fo_name, name); filebench_shutdown(1); } } if (flowop_initflow(newflowop) < 0) { filebench_log(LOG_ERROR, "Flowop init of %s failed", newflowop->fo_name); } flowop = flowop->fo_exec_next; } return (FILEBENCH_OK); } /* * Calls the flowop's destruct function, pointed to by * flowop->fo_destruct. */ static void flowop_destructflow(flowop_t *flowop) { (*flowop->fo_destruct)(flowop); } /* * call the destruct funtions of all the threadflow's flowops, * if it is still flagged as "running". */ void flowop_destruct_all_flows(threadflow_t *threadflow) { flowop_t *flowop; /* wait a moment to give other threads a chance to stop too */ (void) sleep(1); (void) ipc_mutex_lock(&threadflow->tf_lock); /* prepare to call destruct flow routines, if necessary */ if (threadflow->tf_running == 0) { /* allready destroyed */ (void) ipc_mutex_unlock(&threadflow->tf_lock); return; } flowop = threadflow->tf_thrd_fops; threadflow->tf_running = 0; (void) ipc_mutex_unlock(&threadflow->tf_lock); while (flowop) { flowop_destructflow(flowop); flowop = flowop->fo_exec_next; } } /* * The final initialization and main execution loop for the * worker threads. Sets threadflow and flowop start times, * waits for all process to start, then creates the runtime * flowops from those defined by the F language workload * script. It does some more initialization, then enters a * loop to repeatedly execute the flowops on the flowop list * until an abort condition is detected, at which time it exits. * This is the starting routine for the new worker thread * created by threadflow_createthread(), and is not currently * called from anywhere else. */ void flowop_start(threadflow_t *threadflow) { flowop_t *flowop; size_t memsize; int ret = FILEBENCH_OK; set_thread_ioprio(threadflow); (void) ipc_mutex_lock(&controlstats_lock); if (!controlstats_zeroed) { (void) memset(&controlstats, 0, sizeof (controlstats)); controlstats_zeroed = 1; } (void) ipc_mutex_unlock(&controlstats_lock); flowop = threadflow->tf_thrd_fops; /* Hold the flowop find lock as reader to prevent lookups */ (void) pthread_rwlock_rdlock(&filebench_shm->shm_flowop_find_lock); /* Create the runtime flowops from those defined by the script */ (void) ipc_mutex_lock(&filebench_shm->shm_flowop_lock); if (flowop_create_runtime_flowops(threadflow, &threadflow->tf_thrd_fops) != FILEBENCH_OK) { (void) ipc_mutex_unlock(&filebench_shm->shm_flowop_lock); filebench_shutdown(1); return; } (void) ipc_mutex_unlock(&filebench_shm->shm_flowop_lock); /* Release the find lock as reader to allow lookups */ (void) pthread_rwlock_unlock(&filebench_shm->shm_flowop_find_lock); /* Set to the start of the new flowop list */ flowop = threadflow->tf_thrd_fops; #ifdef HAVE_LWPS filebench_log(LOG_DEBUG_SCRIPT, "Thread %zx (%d) started", threadflow, _lwp_self()); #endif /* * Now we set tf_running flag to indicate to the main process * that the worker thread is running. However, the thread is * still not executing the workload, as it is blocked by the * shm_run_lock. Main thread will release this lock when all * threads set their tf_running flag to 1. */ threadflow->tf_abort = 0; threadflow->tf_running = 1; /* * Block until all processes have started, acting like * a barrier. The original filebench process initially * holds the run_lock as a reader, preventing any of the * threads from obtaining the writer lock, and hence * passing this point. Once all processes and threads * have been created, the original process unlocks * run_lock, allowing each waiting thread to lock * and then immediately unlock it, then begin running. */ (void) pthread_rwlock_wrlock(&filebench_shm->shm_run_lock); (void) pthread_rwlock_unlock(&filebench_shm->shm_run_lock); memsize = (size_t)threadflow->tf_constmemsize; /* * Alloc from ISM, which should have been created before the main process * wakes up the current process by releasing shm_run_lock. */ if (threadflow->tf_attrs & THREADFLOW_USEISM) { threadflow->tf_mem = ipc_ismmalloc(memsize); } else { threadflow->tf_mem = malloc(memsize); } (void) memset(threadflow->tf_mem, 0, memsize); filebench_log(LOG_DEBUG_SCRIPT, "Thread allocated %d bytes", memsize); /* Main filebench worker loop */ while (ret == FILEBENCH_OK) { int i, count; /* Abort if asked */ if (threadflow->tf_abort || filebench_shm->shm_f_abort) break; /* Be quiet while stats are gathered */ if (filebench_shm->shm_bequiet) { (void) sleep(1); continue; } /* Take it easy until everyone is ready to go */ if (!filebench_shm->shm_procs_running) { (void) sleep(1); continue; } if (flowop == NULL) { filebench_log(LOG_ERROR, "flowop_read null flowop"); return; } /* Execute the flowop for fo_iters times */ count = (int)avd_get_int(flowop->fo_iters); for (i = 0; i < count; i++) { filebench_log(LOG_DEBUG_SCRIPT, "%s: executing flowop " "%s-%d", threadflow->tf_name, flowop->fo_name, flowop->fo_instance); ret = (*flowop->fo_func)(threadflow, flowop); /* * Return value FILEBENCH_ERROR means "flowop * failed, stop the filebench run" */ if (ret == FILEBENCH_ERROR) { filebench_log(LOG_ERROR, "%s-%d: flowop %s-%d failed", threadflow->tf_name, threadflow->tf_instance, flowop->fo_name, flowop->fo_instance); (void) ipc_mutex_lock(&threadflow->tf_lock); threadflow->tf_abort = 1; filebench_shm->shm_f_abort = FILEBENCH_ABORT_ERROR; (void) ipc_mutex_unlock(&threadflow->tf_lock); break; } /* * Return value of FILEBENCH_NORSC means "stop * the filebench run" if in "end on no work mode", * otherwise it indicates an error */ if (ret == FILEBENCH_NORSC) { (void) ipc_mutex_lock(&threadflow->tf_lock); threadflow->tf_abort = FILEBENCH_DONE; if (filebench_shm->shm_rmode == FILEBENCH_MODE_Q1STDONE) { filebench_shm->shm_f_abort = FILEBENCH_ABORT_RSRC; } else if (filebench_shm->shm_rmode != FILEBENCH_MODE_QALLDONE) { filebench_log(LOG_ERROR1, "WARNING! Run stopped early:\n " " flowop %s-%d could " "not obtain a file. Please\n " " reduce runtime, " "increase fileset entries " "($nfiles), or switch modes.", flowop->fo_name, flowop->fo_instance); filebench_shm->shm_f_abort = FILEBENCH_ABORT_ERROR; } (void) ipc_mutex_unlock(&threadflow->tf_lock); break; } /* * Return value of FILEBENCH_DONE means "stop * the filebench run without error" */ if (ret == FILEBENCH_DONE) { (void) ipc_mutex_lock(&threadflow->tf_lock); threadflow->tf_abort = FILEBENCH_DONE; filebench_shm->shm_f_abort = FILEBENCH_ABORT_DONE; (void) ipc_mutex_unlock(&threadflow->tf_lock); break; } /* * If we get here and the return is something other * than FILEBENCH_OK, it means a spurious code * was returned, so treat as major error. This * probably indicates a bug in the flowop. */ if (ret != FILEBENCH_OK) { filebench_log(LOG_ERROR, "Flowop %s unexpected return value = %d\n", flowop->fo_name, ret); filebench_shm->shm_f_abort = FILEBENCH_ABORT_ERROR; break; } } /* advance to next flowop */ flowop = flowop->fo_exec_next; /* but if at end of list, start over from the beginning */ if (flowop == NULL) { flowop = threadflow->tf_thrd_fops; threadflow->tf_stats.fs_count++; } } #ifdef HAVE_LWPS filebench_log(LOG_DEBUG_SCRIPT, "Thread %d exiting", _lwp_self()); #endif /* Tell flowops to destroy locally acquired state */ flowop_destruct_all_flows(threadflow); pthread_exit(&threadflow->tf_abort); } /* * For master mode we add flowops from the generic library, flowops that are * file system specific, and adjust the vector of functions used by the * generic library. For worker mode we only need to adjust the vector. */ void flowop_init(int ismaster) { if (ismaster) { (void) pthread_mutex_init(&controlstats_lock, ipc_mutexattr(IPC_MUTEX_NORMAL)); flowoplib_flowinit(); } switch (filebench_shm->shm_filesys_type) { case LOCAL_FS_PLUG: if (ismaster) fb_lfs_newflowops(); fb_lfs_funcvecinit(); break; case NFS3_PLUG: case NFS4_PLUG: case CIFS_PLUG: break; } } /* * Delete the designated flowop from the thread's flowop list. */ static void flowop_delete(flowop_t **flowoplist, flowop_t *flowop) { flowop_t *entry = *flowoplist; int found = 0; filebench_log(LOG_DEBUG_IMPL, "Deleting flowop (%s-%d)", flowop->fo_name, flowop->fo_instance); /* Delete from thread's flowop list */ if (flowop == *flowoplist) { /* First on list */ *flowoplist = flowop->fo_exec_next; filebench_log(LOG_DEBUG_IMPL, "Delete0 flowop: (%s-%d)", flowop->fo_name, flowop->fo_instance); } else { while (entry->fo_exec_next) { filebench_log(LOG_DEBUG_IMPL, "Delete0 flowop: (%s-%d) == (%s-%d)", entry->fo_exec_next->fo_name, entry->fo_exec_next->fo_instance, flowop->fo_name, flowop->fo_instance); if (flowop == entry->fo_exec_next) { /* Delete */ filebench_log(LOG_DEBUG_IMPL, "Deleted0 flowop: (%s-%d)", entry->fo_exec_next->fo_name, entry->fo_exec_next->fo_instance); entry->fo_exec_next = entry->fo_exec_next->fo_exec_next; break; } entry = entry->fo_exec_next; } } /* Delete from global list */ entry = filebench_shm->shm_flowoplist; if (flowop == filebench_shm->shm_flowoplist) { /* First on list */ filebench_shm->shm_flowoplist = flowop->fo_next; found = 1; } else { while (entry->fo_next) { filebench_log(LOG_DEBUG_IMPL, "Delete flowop: (%s-%d) == (%s-%d)", entry->fo_next->fo_name, entry->fo_next->fo_instance, flowop->fo_name, flowop->fo_instance); if (flowop == entry->fo_next) { /* Delete */ entry->fo_next = entry->fo_next->fo_next; found = 1; break; } entry = entry->fo_next; } } if (found) { filebench_log(LOG_DEBUG_IMPL, "Deleted flowop: (%s-%d)", flowop->fo_name, flowop->fo_instance); ipc_free(FILEBENCH_FLOWOP, (char *)flowop); } else { filebench_log(LOG_DEBUG_IMPL, "Flowop %s-%d not found!", flowop->fo_name, flowop->fo_instance); } } /* * Deletes all the flowops from a flowop list. */ void flowop_delete_all(flowop_t **flowoplist) { flowop_t *flowop = *flowoplist; flowop_t *next_flowop; (void) ipc_mutex_lock(&filebench_shm->shm_flowop_lock); while (flowop) { filebench_log(LOG_DEBUG_IMPL, "Deleting flowop (%s-%d)", flowop->fo_name, flowop->fo_instance); if (flowop->fo_instance && (flowop->fo_instance == FLOW_MASTER)) { flowop = flowop->fo_exec_next; continue; } next_flowop = flowop->fo_exec_next; flowop_delete(flowoplist, flowop); flowop = next_flowop; } (void) ipc_mutex_unlock(&filebench_shm->shm_flowop_lock); } /* * Allocates a flowop entity and initializes it with inherited * contents from the "inherit" flowop, if it is supplied, or * with zeros otherwise. In either case the fo_next and fo_exec_next * pointers are set to NULL, and fo_thread is set to point to * the owning threadflow. The initialized flowop is placed at * the head of the global flowop list, and also placed on the * tail of the supplied local flowop list, which will either * be a threadflow's tf_thrd_fops list or a composite flowop's * fo_comp_fops list. The routine locks the flowop's fo_lock and * leaves it held on return. If successful, it returns a pointer * to the allocated and initialized flowop, otherwise it returns NULL. * * filebench_shm->shm_flowop_lock must be held by caller. */ static flowop_t * flowop_define_common(threadflow_t *threadflow, char *name, flowop_t *inherit, flowop_t **flowoplist_hdp, int instance, int type) { flowop_t *flowop; if (name == NULL) return (NULL); if ((flowop = (flowop_t *)ipc_malloc(FILEBENCH_FLOWOP)) == NULL) { filebench_log(LOG_ERROR, "flowop_define: Can't malloc flowop"); return (NULL); } filebench_log(LOG_DEBUG_IMPL, "defining flowops %s-%d, addr %zx", name, instance, flowop); if (flowop == NULL) return (NULL); if (inherit) { (void) memcpy(flowop, inherit, sizeof (flowop_t)); (void) pthread_mutex_init(&flowop->fo_lock, ipc_mutexattr(IPC_MUTEX_PRI_ROB)); (void) ipc_mutex_lock(&flowop->fo_lock); flowop->fo_next = NULL; flowop->fo_exec_next = NULL; filebench_log(LOG_DEBUG_IMPL, "flowop %s-%d calling init", name, instance); } else { (void) memset(flowop, 0, sizeof (flowop_t)); flowop->fo_iters = avd_int_alloc(1); flowop->fo_type = type; (void) pthread_mutex_init(&flowop->fo_lock, ipc_mutexattr(IPC_MUTEX_PRI_ROB)); (void) ipc_mutex_lock(&flowop->fo_lock); } /* Create backpointer to thread */ flowop->fo_thread = threadflow; /* Add flowop to global list */ if (filebench_shm->shm_flowoplist == NULL) { filebench_shm->shm_flowoplist = flowop; flowop->fo_next = NULL; } else { flowop->fo_next = filebench_shm->shm_flowoplist; filebench_shm->shm_flowoplist = flowop; } (void) strcpy(flowop->fo_name, name); flowop->fo_instance = instance; if (flowoplist_hdp == NULL) return (flowop); /* Add flowop to thread op list */ if (*flowoplist_hdp == NULL) { *flowoplist_hdp = flowop; flowop->fo_exec_next = NULL; } else { flowop_t *flowend; /* Find the end of the thread list */ flowend = *flowoplist_hdp; while (flowend->fo_exec_next != NULL) flowend = flowend->fo_exec_next; flowend->fo_exec_next = flowop; flowop->fo_exec_next = NULL; } return (flowop); } /* * Calls flowop_define_common() to allocate and initialize a * flowop, and holds the shared flowop_lock during the call. * It releases the created flowop's fo_lock when done. */ flowop_t * flowop_define(threadflow_t *threadflow, char *name, flowop_t *inherit, flowop_t **flowoplist_hdp, int instance, int type) { flowop_t *flowop; (void) ipc_mutex_lock(&filebench_shm->shm_flowop_lock); flowop = flowop_define_common(threadflow, name, inherit, flowoplist_hdp, instance, type); (void) ipc_mutex_unlock(&filebench_shm->shm_flowop_lock); if (flowop == NULL) return (NULL); (void) ipc_mutex_unlock(&flowop->fo_lock); return (flowop); } /* * Calls flowop_define_common() to allocate and initialize a * composite flowop, and holds the shared flowop_lock during the call. * It releases the created flowop's fo_lock when done. */ flowop_t * flowop_new_composite_define(char *name) { flowop_t *flowop; (void) ipc_mutex_lock(&filebench_shm->shm_flowop_lock); flowop = flowop_define_common(NULL, name, NULL, NULL, 0, FLOW_TYPE_COMPOSITE); (void) ipc_mutex_unlock(&filebench_shm->shm_flowop_lock); if (flowop == NULL) return (NULL); flowop->fo_func = flowop_composite; flowop->fo_init = flowop_composite_init; flowop->fo_destruct = flowop_composite_destruct; (void) ipc_mutex_unlock(&flowop->fo_lock); return (flowop); } /* * Attempts to take a write lock on the flowop_find_lock that is * defined in interprocess shared memory. Since each call to * flowop_start() holds a read lock on flowop_find_lock, this * routine effectively blocks until all instances of * flowop_start() have finished. The flowop_find() routine calls * this routine so that flowops won't be searched for until all * flowops have been created by flowop_start. */ static void flowop_find_barrier(void) { /* Block on wrlock to ensure find waits for all creates */ (void) pthread_rwlock_wrlock(&filebench_shm->shm_flowop_find_lock); (void) pthread_rwlock_unlock(&filebench_shm->shm_flowop_find_lock); } /* * Returns a list of flowops named "name" from the master * flowop list. */ flowop_t * flowop_find(char *name) { flowop_t *flowop; flowop_t *result = NULL; flowop_find_barrier(); (void) ipc_mutex_lock(&filebench_shm->shm_flowop_lock); flowop = filebench_shm->shm_flowoplist; while (flowop) { if (strcmp(name, flowop->fo_name) == 0) { /* Add flowop to result list */ if (result == NULL) { result = flowop; flowop->fo_resultnext = NULL; } else { flowop->fo_resultnext = result; result = flowop; } } flowop = flowop->fo_next; } (void) ipc_mutex_unlock(&filebench_shm->shm_flowop_lock); return result; } /* * Returns a pointer to the specified instance of flowop * "name" from the global list. */ flowop_t * flowop_find_one(char *name, int instance) { flowop_t *test_flowop; flowop_find_barrier(); (void) ipc_mutex_lock(&filebench_shm->shm_flowop_lock); test_flowop = filebench_shm->shm_flowoplist; while (test_flowop) { if ((strcmp(name, test_flowop->fo_name) == 0) && (instance == test_flowop->fo_instance)) break; test_flowop = test_flowop->fo_next; } (void) ipc_mutex_unlock(&filebench_shm->shm_flowop_lock); return (test_flowop); } /* * recursively searches through lists of flowops on a given thread * and those on any included composite flowops for the named flowop. * either returns with a pointer to the named flowop or NULL if it * cannot be found. */ static flowop_t * flowop_recurse_search(char *path, char *name, flowop_t *list) { flowop_t *test_flowop; char fullname[MAXPATHLEN]; test_flowop = list; /* * when searching a list of inner flowops, "path" is the fullname * of the containing composite flowop. Use it to form the * full name of the inner flowop to search for. */ if (path) { if ((strlen(path) + strlen(name) + 1) > MAXPATHLEN) { filebench_log(LOG_ERROR, "composite flowop path name %s.%s too long", path, name); return (NULL); } /* create composite_name.name for recursive search */ (void) strcpy(fullname, path); (void) strcat(fullname, "."); (void) strcat(fullname, name); } else { (void) strcpy(fullname, name); } /* * loop through all flowops on the supplied tf_thrd_fops (flowop) * list or fo_comp_fops (inner flowop) list. */ while (test_flowop) { if (strcmp(fullname, test_flowop->fo_name) == 0) return (test_flowop); if (test_flowop->fo_type == FLOW_TYPE_COMPOSITE) { flowop_t *found_flowop; found_flowop = flowop_recurse_search( test_flowop->fo_name, name, test_flowop->fo_comp_fops); if (found_flowop) return (found_flowop); } test_flowop = test_flowop->fo_exec_next; } /* not found here or on any child lists */ return (NULL); } /* * Returns a pointer to flowop named "name" from the supplied tf_thrd_fops * list of flowops. Returns the named flowop if found, or NULL. */ flowop_t * flowop_find_from_list(char *name, flowop_t *list) { flowop_t *found_flowop; flowop_find_barrier(); (void) ipc_mutex_lock(&filebench_shm->shm_flowop_lock); found_flowop = flowop_recurse_search(NULL, name, list); (void) ipc_mutex_unlock(&filebench_shm->shm_flowop_lock); return (found_flowop); } /* * Composite flowop method. Does one pass through its list of * inner flowops per iteration. */ static int flowop_composite(threadflow_t *threadflow, flowop_t *flowop) { flowop_t *inner_flowop; /* get the first flowop in the list */ inner_flowop = flowop->fo_comp_fops; /* make a pass through the list of sub flowops */ while (inner_flowop) { int i, count; /* Abort if asked */ if (threadflow->tf_abort || filebench_shm->shm_f_abort) return (FILEBENCH_DONE); /* Execute the flowop for fo_iters times */ count = (int)avd_get_int(inner_flowop->fo_iters); for (i = 0; i < count; i++) { filebench_log(LOG_DEBUG_SCRIPT, "%s: executing flowop " "%s-%d", threadflow->tf_name, inner_flowop->fo_name, inner_flowop->fo_instance); switch ((*inner_flowop->fo_func)(threadflow, inner_flowop)) { /* all done */ case FILEBENCH_DONE: return (FILEBENCH_DONE); /* quit if inner flowop limit reached */ case FILEBENCH_NORSC: return (FILEBENCH_NORSC); /* quit on inner flowop error */ case FILEBENCH_ERROR: filebench_log(LOG_ERROR, "inner flowop %s failed", inner_flowop->fo_name); return (FILEBENCH_ERROR); /* otherwise keep going */ default: break; } } /* advance to next flowop */ inner_flowop = inner_flowop->fo_exec_next; } /* finished with this pass */ return (FILEBENCH_OK); } /* * Composite flowop initialization. Creates runtime inner flowops * from prototype inner flowops. */ static int flowop_composite_init(flowop_t *flowop) { int err; err = flowop_create_runtime_flowops(flowop->fo_thread, &flowop->fo_comp_fops); if (err != FILEBENCH_OK) return (err); (void) ipc_mutex_unlock(&flowop->fo_lock); return (0); } /* * clean up inner flowops */ static void flowop_composite_destruct(flowop_t *flowop) { flowop_t *inner_flowop = flowop->fo_comp_fops; while (inner_flowop) { filebench_log(LOG_DEBUG_IMPL, "Deleting inner flowop (%s-%d)", inner_flowop->fo_name, inner_flowop->fo_instance); if (inner_flowop->fo_instance && (inner_flowop->fo_instance == FLOW_MASTER)) { inner_flowop = inner_flowop->fo_exec_next; continue; } flowop_delete(&flowop->fo_comp_fops, inner_flowop); inner_flowop = inner_flowop->fo_exec_next; } } /* * Support routines for libraries of flowops */ int flowop_init_generic(flowop_t *flowop) { (void) ipc_mutex_unlock(&flowop->fo_lock); return (FILEBENCH_OK); } void flowop_destruct_generic(flowop_t *flowop) { char *buf; /* release any local resources held by the flowop */ (void) ipc_mutex_lock(&flowop->fo_lock); buf = flowop->fo_buf; flowop->fo_buf = NULL; (void) ipc_mutex_unlock(&flowop->fo_lock); if (buf) free(buf); } /* * Loops through the supplied list of flowop *prototypes*, creates * corresponding flowops by calling flowop_define(), and initializes flowops. * flowop_define() places flowops on the master flowop list. All created * flowops are set to instance FLOW_DEFINITION (0). */ void flowop_add_from_proto(flowop_proto_t *list, int nops) { int i; for (i = 0; i < nops; i++) { flowop_t *flowop; flowop_proto_t *flproto; flproto = &(list[i]); flowop = flowop_define(NULL, flproto->fl_name, NULL, NULL, FLOW_DEFINITION, flproto->fl_type); if (!flowop) { filebench_log(LOG_ERROR, "failed to create flowop %s\n", flproto->fl_name); filebench_shutdown(1); } flowop->fo_func = flproto->fl_func; flowop->fo_init = flproto->fl_init; flowop->fo_destruct = flproto->fl_destruct; flowop->fo_attrs = flproto->fl_attrs; } }
31,376
26.284348
80
c
filebench
filebench-master/flowop.h
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _FB_FLOWOP_H #define _FB_FLOWOP_H #include "filebench.h" typedef struct flowop { char fo_name[128]; /* Name */ int fo_instance; /* Instance number */ struct flowop *fo_next; /* Next in global list */ struct flowop *fo_exec_next; /* Next in thread's or compfo's list */ struct flowop *fo_resultnext; /* List of flowops in result */ struct flowop *fo_comp_fops; /* List of flowops in composite fo */ var_t *fo_lvar_list; /* List of composite local vars */ struct threadflow *fo_thread; /* Backpointer to thread */ int (*fo_func)(); /* Method */ int (*fo_init)(); /* Init Method */ void (*fo_destruct)(); /* Destructor Method */ int fo_type; /* Type */ int fo_attrs; /* Flow op attribute */ avd_t fo_filename; /* file/fileset name */ fileset_t *fo_fileset; /* Fileset for op */ int fo_fdnumber; /* User specified file descriptor */ int fo_srcfdnumber; /* User specified src file descriptor */ fbint_t fo_constvalue; /* constant version of fo_value */ fbint_t fo_constwss; /* constant version of fo_wss */ avd_t fo_iosize; /* Size of operation */ avd_t fo_wss; /* Flow op working set size */ char fo_targetname[128]; /* Target, for wakeup etc... */ struct flowop *fo_targets; /* List of targets matching name */ struct flowop *fo_targetnext; /* List of targets matching name */ avd_t fo_iters; /* Number of iterations of op */ avd_t fo_value; /* Attr */ avd_t fo_sequential; /* Attr */ avd_t fo_random; /* Attr */ avd_t fo_stride; /* Attr */ avd_t fo_backwards; /* Attr */ avd_t fo_dsync; /* Attr */ avd_t fo_blocking; /* Attr */ avd_t fo_directio; /* Attr */ avd_t fo_rotatefd; /* Attr */ avd_t fo_fileindex; /* Attr */ avd_t fo_noreadahead; /* Attr */ struct flowstats fo_stats; /* Flow statistics */ pthread_cond_t fo_cv; /* Block/wakeup cv */ pthread_mutex_t fo_lock; /* Mutex around flowop */ void *fo_private; /* Flowop private scratch pad area */ char *fo_buf; /* Per-flowop buffer */ uint64_t fo_buf_size; /* current size of buffer */ #ifdef HAVE_SYSV_SEM int fo_semid_lw; /* sem id */ int fo_semid_hw; /* sem id for highwater block */ #else sem_t fo_sem; /* sem_t for posix semaphores */ #endif /* HAVE_SYSV_SEM */ avd_t fo_highwater; /* value of highwater paramter */ void *fo_idp; /* id, for sems etc */ hrtime_t fo_timestamp; /* for ratecontrol, etc... */ int fo_initted; /* Set to one if initialized */ int64_t fo_tputbucket; /* Throughput bucket, for limiter */ uint64_t fo_tputlast; /* Throughput count, for delta's */ } flowop_t; /* Flow Op Attrs */ #define FLOW_ATTR_SEQUENTIAL 0x1 #define FLOW_ATTR_RANDOM 0x2 #define FLOW_ATTR_STRIDE 0x4 #define FLOW_ATTR_BACKWARDS 0x8 #define FLOW_ATTR_DSYNC 0x10 #define FLOW_ATTR_BLOCKING 0x20 #define FLOW_ATTR_DIRECTIO 0x40 #define FLOW_ATTR_READ 0x80 #define FLOW_ATTR_WRITE 0x100 #define FLOW_ATTR_FADV_RANDOM 0x200 /* Flowop Instance Numbers */ /* Worker flowops have instance numbers > 0 */ #define FLOW_DEFINITION 0 /* Prototype definition of flowop from library */ #define FLOW_INNER_DEF -1 /* Constructed proto flowops within composite */ #define FLOW_MASTER -2 /* Master flowop based on flowop declaration */ /* supplied within a thread definition */ /* Flowop type definitions */ #define FLOW_TYPES 6 #define FLOW_TYPE_GLOBAL 0 /* Rolled up statistics */ #define FLOW_TYPE_IO 1 /* Op is an I/O, reflected in iops and lat */ #define FLOW_TYPE_AIO 2 /* Op is an async I/O, reflected in iops */ #define FLOW_TYPE_SYNC 3 /* Op is a sync event */ #define FLOW_TYPE_COMPOSITE 4 /* Op is a composite flowop */ #define FLOW_TYPE_OTHER 5 /* Op is a something else */ typedef struct flowop_proto { int fl_type; int fl_attrs; char *fl_name; int (*fl_init)(); int (*fl_func)(); void (*fl_destruct)(); } flowop_proto_t; extern struct flowstats controlstats; extern pthread_mutex_t controlstats_lock; flowop_t *flowop_define(threadflow_t *, char *name, flowop_t *inherit, flowop_t **flowoplist_hdp, int instance, int type); flowop_t *flowop_find(char *name); flowop_t *flowop_find_one(char *name, int instance); flowop_t *flowop_find_from_list(char *name, flowop_t *list); int flowop_init_generic(flowop_t *flowop); void flowop_destruct_generic(flowop_t *flowop); void flowop_add_from_proto(flowop_proto_t *list, int nops); int flowoplib_iosetup(threadflow_t *threadflow, flowop_t *flowop, fbint_t *wssp, caddr_t *iobufp, fb_fdesc_t **filedescp, fbint_t iosize); void flowoplib_flowinit(void); void flowop_delete_all(flowop_t **threadlist); void flowop_endop(threadflow_t *threadflow, flowop_t *flowop, int64_t bytes); void flowop_beginop(threadflow_t *threadflow, flowop_t *flowop); void flowop_destruct_all_flows(threadflow_t *threadflow); flowop_t *flowop_new_composite_define(char *name); void flowop_printall(void); void flowop_init(int ismaster); /* Local file system specific */ void fb_lfs_funcvecinit(); void fb_lfs_newflowops(); #endif /* _FB_FLOWOP_H */
5,901
37.077419
77
h
filebench
filebench-master/flowop_library.c
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * Portions Copyright 2008 Denis Cheng */ #include "config.h" #include <sys/types.h> #include <stddef.h> #include <sys/ipc.h> #include <sys/sem.h> #include <sys/errno.h> #include <sys/time.h> #include <inttypes.h> #include <fcntl.h> #include <math.h> #include <dirent.h> #ifndef HAVE_SYSV_SEM #include <semaphore.h> #endif /* HAVE_SYSV_SEM */ #include "filebench.h" #include "flowop.h" #include "fileset.h" #include "fb_random.h" #include "utils.h" #include "fsplug.h" /* * These routines implement the flowops from the f language. Each * flowop has has a name such as "read", and a set of function pointers * to call for initialization, execution and destruction of the flowop. * The table flowoplib_funcs[] contains a flowoplib struct for each * implemented flowop. Most flowops use a generic initialization function * and all currently use a generic destruction function. All flowop * functions referenced from the table are in this file, though, of * course, they often call functions from other files. * * The flowop_init() routine uses the flowoplib_funcs[] table to * create an initial set of "instance 0" flowops, one for each type of * flowop, from which all other flowops are derived. These "instance 0" * flowops are initialized with information from the table including * pointers for their fo_init, fo_func and fo_destroy functions. When * a flowop definition is encountered in an f language script, the * "type" of flowop, such as "read" is used to search for the * "instance 0" flowop named "read", then a new flowop is allocated * which inherits its function pointers and other initial properties * from the instance 0 flowop, and is given a new name as specified * by the "name=" attribute. */ static void flowoplib_destruct_noop(flowop_t *flowop); static int flowoplib_fdnum(threadflow_t *threadflow, flowop_t *flowop); static int flowoplib_print(threadflow_t *threadflow, flowop_t *flowop); static int flowoplib_write(threadflow_t *threadflow, flowop_t *flowop); static int flowoplib_read(threadflow_t *threadflow, flowop_t *flowop); static int flowoplib_block_init(flowop_t *flowop); static int flowoplib_block(threadflow_t *threadflow, flowop_t *flowop); static int flowoplib_wakeup(threadflow_t *threadflow, flowop_t *flowop); static int flowoplib_hog(threadflow_t *threadflow, flowop_t *flowop); static int flowoplib_delay(threadflow_t *threadflow, flowop_t *flowop); static int flowoplib_sempost(threadflow_t *threadflow, flowop_t *flowop); static int flowoplib_sempost_init(flowop_t *flowop); static int flowoplib_semblock(threadflow_t *threadflow, flowop_t *flowop); static int flowoplib_semblock_init(flowop_t *flowop); static void flowoplib_semblock_destruct(flowop_t *flowop); static int flowoplib_eventlimit(threadflow_t *, flowop_t *flowop); static int flowoplib_bwlimit(threadflow_t *, flowop_t *flowop); static int flowoplib_iopslimit(threadflow_t *, flowop_t *flowop); static int flowoplib_opslimit(threadflow_t *, flowop_t *flowop); static int flowoplib_openfile(threadflow_t *, flowop_t *flowop); static int flowoplib_openfile_common(threadflow_t *, flowop_t *flowop, int fd); static int flowoplib_createfile(threadflow_t *, flowop_t *flowop); static int flowoplib_closefile(threadflow_t *, flowop_t *flowop); static int flowoplib_makedir(threadflow_t *, flowop_t *flowop); static int flowoplib_removedir(threadflow_t *, flowop_t *flowop); static int flowoplib_listdir(threadflow_t *, flowop_t *flowop); static int flowoplib_fsync(threadflow_t *, flowop_t *flowop); static int flowoplib_readwholefile(threadflow_t *, flowop_t *flowop); static int flowoplib_writewholefile(threadflow_t *, flowop_t *flowop); static int flowoplib_appendfile(threadflow_t *threadflow, flowop_t *flowop); static int flowoplib_appendfilerand(threadflow_t *threadflow, flowop_t *flowop); static int flowoplib_deletefile(threadflow_t *threadflow, flowop_t *flowop); static int flowoplib_statfile(threadflow_t *threadflow, flowop_t *flowop); static int flowoplib_finishoncount(threadflow_t *threadflow, flowop_t *flowop); static int flowoplib_finishonbytes(threadflow_t *threadflow, flowop_t *flowop); static int flowoplib_fsyncset(threadflow_t *threadflow, flowop_t *flowop); static int flowoplib_testrandvar(threadflow_t *threadflow, flowop_t *flowop); static int flowoplib_testrandvar_init(flowop_t *flowop); static void flowoplib_testrandvar_destruct(flowop_t *flowop); static flowop_proto_t flowoplib_funcs[] = { {FLOW_TYPE_IO, FLOW_ATTR_WRITE, "write", flowop_init_generic, flowoplib_write, flowop_destruct_generic}, {FLOW_TYPE_IO, FLOW_ATTR_READ, "read", flowop_init_generic, flowoplib_read, flowop_destruct_generic}, {FLOW_TYPE_SYNC, 0, "block", flowoplib_block_init, flowoplib_block, flowop_destruct_generic}, {FLOW_TYPE_SYNC, 0, "wakeup", flowop_init_generic, flowoplib_wakeup, flowop_destruct_generic}, {FLOW_TYPE_SYNC, 0, "semblock", flowoplib_semblock_init, flowoplib_semblock, flowoplib_semblock_destruct}, {FLOW_TYPE_SYNC, 0, "sempost", flowoplib_sempost_init, flowoplib_sempost, flowoplib_destruct_noop}, {FLOW_TYPE_OTHER, 0, "hog", flowop_init_generic, flowoplib_hog, flowop_destruct_generic}, {FLOW_TYPE_OTHER, 0, "delay", flowop_init_generic, flowoplib_delay, flowop_destruct_generic}, {FLOW_TYPE_OTHER, 0, "eventlimit", flowop_init_generic, flowoplib_eventlimit, flowop_destruct_generic}, {FLOW_TYPE_OTHER, 0, "bwlimit", flowop_init_generic, flowoplib_bwlimit, flowop_destruct_generic}, {FLOW_TYPE_OTHER, 0, "iopslimit", flowop_init_generic, flowoplib_iopslimit, flowop_destruct_generic}, {FLOW_TYPE_OTHER, 0, "opslimit", flowop_init_generic, flowoplib_opslimit, flowop_destruct_generic}, {FLOW_TYPE_OTHER, 0, "finishoncount", flowop_init_generic, flowoplib_finishoncount, flowop_destruct_generic}, {FLOW_TYPE_OTHER, 0, "finishonbytes", flowop_init_generic, flowoplib_finishonbytes, flowop_destruct_generic}, {FLOW_TYPE_IO, 0, "openfile", flowop_init_generic, flowoplib_openfile, flowop_destruct_generic}, {FLOW_TYPE_IO, 0, "createfile", flowop_init_generic, flowoplib_createfile, flowop_destruct_generic}, {FLOW_TYPE_IO, 0, "closefile", flowop_init_generic, flowoplib_closefile, flowop_destruct_generic}, {FLOW_TYPE_IO, 0, "makedir", flowop_init_generic, flowoplib_makedir, flowop_destruct_generic}, {FLOW_TYPE_IO, 0, "removedir", flowop_init_generic, flowoplib_removedir, flowop_destruct_generic}, {FLOW_TYPE_IO, 0, "listdir", flowop_init_generic, flowoplib_listdir, flowop_destruct_generic}, {FLOW_TYPE_IO, 0, "fsync", flowop_init_generic, flowoplib_fsync, flowop_destruct_generic}, {FLOW_TYPE_IO, 0, "fsyncset", flowop_init_generic, flowoplib_fsyncset, flowop_destruct_generic}, {FLOW_TYPE_IO, 0, "statfile", flowop_init_generic, flowoplib_statfile, flowop_destruct_generic}, {FLOW_TYPE_IO, FLOW_ATTR_READ, "readwholefile", flowop_init_generic, flowoplib_readwholefile, flowop_destruct_generic}, {FLOW_TYPE_IO, FLOW_ATTR_WRITE, "appendfile", flowop_init_generic, flowoplib_appendfile, flowop_destruct_generic}, {FLOW_TYPE_IO, FLOW_ATTR_WRITE, "appendfilerand", flowop_init_generic, flowoplib_appendfilerand, flowop_destruct_generic}, {FLOW_TYPE_IO, 0, "deletefile", flowop_init_generic, flowoplib_deletefile, flowop_destruct_generic}, {FLOW_TYPE_IO, FLOW_ATTR_WRITE, "writewholefile", flowop_init_generic, flowoplib_writewholefile, flowop_destruct_generic}, {FLOW_TYPE_OTHER, 0, "print", flowop_init_generic, flowoplib_print, flowop_destruct_generic}, /* routine to calculate mean and stddev for output from a randvar */ {FLOW_TYPE_OTHER, 0, "testrandvar", flowoplib_testrandvar_init, flowoplib_testrandvar, flowoplib_testrandvar_destruct} }; /* * Loops through the list of flowops defined in this * module, and creates and initializes a flowop for each one * by calling flowop_flow_init. As a side effect of calling * flowop_flow_init, the created flowops are placed on the * master flowop list. All created flowops are set to * instance "0". */ void flowoplib_flowinit(void) { int nops = sizeof (flowoplib_funcs) / sizeof (flowop_proto_t); flowop_add_from_proto(flowoplib_funcs, nops); } /* * Special total noop destruct */ /* ARGSUSED */ static void flowoplib_destruct_noop(flowop_t *flowop) { } /* * Generates a file attribute from flags in the supplied flowop. * Sets FLOW_ATTR_DIRECTIO and/or FLOW_ATTR_DSYNC and advise for * no random read (POSIX_FADV_RANDOM) as needed. */ static int flowoplib_fileattrs(flowop_t *flowop) { int attrs = 0; if (avd_get_bool(flowop->fo_directio)) attrs |= FLOW_ATTR_DIRECTIO; if (avd_get_bool(flowop->fo_dsync)) attrs |= FLOW_ATTR_DSYNC; if (avd_get_bool(flowop->fo_noreadahead)) attrs |= FLOW_ATTR_FADV_RANDOM; return (attrs); } /* * Obtain a filesetentry for a file. Result placed where filep points. * Supply with a flowop and a flag to indicate whether an existent or * non-existent file is required. Returns FILEBENCH_NORSC if all out * of the appropriate type of directories, FILEBENCH_ERROR if the * flowop does not point to a fileset, and FILEBENCH_OK otherwise. */ static int flowoplib_pickfile(filesetentry_t **filep, flowop_t *flowop, int flags, int tid) { fileset_t *fileset; int fileindex; if ((fileset = flowop->fo_fileset) == NULL) { filebench_log(LOG_ERROR, "flowop NO fileset"); return (FILEBENCH_ERROR); } if (flowop->fo_fileindex) { fileindex = (int)(avd_get_dbl(flowop->fo_fileindex)); fileindex = fileindex % fileset->fs_constentries; flags |= FILESET_PICKBYINDEX; } else { fileindex = 0; } if ((*filep = fileset_pick(fileset, FILESET_PICKFILE | flags, tid, fileindex)) == NULL) { filebench_log(LOG_DEBUG_SCRIPT, "flowop %s failed to pick file from fileset %s", flowop->fo_name, avd_get_str(fileset->fs_name)); return (FILEBENCH_NORSC); } return (FILEBENCH_OK); } /* * Obtain a filesetentry for a leaf directory. Result placed where dirp * points. Supply with flowop and a flag to indicate whether an existent * or non-existent leaf directory is required. Returns FILEBENCH_NORSC * if all out of the appropriate type of directories, FILEBENCH_ERROR * if the flowop does not point to a fileset, and FILEBENCH_OK otherwise. */ static int flowoplib_pickleafdir(filesetentry_t **dirp, flowop_t *flowop, int flags) { fileset_t *fileset; int dirindex; if ((fileset = flowop->fo_fileset) == NULL) { filebench_log(LOG_ERROR, "flowop NO fileset"); return (FILEBENCH_ERROR); } if (flowop->fo_fileindex) { dirindex = (int)(avd_get_dbl(flowop->fo_fileindex) * ((double)(fileset->fs_constleafdirs / 2))); dirindex = dirindex % fileset->fs_constleafdirs; flags |= FILESET_PICKBYINDEX; } else { dirindex = 0; } if ((*dirp = fileset_pick(fileset, FILESET_PICKLEAFDIR | flags, 0, dirindex)) == NULL) { filebench_log(LOG_DEBUG_SCRIPT, "flowop %s failed to pick directory from fileset %s", flowop->fo_name, avd_get_str(fileset->fs_name)); return (FILEBENCH_NORSC); } return (FILEBENCH_OK); } /* * Searches for a file descriptor. Tries the flowop's fo_fdnumber first and * returns with it if it has been explicitly set (greater than 0). It next * checks to see if a rotating file descriptor policy is in effect, and if not * returns the fdnumber regardless of what it is. (note that if it is 0, it * just selects to the default file descriptor in the threadflow's tf_fd * array). If the rotating fd policy is in effect, it cycles from the end of * the tf_fd array to 0 and then starts over from the end. * * The routine returns an index into the threadflow's tf_fd table where the * actual file descriptor will be found. */ static int flowoplib_fdnum(threadflow_t *threadflow, flowop_t *flowop) { int fd = flowop->fo_fdnumber; if (fd > 0) { filebench_log(LOG_DEBUG_IMPL, "picking explicitly set fd"); goto retfd; } if (!avd_get_bool(flowop->fo_rotatefd)) { filebench_log(LOG_DEBUG_IMPL, "picking default fd"); goto retfd; } filebench_log(LOG_DEBUG_IMPL, "picking rotor fd"); /* first time or we wraped around */ if (!threadflow->tf_fdrotor) threadflow->tf_fdrotor = THREADFLOW_MAXFD; threadflow->tf_fdrotor--; fd = threadflow->tf_fdrotor; retfd: filebench_log(LOG_DEBUG_IMPL, "picked fd = %d", fd); return fd; } /* * Determines the file descriptor to use, and attempts to open * the file if it is not already open. Also determines the wss * value. Returns FILEBENCH_ERROR on errors, FILESET_NORSC if * if flowop_openfile_common couldn't obtain an appropriate file * from a the fileset, and FILEBENCH_OK otherwise. */ static int flowoplib_filesetup(threadflow_t *threadflow, flowop_t *flowop, fbint_t *wssp, fb_fdesc_t **fdescp) { int fd = flowoplib_fdnum(threadflow, flowop); if (fd == -1) return (FILEBENCH_ERROR); /* check for conflicting fdnumber and file name */ if ((fd > 0) && (threadflow->tf_fse[fd] != NULL)) { char *fd_based_name; fd_based_name = avd_get_str(threadflow->tf_fse[fd]->fse_fileset->fs_name); if (flowop->fo_filename != NULL) { char *fo_based_name; fo_based_name = avd_get_str(flowop->fo_filename); if (strcmp(fd_based_name, fo_based_name) != 0) { filebench_log(LOG_ERROR, "Name of fd refer" "enced fileset name (%s) CONFLICTS with" " flowop supplied fileset name (%s)", fd_based_name, fo_based_name); filebench_shutdown(1); return (FILEBENCH_ERROR); } } } if (threadflow->tf_fd[fd].fd_ptr == NULL) { int ret; if ((ret = flowoplib_openfile_common( threadflow, flowop, fd)) != FILEBENCH_OK) return (ret); if (threadflow->tf_fse[fd]) { filebench_log(LOG_DEBUG_IMPL, "opened file %s", threadflow->tf_fse[fd]->fse_path); } else { filebench_log(LOG_DEBUG_IMPL, "opened device %s/%s", avd_get_str(flowop->fo_fileset->fs_path), avd_get_str(flowop->fo_fileset->fs_name)); } } *fdescp = &(threadflow->tf_fd[fd]); if ((*wssp = flowop->fo_constwss) == 0) { if (threadflow->tf_fse[fd]) *wssp = threadflow->tf_fse[fd]->fse_size; else *wssp = avd_get_int(flowop->fo_fileset->fs_size); } return (FILEBENCH_OK); } /* * Determines the io buffer or random offset into tf_mem for * the IO operation. Returns FILEBENCH_ERROR on errors, FILEBENCH_OK otherwise. */ static int flowoplib_iobufsetup(threadflow_t *threadflow, flowop_t *flowop, caddr_t *iobufp, fbint_t iosize) { long memsize; size_t memoffset; if (iosize == 0) { filebench_log(LOG_ERROR, "zero iosize for thread %s", flowop->fo_name); return (FILEBENCH_ERROR); } /* If directio, we need to align buffer address by sector */ if (flowoplib_fileattrs(flowop) & FLOW_ATTR_DIRECTIO) iosize = iosize + 512; if ((memsize = threadflow->tf_constmemsize) != 0) { /* use tf_mem for I/O with random offset */ if (memsize < iosize) { filebench_log(LOG_ERROR, "tf_memsize smaller than IO size for thread %s", flowop->fo_name); return (FILEBENCH_ERROR); } fb_random(&memoffset, memsize, iosize, NULL); *iobufp = threadflow->tf_mem + memoffset; } else { /* use private I/O buffer */ if ((flowop->fo_buf != NULL) && (flowop->fo_buf_size < iosize)) { /* too small, so free up and re-allocate */ free(flowop->fo_buf); flowop->fo_buf = NULL; } /* * Allocate memory for the buffer. The memory is freed * by flowop_destruct_generic() or by this routine if more * memory is needed for the buffer. */ if ((flowop->fo_buf == NULL) && ((flowop->fo_buf = (char *)malloc(iosize)) == NULL)) return (FILEBENCH_ERROR); flowop->fo_buf_size = iosize; *iobufp = flowop->fo_buf; } if (flowoplib_fileattrs(flowop) & FLOW_ATTR_DIRECTIO) *iobufp = (caddr_t)((((unsigned long)(*iobufp) + 512) / 512) * 512); return (FILEBENCH_OK); } /* * Determines the file descriptor to use, opens it if necessary, the * io buffer or random offset into tf_mem for IO operation and the wss * value. Returns FILEBENCH_ERROR on errors, FILEBENCH_OK otherwise. */ int flowoplib_iosetup(threadflow_t *threadflow, flowop_t *flowop, fbint_t *wssp, caddr_t *iobufp, fb_fdesc_t **filedescp, fbint_t iosize) { int ret; if ((ret = flowoplib_filesetup(threadflow, flowop, wssp, filedescp)) != FILEBENCH_OK) return (ret); if ((ret = flowoplib_iobufsetup(threadflow, flowop, iobufp, iosize)) != FILEBENCH_OK) return (ret); return (FILEBENCH_OK); } /* * Emulate posix read / pread. If the flowop has a fileset, * a file descriptor number index is fetched, otherwise a * supplied fileobj file is used. In either case the specified * file will be opened if not already open. If the flowop has * neither a fileset or fileobj, an error is logged and FILEBENCH_ERROR * returned. * * The actual read is done to a random offset in the * threadflow's thread memory (tf_mem), with a size set by * fo_iosize and at either a random disk offset within the * working set size, or at the next sequential location. If * any errors are encountered, FILEBENCH_ERROR is returned, * if no appropriate file can be obtained from the fileset then * FILEBENCH_NORSC is returned, otherise FILEBENCH_OK is returned. */ static int flowoplib_read(threadflow_t *threadflow, flowop_t *flowop) { caddr_t iobuf; fbint_t wss; fbint_t iosize; fb_fdesc_t *fdesc; int ret; iosize = avd_get_int(flowop->fo_iosize); if ((ret = flowoplib_iosetup(threadflow, flowop, &wss, &iobuf, &fdesc, iosize)) != FILEBENCH_OK) return (ret); if (avd_get_bool(flowop->fo_random)) { uint64_t fileoffset; if (iosize > wss) { filebench_log(LOG_ERROR, "file size smaller than IO size for thread %s", flowop->fo_name); return (FILEBENCH_ERROR); } /* select randomly */ fb_random64(&fileoffset, wss, iosize, NULL); (void) flowop_beginop(threadflow, flowop); if ((ret = FB_PREAD(fdesc, iobuf, iosize, (off64_t)fileoffset)) == -1) { (void) flowop_endop(threadflow, flowop, 0); filebench_log(LOG_ERROR, "read file %s failed, offset %llu " "io buffer %zd: %s", avd_get_str(flowop->fo_fileset->fs_name), (u_longlong_t)fileoffset, iobuf, strerror(errno)); flowop_endop(threadflow, flowop, 0); return (FILEBENCH_ERROR); } (void) flowop_endop(threadflow, flowop, ret); if ((ret == 0)) (void) FB_LSEEK(fdesc, 0, SEEK_SET); } else { (void) flowop_beginop(threadflow, flowop); if ((ret = FB_READ(fdesc, iobuf, iosize)) == -1) { (void) flowop_endop(threadflow, flowop, 0); filebench_log(LOG_ERROR, "read file %s failed, io buffer %zd: %s", avd_get_str(flowop->fo_fileset->fs_name), iobuf, strerror(errno)); (void) flowop_endop(threadflow, flowop, 0); return (FILEBENCH_ERROR); } (void) flowop_endop(threadflow, flowop, ret); if ((ret == 0)) (void) FB_LSEEK(fdesc, 0, SEEK_SET); } return (FILEBENCH_OK); } /* * Initializes a "flowop_block" flowop. Specifically, it * initializes the flowop's fo_cv and unlocks the fo_lock. */ static int flowoplib_block_init(flowop_t *flowop) { filebench_log(LOG_DEBUG_IMPL, "flow %s-%d block init address %zx", flowop->fo_name, flowop->fo_instance, &flowop->fo_cv); (void) pthread_cond_init(&flowop->fo_cv, ipc_condattr()); (void) ipc_mutex_unlock(&flowop->fo_lock); return (FILEBENCH_OK); } /* * Blocks the threadflow until woken up by flowoplib_wakeup. * The routine blocks on the flowop's fo_cv condition variable. */ static int flowoplib_block(threadflow_t *threadflow, flowop_t *flowop) { filebench_log(LOG_DEBUG_IMPL, "flow %s-%d blocking at address %zx", flowop->fo_name, flowop->fo_instance, &flowop->fo_cv); (void) ipc_mutex_lock(&flowop->fo_lock); flowop_beginop(threadflow, flowop); (void) pthread_cond_wait(&flowop->fo_cv, &flowop->fo_lock); flowop_endop(threadflow, flowop, 0); filebench_log(LOG_DEBUG_IMPL, "flow %s-%d unblocking", flowop->fo_name, flowop->fo_instance); (void) ipc_mutex_unlock(&flowop->fo_lock); return (FILEBENCH_OK); } /* * Wakes up one or more target blocking flowops. * Sends broadcasts on the fo_cv condition variables of all * flowops on the target list, except those that are * FLOW_MASTER flowops. The target list consists of all * flowops whose name matches this flowop's "fo_targetname" * attribute. The target list is generated on the first * invocation, and the run will be shutdown if no targets * are found. Otherwise the routine always returns FILEBENCH_OK. */ static int flowoplib_wakeup(threadflow_t *threadflow, flowop_t *flowop) { flowop_t *target; /* if this is the first wakeup, create the wakeup list */ if (flowop->fo_targets == NULL) { flowop_t *result = flowop_find(flowop->fo_targetname); flowop->fo_targets = result; if (result == NULL) { filebench_log(LOG_ERROR, "wakeup: could not find op %s for thread %s", flowop->fo_targetname, threadflow->tf_name); filebench_shutdown(1); } while (result) { result->fo_targetnext = result->fo_resultnext; result = result->fo_resultnext; } } target = flowop->fo_targets; /* wakeup the targets */ while (target) { if (target->fo_instance == FLOW_MASTER) { target = target->fo_targetnext; continue; } filebench_log(LOG_DEBUG_IMPL, "wakeup flow %s-%d at address %zx", target->fo_name, target->fo_instance, &target->fo_cv); flowop_beginop(threadflow, flowop); (void) ipc_mutex_lock(&target->fo_lock); (void) pthread_cond_broadcast(&target->fo_cv); (void) ipc_mutex_unlock(&target->fo_lock); flowop_endop(threadflow, flowop, 0); target = target->fo_targetnext; } return (FILEBENCH_OK); } /* * "think time" routines. the "hog" routine consumes cpu cycles as * it "thinks", while the "delay" flowop simply calls sleep() to delay * for a given number of seconds without consuming cpu cycles. */ /* * Consumes CPU cycles and memory bandwidth by looping for * flowop->fo_value times. With each loop sets memory location * threadflow->tf_mem to 1. */ static int flowoplib_hog(threadflow_t *threadflow, flowop_t *flowop) { uint64_t value = avd_get_int(flowop->fo_value); int i; filebench_log(LOG_DEBUG_IMPL, "hog enter"); flowop_beginop(threadflow, flowop); if (threadflow->tf_mem != NULL) { for (i = 0; i < value; i++) *(threadflow->tf_mem) = 1; } flowop_endop(threadflow, flowop, 0); filebench_log(LOG_DEBUG_IMPL, "hog exit"); return (FILEBENCH_OK); } /* * Delays for fo_value seconds. */ static int flowoplib_delay(threadflow_t *threadflow, flowop_t *flowop) { int value = avd_get_int(flowop->fo_value); flowop_beginop(threadflow, flowop); (void) sleep(value); flowop_endop(threadflow, flowop, 0); return (FILEBENCH_OK); } /* * Rate limiting routines. This is the event consuming half of the * event system. Each of the four following routines will limit the rate * to one unit of either calls, issued I/O operations, issued filebench * operations, or I/O bandwidth. Since there is only one event generator, * the events will be divided amoung multiple instances of an event * consumer, and further divided among different consumers if more than * one has been defined. There is no mechanism to enforce equal sharing * of events. */ /* * Completes one invocation per posted event. If eventgen_q * has an event count greater than zero, one will be removed * (count decremented), otherwise the calling thread will * block until another event has been posted. Always returns 0 */ static int flowoplib_eventlimit(threadflow_t *threadflow, flowop_t *flowop) { /* Immediately bail if not set/enabled */ if (!filebench_shm->shm_eventgen_enabled) return (FILEBENCH_OK); if (flowop->fo_initted == 0) { filebench_log(LOG_DEBUG_IMPL, "rate %zx %s-%d locking", flowop, threadflow->tf_name, threadflow->tf_instance); flowop->fo_initted = 1; } flowop_beginop(threadflow, flowop); while (filebench_shm->shm_eventgen_enabled) { (void) ipc_mutex_lock(&filebench_shm->shm_eventgen_lock); if (filebench_shm->shm_eventgen_q > 0) { filebench_shm->shm_eventgen_q--; (void) ipc_mutex_unlock( &filebench_shm->shm_eventgen_lock); break; } (void) pthread_cond_wait(&filebench_shm->shm_eventgen_cv, &filebench_shm->shm_eventgen_lock); (void) ipc_mutex_unlock(&filebench_shm->shm_eventgen_lock); } flowop_endop(threadflow, flowop, 0); return (FILEBENCH_OK); } static int flowoplib_event_find_target(threadflow_t *threadflow, flowop_t *flowop) { if (flowop->fo_targetname[0] != '\0') { /* Try to use statistics from specific flowop */ flowop->fo_targets = flowop_find_from_list(flowop->fo_targetname, threadflow->tf_thrd_fops); if (flowop->fo_targets == NULL) { filebench_log(LOG_ERROR, "limit target: could not find flowop %s", flowop->fo_targetname); filebench_shutdown(1); return (FILEBENCH_ERROR); } } else { /* use total workload statistics */ flowop->fo_targets = NULL; } return (FILEBENCH_OK); } /* * Blocks the calling thread if the number of issued I/O * operations exceeds the number of posted events, thus * limiting the average I/O operation rate to the rate * specified by eventgen_hz. Always returns FILEBENCH_OK. */ static int flowoplib_iopslimit(threadflow_t *threadflow, flowop_t *flowop) { uint64_t iops; uint64_t delta; uint64_t events; /* Immediately bail if not set/enabled */ if (!filebench_shm->shm_eventgen_enabled) return (FILEBENCH_OK); if (flowop->fo_initted == 0) { filebench_log(LOG_DEBUG_IMPL, "rate %zx %s-%d locking", flowop, threadflow->tf_name, threadflow->tf_instance); flowop->fo_initted = 1; if (flowoplib_event_find_target(threadflow, flowop) == FILEBENCH_ERROR) return (FILEBENCH_ERROR); if (flowop->fo_targets && ((flowop->fo_targets->fo_attrs & (FLOW_ATTR_READ | FLOW_ATTR_WRITE)) == 0)) { filebench_log(LOG_ERROR, "WARNING: Flowop %s does no IO", flowop->fo_targets->fo_name); filebench_shutdown(1); return (FILEBENCH_ERROR); } } if (flowop->fo_targets) { /* * Note that fs_count is already the sum of fs_rcount * and fs_wcount if looking at a single flowop. */ iops = flowop->fo_targets->fo_stats.fs_count; } else { (void) ipc_mutex_lock(&controlstats_lock); iops = (controlstats.fs_rcount + controlstats.fs_wcount); (void) ipc_mutex_unlock(&controlstats_lock); } /* Is this the first time around */ if (flowop->fo_tputlast == 0) { flowop->fo_tputlast = iops; return (FILEBENCH_OK); } delta = iops - flowop->fo_tputlast; flowop->fo_tputbucket -= delta; flowop->fo_tputlast = iops; /* No need to block if the q isn't empty */ if (flowop->fo_tputbucket >= 0LL) { flowop_endop(threadflow, flowop, 0); return (FILEBENCH_OK); } iops = flowop->fo_tputbucket * -1; events = iops; flowop_beginop(threadflow, flowop); while (filebench_shm->shm_eventgen_enabled) { (void) ipc_mutex_lock(&filebench_shm->shm_eventgen_lock); if (filebench_shm->shm_eventgen_q >= events) { filebench_shm->shm_eventgen_q -= events; (void) ipc_mutex_unlock( &filebench_shm->shm_eventgen_lock); flowop->fo_tputbucket += events; break; } (void) pthread_cond_wait(&filebench_shm->shm_eventgen_cv, &filebench_shm->shm_eventgen_lock); (void) ipc_mutex_unlock(&filebench_shm->shm_eventgen_lock); } flowop_endop(threadflow, flowop, 0); return (FILEBENCH_OK); } /* * Blocks the calling thread if the number of issued filebench * operations exceeds the number of posted events, thus limiting * the average filebench operation rate to the rate specified by * eventgen_hz. Always returns FILEBENCH_OK. */ static int flowoplib_opslimit(threadflow_t *threadflow, flowop_t *flowop) { uint64_t ops; uint64_t delta; uint64_t events; /* Immediately bail if not set/enabled */ if (!filebench_shm->shm_eventgen_enabled) return (FILEBENCH_OK); if (flowop->fo_initted == 0) { filebench_log(LOG_DEBUG_IMPL, "rate %zx %s-%d locking", flowop, threadflow->tf_name, threadflow->tf_instance); flowop->fo_initted = 1; if (flowoplib_event_find_target(threadflow, flowop) == FILEBENCH_ERROR) return (FILEBENCH_ERROR); } if (flowop->fo_targets) { ops = flowop->fo_targets->fo_stats.fs_count; } else { (void) ipc_mutex_lock(&controlstats_lock); ops = controlstats.fs_count; (void) ipc_mutex_unlock(&controlstats_lock); } /* Is this the first time around */ if (flowop->fo_tputlast == 0) { flowop->fo_tputlast = ops; return (FILEBENCH_OK); } delta = ops - flowop->fo_tputlast; flowop->fo_tputbucket -= delta; flowop->fo_tputlast = ops; /* No need to block if the q isn't empty */ if (flowop->fo_tputbucket >= 0LL) { flowop_endop(threadflow, flowop, 0); return (FILEBENCH_OK); } ops = flowop->fo_tputbucket * -1; events = ops; flowop_beginop(threadflow, flowop); while (filebench_shm->shm_eventgen_enabled) { (void) ipc_mutex_lock(&filebench_shm->shm_eventgen_lock); if (filebench_shm->shm_eventgen_q >= events) { filebench_shm->shm_eventgen_q -= events; (void) ipc_mutex_unlock( &filebench_shm->shm_eventgen_lock); flowop->fo_tputbucket += events; break; } (void) pthread_cond_wait(&filebench_shm->shm_eventgen_cv, &filebench_shm->shm_eventgen_lock); (void) ipc_mutex_unlock(&filebench_shm->shm_eventgen_lock); } flowop_endop(threadflow, flowop, 0); return (FILEBENCH_OK); } /* * Blocks the calling thread if the number of bytes of I/O * issued exceeds one megabyte times the number of posted * events, thus limiting the average I/O byte rate to one * megabyte times the event rate as set by eventgen_hz. * Always retuns FILEBENCH_OK. */ static int flowoplib_bwlimit(threadflow_t *threadflow, flowop_t *flowop) { uint64_t bytes; uint64_t delta; uint64_t events; /* Immediately bail if not set/enabled */ if (!filebench_shm->shm_eventgen_enabled) return (FILEBENCH_OK); if (flowop->fo_initted == 0) { filebench_log(LOG_DEBUG_IMPL, "rate %zx %s-%d locking", flowop, threadflow->tf_name, threadflow->tf_instance); flowop->fo_initted = 1; if (flowoplib_event_find_target(threadflow, flowop) == FILEBENCH_ERROR) return (FILEBENCH_ERROR); if ((flowop->fo_targets) && ((flowop->fo_targets->fo_attrs & (FLOW_ATTR_READ | FLOW_ATTR_WRITE)) == 0)) { filebench_log(LOG_ERROR, "WARNING: Flowop %s does no Reads or Writes", flowop->fo_targets->fo_name); filebench_shutdown(1); return (FILEBENCH_ERROR); } } if (flowop->fo_targets) { /* * Note that fs_bytes is already the sum of fs_rbytes * and fs_wbytes if looking at a single flowop. */ bytes = flowop->fo_targets->fo_stats.fs_bytes; } else { (void) ipc_mutex_lock(&controlstats_lock); bytes = (controlstats.fs_rbytes + controlstats.fs_wbytes); (void) ipc_mutex_unlock(&controlstats_lock); } /* Is this the first time around? */ if (flowop->fo_tputlast == 0) { flowop->fo_tputlast = bytes; return (FILEBENCH_OK); } delta = bytes - flowop->fo_tputlast; flowop->fo_tputbucket -= delta; flowop->fo_tputlast = bytes; /* No need to block if the q isn't empty */ if (flowop->fo_tputbucket >= 0LL) { flowop_endop(threadflow, flowop, 0); return (FILEBENCH_OK); } bytes = flowop->fo_tputbucket * -1; events = (bytes / MB) + 1; filebench_log(LOG_DEBUG_IMPL, "%llu bytes, %llu events", (u_longlong_t)bytes, (u_longlong_t)events); flowop_beginop(threadflow, flowop); while (filebench_shm->shm_eventgen_enabled) { (void) ipc_mutex_lock(&filebench_shm->shm_eventgen_lock); if (filebench_shm->shm_eventgen_q >= events) { filebench_shm->shm_eventgen_q -= events; (void) ipc_mutex_unlock( &filebench_shm->shm_eventgen_lock); flowop->fo_tputbucket += (events * MB); break; } (void) pthread_cond_wait(&filebench_shm->shm_eventgen_cv, &filebench_shm->shm_eventgen_lock); (void) ipc_mutex_unlock(&filebench_shm->shm_eventgen_lock); } flowop_endop(threadflow, flowop, 0); return (FILEBENCH_OK); } /* * Stop worker thread when specified number of I/O bytes have been transferred. */ static int flowoplib_finishonbytes(threadflow_t *threadflow, flowop_t *flowop) { uint64_t bytes_io; /* Bytes of I/O delivered so far */ uint64_t byte_lim = flowop->fo_constvalue; /* Total Bytes desired */ /* Uses constant value */ if (flowop->fo_initted == 0) { filebench_log(LOG_DEBUG_IMPL, "rate %zx %s-%d locking", flowop, threadflow->tf_name, threadflow->tf_instance); flowop->fo_initted = 1; if (flowoplib_event_find_target(threadflow, flowop) == FILEBENCH_ERROR) return (FILEBENCH_ERROR); if ((flowop->fo_targets) && ((flowop->fo_targets->fo_attrs & (FLOW_ATTR_READ | FLOW_ATTR_WRITE)) == 0)) { filebench_log(LOG_ERROR, "WARNING: Flowop %s does no Reads or Writes", flowop->fo_targets->fo_name); filebench_shutdown(1); return (FILEBENCH_ERROR); } } if (flowop->fo_targets) { bytes_io = flowop->fo_targets->fo_stats.fs_bytes; } else { (void) ipc_mutex_lock(&controlstats_lock); bytes_io = controlstats.fs_bytes; (void) ipc_mutex_unlock(&controlstats_lock); } flowop_beginop(threadflow, flowop); if (bytes_io > byte_lim) { flowop_endop(threadflow, flowop, 0); return (FILEBENCH_NORSC); } flowop_endop(threadflow, flowop, 0); return (FILEBENCH_OK); } /* * Stop worker thread when specified number of I/O operations have been * transferred. */ static int flowoplib_finishoncount(threadflow_t *threadflow, flowop_t *flowop) { uint64_t ops; uint64_t count = flowop->fo_constvalue; /* use constant value */ if (flowop->fo_initted == 0) { filebench_log(LOG_DEBUG_IMPL, "rate %zx %s-%d locking", flowop, threadflow->tf_name, threadflow->tf_instance); flowop->fo_initted = 1; if (flowoplib_event_find_target(threadflow, flowop) == FILEBENCH_ERROR) return (FILEBENCH_ERROR); } if (flowop->fo_targets) { ops = flowop->fo_targets->fo_stats.fs_count; } else { (void) ipc_mutex_lock(&controlstats_lock); ops = controlstats.fs_count; (void) ipc_mutex_unlock(&controlstats_lock); } flowop_beginop(threadflow, flowop); if (ops >= count) { flowop_endop(threadflow, flowop, 0); return (FILEBENCH_NORSC); } flowop_endop(threadflow, flowop, 0); return (FILEBENCH_OK); } /* * Semaphore synchronization using either System V semaphores or * posix semaphores. If System V semaphores are available, they will be * used, otherwise posix semaphores will be used. */ /* * Initializes the filebench "block on semaphore" flowop. * If System V semaphores are implemented, the routine * initializes the System V semaphore subsystem if it hasn't * already been initialized, also allocates a pair of semids * and initializes the highwater System V semaphore. * If no System V semaphores, then does nothing special. * Returns FILEBENCH_ERROR if it cannot acquire a set of System V semphores * or if the initial post to the semaphore set fails. Returns FILEBENCH_OK * on success. */ static int flowoplib_semblock_init(flowop_t *flowop) { #ifdef HAVE_SYSV_SEM int sys_semid; struct sembuf sbuf[2]; int highwater; ipc_seminit(); flowop->fo_semid_lw = ipc_semidalloc(); flowop->fo_semid_hw = ipc_semidalloc(); filebench_log(LOG_DEBUG_IMPL, "flow %s-%d semblock init semid=%x", flowop->fo_name, flowop->fo_instance, flowop->fo_semid_lw); sys_semid = filebench_shm->shm_sys_semid; if ((highwater = flowop->fo_semid_hw) == 0) highwater = flowop->fo_constvalue; /* use constant value */ filebench_log(LOG_DEBUG_IMPL, "setting highwater to : %d", highwater); sbuf[0].sem_num = (short)highwater; sbuf[0].sem_op = avd_get_int(flowop->fo_highwater); sbuf[0].sem_flg = 0; if ((semop(sys_semid, &sbuf[0], 1) == -1) && errno) { filebench_log(LOG_ERROR, "semblock init post failed: %s (%d," "%d)", strerror(errno), sbuf[0].sem_num, sbuf[0].sem_op); return (FILEBENCH_ERROR); } #else filebench_log(LOG_DEBUG_IMPL, "flow %s-%d semblock init with posix semaphore", flowop->fo_name, flowop->fo_instance); sem_init(&flowop->fo_sem, 1, 0); #endif /* HAVE_SYSV_SEM */ if (!(avd_get_bool(flowop->fo_blocking))) (void) ipc_mutex_unlock(&flowop->fo_lock); return (FILEBENCH_OK); } /* * Releases the semids for the System V semaphore allocated * to this flowop. If not using System V semaphores, then * it is effectively just a no-op. */ static void flowoplib_semblock_destruct(flowop_t *flowop) { #ifdef HAVE_SYSV_SEM ipc_semidfree(flowop->fo_semid_lw); ipc_semidfree(flowop->fo_semid_hw); #else sem_destroy(&flowop->fo_sem); #endif /* HAVE_SYSV_SEM */ } /* * Attempts to pass a System V or posix semaphore as appropriate, * and blocks if necessary. Returns FILEBENCH_ERROR if a set of System V * semphores is not available or cannot be acquired, or if the initial * post to the semaphore set fails. Returns FILEBENCH_OK on success. */ static int flowoplib_semblock(threadflow_t *threadflow, flowop_t *flowop) { #ifdef HAVE_SYSV_SEM struct sembuf sbuf[2]; int value = avd_get_int(flowop->fo_value); int sys_semid; struct timespec timeout; sys_semid = filebench_shm->shm_sys_semid; filebench_log(LOG_DEBUG_IMPL, "flow %s-%d sem blocking on id %x num %x value %d", flowop->fo_name, flowop->fo_instance, sys_semid, flowop->fo_semid_hw, value); /* Post, decrement the increment the hw queue */ sbuf[0].sem_num = flowop->fo_semid_hw; sbuf[0].sem_op = (short)value; sbuf[0].sem_flg = 0; sbuf[1].sem_num = flowop->fo_semid_lw; sbuf[1].sem_op = value * -1; sbuf[1].sem_flg = 0; timeout.tv_sec = 600; timeout.tv_nsec = 0; if (avd_get_bool(flowop->fo_blocking)) (void) ipc_mutex_unlock(&flowop->fo_lock); flowop_beginop(threadflow, flowop); #ifdef HAVE_SEMTIMEDOP (void) semtimedop(sys_semid, &sbuf[0], 1, &timeout); (void) semtimedop(sys_semid, &sbuf[1], 1, &timeout); #else (void) semop(sys_semid, &sbuf[0], 1); (void) semop(sys_semid, &sbuf[1], 1); #endif /* HAVE_SEMTIMEDOP */ if (avd_get_bool(flowop->fo_blocking)) (void) ipc_mutex_lock(&flowop->fo_lock); flowop_endop(threadflow, flowop, 0); #else int value = avd_get_int(flowop->fo_value); int i; filebench_log(LOG_DEBUG_IMPL, "flow %s-%d sem blocking on posix semaphore", flowop->fo_name, flowop->fo_instance); /* Decrement sem by value */ for (i = 0; i < value; i++) { if (sem_wait(&flowop->fo_sem) == -1) { filebench_log(LOG_ERROR, "semop wait failed"); return (FILEBENCH_ERROR); } } filebench_log(LOG_DEBUG_IMPL, "flow %s-%d sem unblocking", flowop->fo_name, flowop->fo_instance); #endif /* HAVE_SYSV_SEM */ return (FILEBENCH_OK); } /* * Calls ipc_seminit(). Always returns FILEBENCH_OK. */ /* ARGSUSED */ static int flowoplib_sempost_init(flowop_t *flowop) { #ifdef HAVE_SYSV_SEM ipc_seminit(); #endif /* HAVE_SYSV_SEM */ return (FILEBENCH_OK); } /* * Post to a System V or posix semaphore as appropriate. * On the first call for a given flowop instance, this routine * will use the fo_targetname attribute to locate all semblock * flowops that are expecting posts from this flowop. All * target flowops on this list will have a post operation done * to their semaphores on each call. */ static int flowoplib_sempost(threadflow_t *threadflow, flowop_t *flowop) { flowop_t *target; filebench_log(LOG_DEBUG_IMPL, "sempost flow %s-%d", flowop->fo_name, flowop->fo_instance); /* if this is the first post, create the post list */ if (flowop->fo_targets == NULL) { flowop_t *result = flowop_find(flowop->fo_targetname); flowop->fo_targets = result; if (result == NULL) { filebench_log(LOG_ERROR, "sempost: could not find op %s for thread %s", flowop->fo_targetname, threadflow->tf_name); filebench_shutdown(1); } while (result) { result->fo_targetnext = result->fo_resultnext; result = result->fo_resultnext; } } target = flowop->fo_targets; flowop_beginop(threadflow, flowop); /* post to the targets */ while (target) { #ifdef HAVE_SYSV_SEM struct sembuf sbuf[2]; int sys_semid; int blocking; #else int i; #endif /* HAVE_SYSV_SEM */ struct timespec timeout; int value = (int)avd_get_int(flowop->fo_value); if (target->fo_instance == FLOW_MASTER) { target = target->fo_targetnext; continue; } #ifdef HAVE_SYSV_SEM filebench_log(LOG_DEBUG_IMPL, "sempost flow %s-%d num %x", target->fo_name, target->fo_instance, target->fo_semid_lw); sys_semid = filebench_shm->shm_sys_semid; sbuf[0].sem_num = target->fo_semid_lw; sbuf[0].sem_op = (short)value; sbuf[0].sem_flg = 0; sbuf[1].sem_num = target->fo_semid_hw; sbuf[1].sem_op = value * -1; sbuf[1].sem_flg = 0; timeout.tv_sec = 600; timeout.tv_nsec = 0; if (avd_get_bool(flowop->fo_blocking)) blocking = 1; else blocking = 0; #ifdef HAVE_SEMTIMEDOP if ((semtimedop(sys_semid, &sbuf[0], blocking + 1, &timeout) == -1) && (errno && (errno != EAGAIN))) { #else if ((semop(sys_semid, &sbuf[0], blocking + 1) == -1) && (errno && (errno != EAGAIN))) { #endif /* HAVE_SEMTIMEDOP */ filebench_log(LOG_ERROR, "semop post failed: %s", strerror(errno)); return (FILEBENCH_ERROR); } filebench_log(LOG_DEBUG_IMPL, "flow %s-%d finished posting", target->fo_name, target->fo_instance); #else filebench_log(LOG_DEBUG_IMPL, "sempost flow %s-%d to posix semaphore", target->fo_name, target->fo_instance); /* Increment sem by value */ for (i = 0; i < value; i++) { if (sem_post(&target->fo_sem) == -1) { filebench_log(LOG_ERROR, "semop post failed"); return (FILEBENCH_ERROR); } } filebench_log(LOG_DEBUG_IMPL, "flow %s-%d unblocking", target->fo_name, target->fo_instance); #endif /* HAVE_SYSV_SEM */ target = target->fo_targetnext; } flowop_endop(threadflow, flowop, 0); return (FILEBENCH_OK); } /* * Section for exercising create / open / close / delete operations * on files within a fileset. For proper operation, the flowop attribute * "fd", which sets the fo_fdnumber field in the flowop, must be used * so that the same file is opened and later closed. "fd" is an index * into a pair of arrays maintained by threadflows, one of which * contains the operating system assigned file descriptors and the other * a pointer to the filesetentry whose file the file descriptor * references. An openfile flowop defined without fd being set will use * the default (0) fd or, if specified, rotate through fd indices, but * createfile and closefile must use the default or a specified fd. * Meanwhile deletefile picks and arbitrary file to delete, regardless * of fd attribute. */ /* * Emulates (and actually does) file open. Obtains a file descriptor * index, then calls flowoplib_openfile_common() to open. Returns * FILEBENCH_ERROR if no file descriptor is found, and returns the * status from flowoplib_openfile_common otherwise (FILEBENCH_ERROR, * FILEBENCH_NORSC, FILEBENCH_OK). */ static int flowoplib_openfile(threadflow_t *threadflow, flowop_t *flowop) { int fd = flowoplib_fdnum(threadflow, flowop); if (fd == -1) return (FILEBENCH_ERROR); return (flowoplib_openfile_common(threadflow, flowop, fd)); } /* * Common file opening code for filesets. Uses the supplied * file descriptor index to determine the tf_fd entry to use. * If the entry is empty (0) and the fileset exists, fileset * pick is called to select a fileset entry to use. The file * specified in the filesetentry is opened, and the returned * operating system file descriptor and a pointer to the * filesetentry are stored in tf_fd[fd] and tf_fse[fd], * respectively. Returns FILEBENCH_ERROR on error, * FILEBENCH_NORSC if no suitable filesetentry can be found, * and FILEBENCH_OK on success. */ static int flowoplib_openfile_common(threadflow_t *threadflow, flowop_t *flowop, int fd) { filesetentry_t *file; char *fileset_name; int tid = 0; int openflag = 0; int err; if (flowop->fo_fileset == NULL) { filebench_log(LOG_ERROR, "flowop NULL file"); return (FILEBENCH_ERROR); } if ((fileset_name = avd_get_str(flowop->fo_fileset->fs_name)) == NULL) { filebench_log(LOG_ERROR, "flowop %s: fileset has no name", flowop->fo_name); return (FILEBENCH_ERROR); } /* * set the open flag for read only or read/write, as appropriate. */ if (avd_get_bool(flowop->fo_fileset->fs_readonly) == TRUE) openflag = O_RDONLY; else if (avd_get_bool(flowop->fo_fileset->fs_writeonly) == TRUE) openflag = O_WRONLY; else openflag = O_RDWR; /* * If the flowop doesn't default to persistent fd * then get unique thread ID for use by fileset_pick */ if (avd_get_bool(flowop->fo_rotatefd)) tid = threadflow->tf_utid; if (threadflow->tf_fd[fd].fd_ptr != NULL) { filebench_log(LOG_ERROR, "flowop %s attempted to open without closing on fd %d", flowop->fo_name, fd); return (FILEBENCH_ERROR); } if (flowop->fo_fileset->fs_attrs & FILESET_IS_RAW_DEV) { int open_attrs = 0; char name[MAXPATHLEN]; (void) fb_strlcpy(name, avd_get_str(flowop->fo_fileset->fs_path), MAXPATHLEN); (void) fb_strlcat(name, "/", MAXPATHLEN); (void) fb_strlcat(name, fileset_name, MAXPATHLEN); if (avd_get_bool(flowop->fo_dsync)) open_attrs |= O_SYNC; #ifdef HAVE_O_DIRECT if (flowoplib_fileattrs(flowop) & FLOW_ATTR_DIRECTIO) open_attrs |= O_DIRECT; #endif /* HAVE_O_DIRECT */ filebench_log(LOG_DEBUG_SCRIPT, "open raw device %s flags %d = %d", name, open_attrs, fd); if (FB_OPEN(&(threadflow->tf_fd[fd]), name, openflag | open_attrs, 0666) == FILEBENCH_ERROR) { filebench_log(LOG_ERROR, "Failed to open raw device %s: %s", name, strerror(errno)); return (FILEBENCH_ERROR); } #ifdef HAVE_DIRECTIO if (flowoplib_fileattrs(flowop) & FLOW_ATTR_DIRECTIO) (void)directio(threadflow->tf_fd[fd].fd_num, DIRECTIO_ON); #endif /* HAVE_DIRECTIO */ #ifdef HAVE_NOCACHE_FCNTL if (flowoplib_fileattrs(flowop) & FLOW_ATTR_DIRECTIO) (void)fcntl(threadflow->tf_fd[fd].fd_num, F_NOCACHE, 1); #endif /* HAVE_NOCACHE_FCNTL */ /* Disable read ahead with the help of fadvise, if asked for */ if (flowoplib_fileattrs(flowop) & FLOW_ATTR_FADV_RANDOM) { #ifdef HAVE_FADVISE if (posix_fadvise(threadflow->tf_fd[fd].fd_num, 0, 0, POSIX_FADV_RANDOM) != FILEBENCH_OK) { filebench_log(LOG_ERROR, "Failed to disable read ahead for raw device %s, with status %s", name, strerror(errno)); return (FILEBENCH_ERROR); } filebench_log(LOG_INFO, "** Read ahead disabled ** "); #else filebench_log(LOG_INFO, "** Read ahead was NOT disabled: not supported on this platform! **"); #endif } threadflow->tf_fse[fd] = NULL; return (FILEBENCH_OK); } if ((err = flowoplib_pickfile(&file, flowop, FILESET_PICKEXISTS, tid)) != FILEBENCH_OK) { filebench_log(LOG_DEBUG_SCRIPT, "flowop %s failed to pick file from %s on fd %d", flowop->fo_name, fileset_name, fd); return (err); } threadflow->tf_fse[fd] = file; flowop_beginop(threadflow, flowop); err = fileset_openfile(&threadflow->tf_fd[fd], flowop->fo_fileset, file, openflag, 0666, flowoplib_fileattrs(flowop)); flowop_endop(threadflow, flowop, 0); if (err == FILEBENCH_ERROR) { filebench_log(LOG_ERROR, "flowop %s failed to open file %s", flowop->fo_name, file->fse_path); return (FILEBENCH_ERROR); } filebench_log(LOG_DEBUG_SCRIPT, "flowop %s: opened %s fd[%d] = %d", flowop->fo_name, file->fse_path, fd, threadflow->tf_fd[fd]); return (FILEBENCH_OK); } /* * Emulate create of a file. Uses the flowoplib_fdnum to select * tf_fd and tf_fse array locations to put the created file's file * descriptor and filesetentry respectively. Uses flowoplib_pickfile() * to select a specific filesetentry whose file does not currently * exist for the file create operation. Then calls * fileset_openfile() with the O_CREATE flag set to create the * file. Returns FILEBENCH_ERROR if the array index specified by fdnumber is * already in use, the flowop has no associated fileset, or * the create call fails. Returns 1 if a filesetentry with a * nonexistent file cannot be found. Returns FILEBENCH_OK on success. */ static int flowoplib_createfile(threadflow_t *threadflow, flowop_t *flowop) { filesetentry_t *file; int openflag = O_CREAT; int fd; int err; fd = flowoplib_fdnum(threadflow, flowop); if (threadflow->tf_fd[fd].fd_ptr != NULL) { filebench_log(LOG_ERROR, "flowop %s attempted to create without closing on fd %d", flowop->fo_name, fd); return (FILEBENCH_ERROR); } if (flowop->fo_fileset == NULL) { filebench_log(LOG_ERROR, "flowop NULL file"); return (FILEBENCH_ERROR); } if (avd_get_bool(flowop->fo_fileset->fs_readonly) == TRUE) openflag |= O_RDONLY; else if (avd_get_bool(flowop->fo_fileset->fs_writeonly) == TRUE) openflag |= O_WRONLY; else openflag |= O_RDWR; /* can't be used with raw devices */ if (flowop->fo_fileset->fs_attrs & FILESET_IS_RAW_DEV) { filebench_log(LOG_ERROR, "flowop %s attempted to a createfile on RAW device", flowop->fo_name); return (FILEBENCH_ERROR); } if ((err = flowoplib_pickfile(&file, flowop, FILESET_PICKNOEXIST, 0)) != FILEBENCH_OK) { filebench_log(LOG_DEBUG_SCRIPT, "flowop %s failed to pick file from fileset %s", flowop->fo_name, avd_get_str(flowop->fo_fileset->fs_name)); return (err); } threadflow->tf_fse[fd] = file; flowop_beginop(threadflow, flowop); err = fileset_openfile(&threadflow->tf_fd[fd], flowop->fo_fileset, file, openflag, 0666, flowoplib_fileattrs(flowop)); flowop_endop(threadflow, flowop, 0); if (err == FILEBENCH_ERROR) { filebench_log(LOG_ERROR, "failed to create file %s", flowop->fo_name); return (FILEBENCH_ERROR); } filebench_log(LOG_DEBUG_SCRIPT, "flowop %s: created %s fd[%d] = %d", flowop->fo_name, file->fse_path, fd, threadflow->tf_fd[fd]); return (FILEBENCH_OK); } /* * Emulates delete of a file. If a valid fd is provided, it uses the * filesetentry stored at that fd location to select the file to be * deleted, otherwise it picks an arbitrary filesetentry * whose file exists. It then uses unlink() to delete it and Clears * the FSE_EXISTS flag for the filesetentry. Returns FILEBENCH_ERROR if the * flowop has no associated fileset. Returns FILEBENCH_NORSC if an appropriate * filesetentry cannot be found, and FILEBENCH_OK on success. */ static int flowoplib_deletefile(threadflow_t *threadflow, flowop_t *flowop) { filesetentry_t *file; fileset_t *fileset; char path[MAXPATHLEN]; char *pathtmp; int fd; fd = flowoplib_fdnum(threadflow, flowop); /* if fd specified, use it to access file */ if ((fd > 0) && ((file = threadflow->tf_fse[fd]) != NULL)) { /* indicate that the file will be deleted */ threadflow->tf_fse[fd] = NULL; /* if here, we still have a valid file pointer */ fileset = file->fse_fileset; } else { /* Otherwise, pick arbitrary file */ file = NULL; fileset = flowop->fo_fileset; } if (fileset == NULL) { filebench_log(LOG_ERROR, "flowop NULL file"); return (FILEBENCH_ERROR); } /* can't be used with raw devices */ if (fileset->fs_attrs & FILESET_IS_RAW_DEV) { filebench_log(LOG_ERROR, "flowop %s attempted a deletefile on RAW device", flowop->fo_name); return (FILEBENCH_ERROR); } if (file == NULL) { int err; /* pick arbitrary, existing (allocated) file */ if ((err = flowoplib_pickfile(&file, flowop, FILESET_PICKEXISTS, 0)) != FILEBENCH_OK) { filebench_log(LOG_DEBUG_SCRIPT, "flowop %s failed to pick file", flowop->fo_name); return (err); } } else { /* delete specific file. wait for it to be non-busy */ (void) ipc_mutex_lock(&fileset->fs_pick_lock); while (file->fse_flags & FSE_BUSY) { file->fse_flags |= FSE_THRD_WAITNG; (void) pthread_cond_wait(&fileset->fs_thrd_wait_cv, &fileset->fs_pick_lock); } /* File now available, grab it for deletion */ file->fse_flags |= FSE_BUSY; fileset->fs_idle_files--; (void) ipc_mutex_unlock(&fileset->fs_pick_lock); } /* don't delete if anyone (other than me) has file open */ if ((fd > 0) && (threadflow->tf_fd[fd].fd_num > 0)) { if (file->fse_open_cnt > 1) { filebench_log(LOG_DEBUG_SCRIPT, "flowop %s can't delete file opened by other" " threads at fd = %d", flowop->fo_name, fd); fileset_unbusy(file, FALSE, FALSE, 0); return (FILEBENCH_OK); } else { filebench_log(LOG_DEBUG_SCRIPT, "flowop %s deleting still open file at fd = %d", flowop->fo_name, fd); } } else if (file->fse_open_cnt > 0) { filebench_log(LOG_DEBUG_SCRIPT, "flowop %s can't delete file opened by other" " threads at fd = %d, open count = %d", flowop->fo_name, fd, file->fse_open_cnt); fileset_unbusy(file, FALSE, FALSE, 0); return (FILEBENCH_OK); } (void) fb_strlcpy(path, avd_get_str(fileset->fs_path), MAXPATHLEN); (void) fb_strlcat(path, "/", MAXPATHLEN); (void) fb_strlcat(path, avd_get_str(fileset->fs_name), MAXPATHLEN); pathtmp = fileset_resolvepath(file); (void) fb_strlcat(path, pathtmp, MAXPATHLEN); free(pathtmp); /* delete the selected file */ flowop_beginop(threadflow, flowop); (void) FB_UNLINK(path); flowop_endop(threadflow, flowop, 0); /* indicate that it is no longer busy and no longer exists */ fileset_unbusy(file, TRUE, FALSE, -file->fse_open_cnt); filebench_log(LOG_DEBUG_SCRIPT, "deleted file %s", file->fse_path); return (FILEBENCH_OK); } /* * Emulates fsync of a file. Obtains the file descriptor index * from the flowop, obtains the actual file descriptor from * the threadflow's table, checks to be sure it is still an * open file, then does an fsync operation on it. Returns FILEBENCH_ERROR * if the file no longer is open, FILEBENCH_OK otherwise. */ static int flowoplib_fsync(threadflow_t *threadflow, flowop_t *flowop) { filesetentry_t *file; int fd; fd = flowoplib_fdnum(threadflow, flowop); if (threadflow->tf_fd[fd].fd_ptr == NULL) { filebench_log(LOG_ERROR, "flowop %s attempted to fsync a closed fd %d", flowop->fo_name, fd); return (FILEBENCH_ERROR); } file = threadflow->tf_fse[fd]; if ((file == NULL) || (file->fse_fileset->fs_attrs & FILESET_IS_RAW_DEV)) { filebench_log(LOG_ERROR, "flowop %s attempted to a fsync a RAW device", flowop->fo_name); return (FILEBENCH_ERROR); } /* Measure time to fsync */ flowop_beginop(threadflow, flowop); (void) FB_FSYNC(&threadflow->tf_fd[fd]); flowop_endop(threadflow, flowop, 0); filebench_log(LOG_DEBUG_SCRIPT, "fsync file %s", file->fse_path); return (FILEBENCH_OK); } /* * Emulate fsync of an entire fileset. Search through the * threadflow's file descriptor array, doing fsync() on each * open file that belongs to the flowop's fileset. Always * returns FILEBENCH_OK. */ static int flowoplib_fsyncset(threadflow_t *threadflow, flowop_t *flowop) { int fd; for (fd = 0; fd < THREADFLOW_MAXFD; fd++) { filesetentry_t *file; /* Match the file set to fsync */ if ((threadflow->tf_fse[fd] == NULL) || (flowop->fo_fileset != threadflow->tf_fse[fd]->fse_fileset)) continue; /* Measure time to fsync */ flowop_beginop(threadflow, flowop); (void) FB_FSYNC(&threadflow->tf_fd[fd]); flowop_endop(threadflow, flowop, 0); file = threadflow->tf_fse[fd]; filebench_log(LOG_DEBUG_SCRIPT, "fsync file %s", file->fse_path); } return (FILEBENCH_OK); } /* * Emulate close of a file. Obtains the file descriptor index * from the flowop, obtains the actual file descriptor from the * threadflow's table, checks to be sure it is still an open * file, then does a close operation on it. Then sets the * threadflow file descriptor table entry to 0, and the file set * entry pointer to NULL. Returns FILEBENCH_ERROR if the file was not open, * FILEBENCH_OK otherwise. */ static int flowoplib_closefile(threadflow_t *threadflow, flowop_t *flowop) { filesetentry_t *file; fileset_t *fileset; int fd; fd = flowoplib_fdnum(threadflow, flowop); if (threadflow->tf_fd[fd].fd_ptr == NULL) { filebench_log(LOG_ERROR, "flowop %s attempted to close an already closed fd %d", flowop->fo_name, fd); return (FILEBENCH_ERROR); } file = threadflow->tf_fse[fd]; fileset = file->fse_fileset; /* Wait for it to be non-busy */ (void) ipc_mutex_lock(&fileset->fs_pick_lock); while (file->fse_flags & FSE_BUSY) { file->fse_flags |= FSE_THRD_WAITNG; (void) pthread_cond_wait(&fileset->fs_thrd_wait_cv, &fileset->fs_pick_lock); } /* File now available, grab it for closing */ file->fse_flags |= FSE_BUSY; /* if last open, set declare idle */ if (file->fse_open_cnt == 1) fileset->fs_idle_files--; (void) ipc_mutex_unlock(&fileset->fs_pick_lock); /* Measure time to close */ flowop_beginop(threadflow, flowop); (void) FB_CLOSE(&threadflow->tf_fd[fd]); flowop_endop(threadflow, flowop, 0); fileset_unbusy(file, FALSE, FALSE, -1); threadflow->tf_fd[fd].fd_ptr = NULL; filebench_log(LOG_DEBUG_SCRIPT, "closed file %s", file->fse_path); return (FILEBENCH_OK); } /* * Obtain the full pathname of the directory described by the filesetentry * indicated by "dir", and copy it into the character array pointed to by * path. Returns FILEBENCH_ERROR on errors, FILEBENCH_OK otherwise. */ static int flowoplib_getdirpath(filesetentry_t *dir, char *path) { char *fileset_path; char *fileset_name; char *part_path; if ((fileset_path = avd_get_str(dir->fse_fileset->fs_path)) == NULL) { filebench_log(LOG_ERROR, "Fileset path not set"); return (FILEBENCH_ERROR); } if ((fileset_name = avd_get_str(dir->fse_fileset->fs_name)) == NULL) { filebench_log(LOG_ERROR, "Fileset name not set"); return (FILEBENCH_ERROR); } (void) fb_strlcpy(path, fileset_path, MAXPATHLEN); (void) fb_strlcat(path, "/", MAXPATHLEN); (void) fb_strlcat(path, fileset_name, MAXPATHLEN); if ((part_path = fileset_resolvepath(dir)) == NULL) return (FILEBENCH_ERROR); (void) fb_strlcat(path, part_path, MAXPATHLEN); free(part_path); return (FILEBENCH_OK); } /* * Use mkdir to create a directory. Obtains the fileset name from the * flowop, selects a non-existent leaf directory and obtains its full * path, then uses mkdir to create it on the storage subsystem (make it * existent). Returns FILEBENCH_NORSC is there are no more non-existent * directories in the fileset, FILEBENCH_ERROR on other errors, and * FILEBENCH_OK on success. */ static int flowoplib_makedir(threadflow_t *threadflow, flowop_t *flowop) { filesetentry_t *dir; int ret; char full_path[MAXPATHLEN]; if ((ret = flowoplib_pickleafdir(&dir, flowop, FILESET_PICKNOEXIST)) != FILEBENCH_OK) return (ret); if ((ret = flowoplib_getdirpath(dir, full_path)) != FILEBENCH_OK) return (ret); flowop_beginop(threadflow, flowop); (void) FB_MKDIR(full_path, 0755); flowop_endop(threadflow, flowop, 0); /* indicate that it is no longer busy and now exists */ fileset_unbusy(dir, TRUE, TRUE, 0); return (FILEBENCH_OK); } /* * Use rmdir to delete a directory. Obtains the fileset name from the * flowop, selects an existent leaf directory and obtains its full path, * then uses rmdir to remove it from the storage subsystem (make it * non-existent). Returns FILEBENCH_NORSC is there are no more existent * directories in the fileset, FILEBENCH_ERROR on other errors, and * FILEBENCH_OK on success. */ static int flowoplib_removedir(threadflow_t *threadflow, flowop_t *flowop) { filesetentry_t *dir; int ret; char full_path[MAXPATHLEN]; if ((ret = flowoplib_pickleafdir(&dir, flowop, FILESET_PICKEXISTS)) != FILEBENCH_OK) return (ret); if ((ret = flowoplib_getdirpath(dir, full_path)) != FILEBENCH_OK) return (ret); flowop_beginop(threadflow, flowop); (void) FB_RMDIR(full_path); flowop_endop(threadflow, flowop, 0); /* indicate that it is no longer busy and no longer exists */ fileset_unbusy(dir, TRUE, FALSE, 0); return (FILEBENCH_OK); } /* * Use opendir(), multiple readdir() calls, and closedir() to list the * contents of a directory. Obtains the fileset name from the * flowop, selects a normal subdirectory (which always exist) and obtains * its full path, then uses opendir() to get a DIR handle to it from the * file system, a readdir() loop to access each directory entry, and * finally cleans up with a closedir(). The latency reported is the total * for all this activity, and it also reports the total number of bytes * in the entries as the amount "read". Returns FILEBENCH_ERROR on errors, * and FILEBENCH_OK on success. */ static int flowoplib_listdir(threadflow_t *threadflow, flowop_t *flowop) { fileset_t *fileset; filesetentry_t *dir; DIR *dir_handle; struct dirent *direntp; int dir_bytes = 0; int ret; char full_path[MAXPATHLEN]; if ((fileset = flowop->fo_fileset) == NULL) { filebench_log(LOG_ERROR, "flowop NO fileset"); return (FILEBENCH_ERROR); } if ((dir = fileset_pick(fileset, FILESET_PICKDIR, 0, 0)) == NULL) { filebench_log(LOG_DEBUG_SCRIPT, "flowop %s failed to pick directory from fileset %s", flowop->fo_name, avd_get_str(fileset->fs_name)); return (FILEBENCH_ERROR); } if ((ret = flowoplib_getdirpath(dir, full_path)) != FILEBENCH_OK) return (ret); flowop_beginop(threadflow, flowop); /* open the directory */ if ((dir_handle = FB_OPENDIR(full_path)) == NULL) { filebench_log(LOG_ERROR, "flowop %s failed to open directory in fileset %s\n", flowop->fo_name, avd_get_str(fileset->fs_name)); return (FILEBENCH_ERROR); } /* read through the directory entries */ while ((direntp = FB_READDIR(dir_handle)) != NULL) { dir_bytes += (strlen(direntp->d_name) + sizeof (struct dirent) - 1); } /* close the directory */ (void) FB_CLOSEDIR(dir_handle); flowop_endop(threadflow, flowop, dir_bytes); /* indicate that it is no longer busy */ fileset_unbusy(dir, FALSE, FALSE, 0); return (FILEBENCH_OK); } /* * Emulate stat of a file. Picks an arbitrary filesetentry with * an existing file from the flowop's fileset, then performs a * stat() operation on it. Returns FILEBENCH_ERROR if the flowop has no * associated fileset. Returns FILEBENCH_NORSC if an appropriate filesetentry * cannot be found, and FILEBENCH_OK on success. */ static int flowoplib_statfile(threadflow_t *threadflow, flowop_t *flowop) { filesetentry_t *file; fileset_t *fileset; struct stat64 statbuf; int fd; fd = flowoplib_fdnum(threadflow, flowop); /* if fd specified and the file is open, use it to access file */ if ((fd > 0) && (threadflow->tf_fd[fd].fd_num > 0)) { /* check whether file handle still valid */ if ((file = threadflow->tf_fse[fd]) == NULL) { filebench_log(LOG_DEBUG_SCRIPT, "flowop %s trying to stat NULL file at fd = %d", flowop->fo_name, fd); return (FILEBENCH_ERROR); } /* if here, we still have a valid file pointer */ fileset = file->fse_fileset; } else { /* Otherwise, pick arbitrary file */ file = NULL; fileset = flowop->fo_fileset; } if (fileset == NULL) { filebench_log(LOG_ERROR, "statfile with no fileset specified"); return (FILEBENCH_ERROR); } /* can't be used with raw devices */ if (fileset->fs_attrs & FILESET_IS_RAW_DEV) { filebench_log(LOG_ERROR, "flowop %s attempted do a statfile on a RAW device", flowop->fo_name); return (FILEBENCH_ERROR); } if (file == NULL) { char path[MAXPATHLEN]; char *pathtmp; int err; /* pick arbitrary, existing (allocated) file */ if ((err = flowoplib_pickfile(&file, flowop, FILESET_PICKEXISTS, 0)) != FILEBENCH_OK) { filebench_log(LOG_DEBUG_SCRIPT, "Statfile flowop %s failed to pick file", flowop->fo_name); return (err); } /* resolve path and do a stat on file */ (void) fb_strlcpy(path, avd_get_str(fileset->fs_path), MAXPATHLEN); (void) fb_strlcat(path, "/", MAXPATHLEN); (void) fb_strlcat(path, avd_get_str(fileset->fs_name), MAXPATHLEN); pathtmp = fileset_resolvepath(file); (void) fb_strlcat(path, pathtmp, MAXPATHLEN); free(pathtmp); /* stat the file */ flowop_beginop(threadflow, flowop); if (FB_STAT(path, &statbuf) == -1) filebench_log(LOG_ERROR, "statfile flowop %s failed", flowop->fo_name); flowop_endop(threadflow, flowop, 0); fileset_unbusy(file, FALSE, FALSE, 0); } else { /* stat specific file */ flowop_beginop(threadflow, flowop); if (FB_FSTAT(&threadflow->tf_fd[fd], &statbuf) == -1) filebench_log(LOG_ERROR, "statfile flowop %s failed", flowop->fo_name); flowop_endop(threadflow, flowop, 0); } return (FILEBENCH_OK); } /* * Additional reads and writes. Read and write whole files, write * and append to files. Some of these work with both fileobjs and * filesets, others only with filesets. The flowoplib_write routine * writes from thread memory, while the others read or write using * fo_buf memory. Note that both flowoplib_read() and * flowoplib_aiowrite() use thread memory as well. */ /* * Emulate a read of a whole file. The file must be open with * file descriptor and filesetentry stored at the locations indexed * by the flowop's fdnumber. It then seeks to the beginning of the * associated file, and reads fs_iosize bytes at a time until the end * of the file. Returns FILEBENCH_ERROR on error, FILEBENCH_NORSC if * out of files, and FILEBENCH_OK on success. */ static int flowoplib_readwholefile(threadflow_t *threadflow, flowop_t *flowop) { caddr_t iobuf; off64_t bytes = 0; fb_fdesc_t *fdesc; uint64_t wss; fbint_t iosize; int ret; char zerordbuf; /* get the file to use */ if ((ret = flowoplib_filesetup(threadflow, flowop, &wss, &fdesc)) != FILEBENCH_OK) return (ret); /* an I/O size of zero means read entire working set with one I/O */ if ((iosize = avd_get_int(flowop->fo_iosize)) == 0) iosize = wss; /* * The file may actually be 0 bytes long, in which case skip * the buffer set up call (which would fail) and substitute * a small buffer, which won't really be used. */ if (iosize == 0) { iobuf = (caddr_t)&zerordbuf; filebench_log(LOG_DEBUG_SCRIPT, "flowop %s read zero length file", flowop->fo_name); } else { if (flowoplib_iobufsetup(threadflow, flowop, &iobuf, iosize) != 0) return (FILEBENCH_ERROR); } /* Measure time to read bytes */ flowop_beginop(threadflow, flowop); (void) FB_LSEEK(fdesc, 0, SEEK_SET); while ((ret = FB_READ(fdesc, iobuf, iosize)) > 0) bytes += ret; flowop_endop(threadflow, flowop, bytes); if (ret < 0) { filebench_log(LOG_ERROR, "readwhole fail Failed to read whole file: %s", strerror(errno)); return (FILEBENCH_ERROR); } return (FILEBENCH_OK); } /* * Emulate a write to a file of size fo_iosize. Will write * to a file from a fileset if the flowop's fo_fileset field * specifies one or its fdnumber is non zero. Otherwise it * will write to a fileobj file, if one exists. If the file * is not currently open, the routine will attempt to open * it. The flowop's fo_wss parameter will be used to set the * maximum file size if it is non-zero, otherwise the * filesetentry's fse_size will be used. A random memory * buffer offset is calculated, and, if fo_random is TRUE, * a random file offset is used for the write. Otherwise the * write is to the next sequential location. Returns * FILEBENCH_ERROR on errors, FILEBENCH_NORSC if iosetup can't * obtain a file, or FILEBENCH_OK on success. */ static int flowoplib_write(threadflow_t *threadflow, flowop_t *flowop) { caddr_t iobuf; fbint_t wss; fbint_t iosize; fb_fdesc_t *fdesc; int ret; iosize = avd_get_int(flowop->fo_iosize); if ((ret = flowoplib_iosetup(threadflow, flowop, &wss, &iobuf, &fdesc, iosize)) != FILEBENCH_OK) return (ret); if (avd_get_bool(flowop->fo_random)) { uint64_t fileoffset; if (wss < iosize) { filebench_log(LOG_ERROR, "file size smaller than IO size for thread %s", flowop->fo_name); return (FILEBENCH_ERROR); } /* select randomly */ fb_random64(&fileoffset, wss, iosize, NULL); flowop_beginop(threadflow, flowop); if (FB_PWRITE(fdesc, iobuf, iosize, (off64_t)fileoffset) == -1) { filebench_log(LOG_ERROR, "write failed, " "offset %llu io buffer %zd: %s", (u_longlong_t)fileoffset, iobuf, strerror(errno)); flowop_endop(threadflow, flowop, 0); return (FILEBENCH_ERROR); } flowop_endop(threadflow, flowop, iosize); } else { flowop_beginop(threadflow, flowop); if (FB_WRITE(fdesc, iobuf, iosize) == -1) { filebench_log(LOG_ERROR, "write failed, io buffer %zd: %s", iobuf, strerror(errno)); flowop_endop(threadflow, flowop, 0); return (FILEBENCH_ERROR); } flowop_endop(threadflow, flowop, iosize); } return (FILEBENCH_OK); } /* * Emulate a write of a whole file. The size of the file * is taken from a filesetentry identified by fo_srcfdnumber or * from the working set size, while the file descriptor used is * identified by fo_fdnumber. Does multiple writes of fo_iosize * length length until full file has been written. Returns FILEBENCH_ERROR on * error, FILEBENCH_NORSC if out of files, FILEBENCH_OK on success. */ static int flowoplib_writewholefile(threadflow_t *threadflow, flowop_t *flowop) { caddr_t iobuf; filesetentry_t *file; int wsize; off64_t seek; off64_t bytes = 0; uint64_t wss; fbint_t iosize; fb_fdesc_t *fdesc; int srcfd = flowop->fo_srcfdnumber; int ret; char zerowrtbuf; /* get the file to use */ if ((ret = flowoplib_filesetup(threadflow, flowop, &wss, &fdesc)) != FILEBENCH_OK) return (ret); /* an I/O size of zero means write entire working set with one I/O */ if ((iosize = avd_get_int(flowop->fo_iosize)) == 0) iosize = wss; /* * The file may actually be 0 bytes long, in which case skip * the buffer set up call (which would fail) and substitute * a small buffer, which won't really be used. */ if (iosize == 0) { iobuf = (caddr_t)&zerowrtbuf; filebench_log(LOG_DEBUG_SCRIPT, "flowop %s wrote zero length file", flowop->fo_name); } else { if (flowoplib_iobufsetup(threadflow, flowop, &iobuf, iosize) != 0) return (FILEBENCH_ERROR); } file = threadflow->tf_fse[srcfd]; if ((srcfd != 0) && (file == NULL)) { filebench_log(LOG_ERROR, "flowop %s: NULL src file", flowop->fo_name); return (FILEBENCH_ERROR); } if (file) wss = file->fse_size; wsize = (int)MIN(wss, iosize); /* Measure time to write bytes */ flowop_beginop(threadflow, flowop); for (seek = 0; seek < wss; seek += wsize) { ret = FB_WRITE(fdesc, iobuf, wsize); if (ret != wsize) { filebench_log(LOG_ERROR, "Failed to write %d bytes on fd %d: %s", wsize, fdesc->fd_num, strerror(errno)); flowop_endop(threadflow, flowop, 0); return (FILEBENCH_ERROR); } wsize = (int)MIN(wss - seek, iosize); bytes += ret; } flowop_endop(threadflow, flowop, bytes); return (FILEBENCH_OK); } /* * Emulate a fixed size append to a file. Will append data to * a file chosen from a fileset if the flowop's fo_fileset * field specifies one or if its fdnumber is non zero. * Otherwise it will write to a fileobj file, if one exists. * The flowop's fo_wss parameter will be used to set the * maximum file size if it is non-zero, otherwise the * filesetentry's fse_size will be used. A random memory * buffer offset is calculated, then a logical seek to the * end of file is done followed by a write of fo_iosize * bytes. Writes are actually done from fo_buf, rather than * tf_mem as is done with flowoplib_write(), and no check * is made to see if fo_iosize exceeds the size of fo_buf. * Returns FILEBENCH_ERROR on error, FILEBENCH_NORSC if out of * files in the fileset, FILEBENCH_OK on success. */ static int flowoplib_appendfile(threadflow_t *threadflow, flowop_t *flowop) { caddr_t iobuf; fb_fdesc_t *fdesc; fbint_t wss; fbint_t iosize; int ret; iosize = avd_get_int(flowop->fo_iosize); if ((ret = flowoplib_iosetup(threadflow, flowop, &wss, &iobuf, &fdesc, iosize)) != FILEBENCH_OK) return (ret); /* XXX wss is not being used */ /* Measure time to write bytes */ flowop_beginop(threadflow, flowop); (void) FB_LSEEK(fdesc, 0, SEEK_END); ret = FB_WRITE(fdesc, iobuf, iosize); if (ret != iosize) { filebench_log(LOG_ERROR, "Failed to write %llu bytes on fd %d: %s", (u_longlong_t)iosize, fdesc->fd_num, strerror(errno)); flowop_endop(threadflow, flowop, ret); return (FILEBENCH_ERROR); } flowop_endop(threadflow, flowop, ret); return (FILEBENCH_OK); } /* * Emulate a random size append to a file. Will append data * to a file chosen from a fileset if the flowop's fo_fileset * field specifies one or if its fdnumber is non zero. Otherwise * it will write to a fileobj file, if one exists. The flowop's * fo_wss parameter will be used to set the maximum file size * if it is non-zero, otherwise the filesetentry's fse_size * will be used. A random transfer size (but at most fo_iosize * bytes) and a random memory offset are calculated. A logical * seek to the end of file is done, then writes of up to * FILE_ALLOC_BLOCK in size are done until the full transfer * size has been written. Writes are actually done from fo_buf, * rather than tf_mem as is done with flowoplib_write(). * Returns FILEBENCH_ERROR on error, FILEBENCH_NORSC if out of * files in the fileset, FILEBENCH_OK on success. */ static int flowoplib_appendfilerand(threadflow_t *threadflow, flowop_t *flowop) { caddr_t iobuf; uint64_t appendsize; fb_fdesc_t *fdesc; fbint_t wss; fbint_t iosize; int ret = 0; if ((iosize = avd_get_int(flowop->fo_iosize)) == 0) { filebench_log(LOG_ERROR, "zero iosize for flowop %s", flowop->fo_name); return (FILEBENCH_ERROR); } fb_random64(&appendsize, iosize, 1LL, NULL); /* skip if attempting zero length append */ if (appendsize == 0) { flowop_beginop(threadflow, flowop); flowop_endop(threadflow, flowop, 0LL); return (FILEBENCH_OK); } if ((ret = flowoplib_iosetup(threadflow, flowop, &wss, &iobuf, &fdesc, appendsize)) != FILEBENCH_OK) return (ret); /* XXX wss is not being used */ /* Measure time to write bytes */ flowop_beginop(threadflow, flowop); (void) FB_LSEEK(fdesc, 0, SEEK_END); ret = FB_WRITE(fdesc, iobuf, appendsize); if (ret != appendsize) { filebench_log(LOG_ERROR, "Failed to write %llu bytes on fd %d: %s", (u_longlong_t)appendsize, fdesc->fd_num, strerror(errno)); flowop_endop(threadflow, flowop, 0); return (FILEBENCH_ERROR); } flowop_endop(threadflow, flowop, appendsize); return (FILEBENCH_OK); } typedef struct testrandvar_priv { uint64_t sample_count; double val_sum; double sqr_sum; } testrandvar_priv_t; /* * flowop to calculate various statistics from the number stream * produced by a random variable. This allows verification that the * random distribution used to define the random variable is producing * the expected distribution of random numbers. */ /* ARGSUSED */ static int flowoplib_testrandvar(threadflow_t *threadflow, flowop_t *flowop) { testrandvar_priv_t *mystats; double value; if ((mystats = (testrandvar_priv_t *)flowop->fo_private) == NULL) { filebench_log(LOG_ERROR, "testrandvar not initialized\n"); filebench_shutdown(1); return (-1); } value = avd_get_dbl(flowop->fo_value); mystats->sample_count++; mystats->val_sum += value; mystats->sqr_sum += (value * value); return (0); } /* * Initialize the private data area used to accumulate the statistics */ static int flowoplib_testrandvar_init(flowop_t *flowop) { testrandvar_priv_t *mystats; if ((mystats = (testrandvar_priv_t *) malloc(sizeof (testrandvar_priv_t))) == NULL) { filebench_log(LOG_ERROR, "could not initialize testrandvar"); filebench_shutdown(1); return (-1); } mystats->sample_count = 0; mystats->val_sum = 0; mystats->sqr_sum = 0; flowop->fo_private = (void *)mystats; (void) ipc_mutex_unlock(&flowop->fo_lock); return (0); } /* * Print out the accumulated statistics, and free the private storage */ static void flowoplib_testrandvar_destruct(flowop_t *flowop) { testrandvar_priv_t *mystats; double mean, std_dev, dbl_count; (void) ipc_mutex_lock(&flowop->fo_lock); if ((mystats = (testrandvar_priv_t *) flowop->fo_private) == NULL) { (void) ipc_mutex_unlock(&flowop->fo_lock); return; } flowop->fo_private = NULL; (void) ipc_mutex_unlock(&flowop->fo_lock); dbl_count = (double)mystats->sample_count; mean = mystats->val_sum / dbl_count; std_dev = sqrt((mystats->sqr_sum / dbl_count) - (mean * mean)) / mean; filebench_log(LOG_VERBOSE, "testrandvar: ops = %llu, mean = %8.2lf, stddev = %8.2lf", (u_longlong_t)mystats->sample_count, mean, std_dev); free(mystats); } /* * prints message to the console from within a thread */ static int flowoplib_print(threadflow_t *threadflow, flowop_t *flowop) { procflow_t *procflow; procflow = threadflow->tf_process; filebench_log(LOG_INFO, "Message from process (%s,%d), thread (%s,%d): %s", procflow->pf_name, procflow->pf_instance, threadflow->tf_name, threadflow->tf_instance, avd_get_str(flowop->fo_value)); return (FILEBENCH_OK); }
78,364
28.933155
96
c
filebench
filebench-master/fsplug.h
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * */ #ifndef _FB_FSPLUG_H #define _FB_FSPLUG_H #include "filebench.h" /* * Type of file system client plug-in desired. */ typedef enum fb_plugin_type { LOCAL_FS_PLUG = 0, NFS3_PLUG, NFS4_PLUG, CIFS_PLUG } fb_plugin_type_t; /* universal file descriptor for both local and nfs file systems */ typedef union fb_fdesc { int fd_num; /* OS file descriptor number */ void *fd_ptr; /* Pointer to nfs information block */ } fb_fdesc_t; typedef struct aiolist aiol_t; /* Functions vector for file system plug-ins */ typedef struct fsplug_func_s { char fs_name[16]; int (*fsp_freemem)(fb_fdesc_t *, off64_t); int (*fsp_open)(fb_fdesc_t *, char *, int, int); int (*fsp_pread)(fb_fdesc_t *, caddr_t, fbint_t, off64_t); int (*fsp_read)(fb_fdesc_t *, caddr_t, fbint_t); int (*fsp_pwrite)(fb_fdesc_t *, caddr_t, fbint_t, off64_t); int (*fsp_write)(fb_fdesc_t *, caddr_t, fbint_t); int (*fsp_lseek)(fb_fdesc_t *, off64_t, int); int (*fsp_ftrunc)(fb_fdesc_t *, off64_t); int (*fsp_rename)(const char *, const char *); int (*fsp_close)(fb_fdesc_t *); int (*fsp_link)(const char *, const char *); int (*fsp_symlink)(const char *, const char *); int (*fsp_unlink)(char *); ssize_t (*fsp_readlink)(const char *, char *, size_t); int (*fsp_mkdir)(char *, int); int (*fsp_rmdir)(char *); DIR *(*fsp_opendir)(char *); struct dirent *(*fsp_readdir)(DIR *); int (*fsp_closedir)(DIR *); int (*fsp_fsync)(fb_fdesc_t *); int (*fsp_stat)(char *, struct stat64 *); int (*fsp_fstat)(fb_fdesc_t *, struct stat64 *); int (*fsp_access)(const char *, int); void (*fsp_recur_rm)(char *); } fsplug_func_t; extern fsplug_func_t *fs_functions_vec; /* Macros for calling functions */ #define FB_FREEMEM(fd, sz) \ (*fs_functions_vec->fsp_freemem)(fd, sz) #define FB_OPEN(fd, path, flags, perms) \ (*fs_functions_vec->fsp_open)(fd, path, flags, perms) #define FB_PREAD(fdesc, iobuf, iosize, offset) \ (*fs_functions_vec->fsp_pread)(fdesc, iobuf, iosize, offset) #define FB_READ(fdesc, iobuf, iosize) \ (*fs_functions_vec->fsp_read)(fdesc, iobuf, iosize) #define FB_PWRITE(fdesc, iobuf, iosize, offset) \ (*fs_functions_vec->fsp_pwrite)(fdesc, iobuf, iosize, offset) #define FB_WRITE(fdesc, iobuf, iosize) \ (*fs_functions_vec->fsp_write)(fdesc, iobuf, iosize) #define FB_LSEEK(fdesc, amnt, whence) \ (*fs_functions_vec->fsp_lseek)(fdesc, amnt, whence) #define FB_CLOSE(fdesc) \ (*fs_functions_vec->fsp_close)(fdesc) #define FB_UNLINK(path) \ (*fs_functions_vec->fsp_unlink)(path) #define FB_MKDIR(path, perm) \ (*fs_functions_vec->fsp_mkdir)(path, perm) #define FB_RMDIR(path) \ (*fs_functions_vec->fsp_rmdir)(path) #define FB_OPENDIR(path) \ (*fs_functions_vec->fsp_opendir)(path) #define FB_READDIR(dir) \ (*fs_functions_vec->fsp_readdir)(dir) #define FB_CLOSEDIR(dir) \ (*fs_functions_vec->fsp_closedir)(dir) #define FB_FSYNC(fdesc) \ (*fs_functions_vec->fsp_fsync)(fdesc) #define FB_RECUR_RM(path) \ (*fs_functions_vec->fsp_recur_rm)(path) #define FB_STAT(path, statp) \ (*fs_functions_vec->fsp_stat)(path, statp) #define FB_FSTAT(fdesc, statp) \ (*fs_functions_vec->fsp_fstat)(fdesc, statp) #define FB_FTRUNC(fdesc, size) \ (*fs_functions_vec->fsp_ftrunc)(fdesc, size) #define FB_LINK(existing, new) \ (*fs_functions_vec->fsp_link)(existing, new) #define FB_SYMLINK(name1, name2) \ (*fs_functions_vec->fsp_symlink)(name1, name2) #endif /* _FB_FSPLUG_H */
4,327
28.442177
70
h
filebench
filebench-master/gamma_dist.c
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #pragma ident "%Z%%M% %I% %E% SMI" #include <stdlib.h> #include <math.h> /* * This is valid for 0 < a <= 1 * * From Knuth Volume 2, 3rd edition, pages 586 - 587. */ static double gamma_dist_knuth_algG(double a, double (*src)(unsigned short *), unsigned short *xi) { double p, U, V, X, q; p = M_E/(a + M_E); G2: /* get a random number U */ U = (*src)(xi); do { /* get a random number V */ V = (*src)(xi); } while (V == 0); if (U < p) { X = pow(V, 1/a); /* q = e^(-X) */ q = exp(-X); } else { X = 1 - log(V); q = pow(X, a-1); } /* * X now has density g, and q = f(X)/cg(X) */ /* get a random number U */ U = (*src)(xi); if (U >= q) goto G2; return (X); } /* * This is valid for a > 1 * * From Knuth Volume 2, 3rd edition, page 134. */ static double gamma_dist_knuth_algA(double a, double (*src)(unsigned short *), unsigned short *xi) { double U, Y, X, V; A1: /* get a random number U */ U = (*src)(xi); Y = tan(M_PI*U); X = (sqrt((2*a) - 1) * Y) + a - 1; if (X <= 0) goto A1; /* get a random number V */ V = (*src)(xi); if (V > ((1 + (Y*Y)) * exp((a-1) * log(X/(a-1)) - sqrt(2*a -1) * Y))) goto A1; return (X); } /* * fetch a uniformly distributed random number using the drand48 generator */ /* ARGSUSED */ static double default_src(unsigned short *xi) { return (drand48()); } /* * Sample the gamma distributed random variable with gamma 'a' and * result mulitplier 'b', which is usually mean/gamma. Uses the default * drand48 random number generator as input */ double gamma_dist_knuth(double a, double b) { if (a <= 1.0) return (b * gamma_dist_knuth_algG(a, default_src, NULL)); else return (b * gamma_dist_knuth_algA(a, default_src, NULL)); } /* * Sample the gamma distributed random variable with gamma 'a' and * multiplier 'b', which is mean / gamma adjusted for the specified * minimum value. The suppled random number source function is * used to optain the uniformly distributed random numbers. */ double gamma_dist_knuth_src(double a, double b, double (*src)(unsigned short *), unsigned short *xi) { if (a <= 1.0) return (b * gamma_dist_knuth_algG(a, src, xi)); else return (b * gamma_dist_knuth_algA(a, src, xi)); }
3,163
21.125874
74
c
filebench
filebench-master/gamma_dist.h
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _FB_GAMMA_DIST_H #define _FB_GAMMA_DIST_H #pragma ident "%Z%%M% %I% %E% SMI" #include "filebench.h" double gamma_dist_knuth(double a, double b); double gamma_dist_knuth_src(double a, double b, double (*src)(unsigned short *), unsigned short *xi); #endif /* _FB_GAMMA_DIST_H */
1,220
31.131579
70
h
filebench
filebench-master/ioprio.c
#include "filebench.h" #include "ioprio.h" #ifdef HAVE_IOPRIO static inline int ioprio_set(int which, int who, int ioprio) { return syscall(__NR_ioprio_set, which, who, ioprio); } static inline int ioprio_get(int which, int who) { return syscall(__NR_ioprio_get, which, who); } enum { IOPRIO_CLASS_NONE, IOPRIO_CLASS_RT, IOPRIO_CLASS_BE, IOPRIO_CLASS_IDLE, }; enum { IOPRIO_WHO_PROCESS = 1, IOPRIO_WHO_PGRP, IOPRIO_WHO_USER, }; #define IOPRIO_CLASS_SHIFT 13 void set_thread_ioprio(threadflow_t *tf) { int ret; int ioprio = avd_get_int(tf->tf_ioprio); if (ioprio > 7) return; ret = ioprio_set(IOPRIO_WHO_PROCESS, 0, ioprio | IOPRIO_CLASS_BE << IOPRIO_CLASS_SHIFT); if (ret) { filebench_log(LOG_ERROR, "set_thread_ioprio: error while setting ioprio!"); return; } ioprio = ioprio_get(IOPRIO_WHO_PROCESS, 0); ioprio = ioprio & 0xff; filebench_log(LOG_INFO, "ioprio set to %d for thread %s", ioprio, tf->tf_name); } #endif /* HAVE_IOPRIO */
980
17.509434
77
c
filebench
filebench-master/ioprio.h
#ifndef _FB_IOPRIO_H #define _FB_IOPRIO_H #ifdef HAVE_IOPRIO #include <asm/unistd.h> extern void set_thread_ioprio(threadflow_t *); #else static inline void set_thread_ioprio(threadflow_t *tf) { return; } #endif #endif /* _FB_IOPRIO_H */
241
15.133333
54
h
filebench
filebench-master/ipc.c
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ /* IPC Hub and Simple memory allocator */ #include "config.h" #include <stdio.h> #include <fcntl.h> #include <sys/mman.h> #include <sys/ipc.h> #include <sys/sem.h> #include <sys/errno.h> #include <signal.h> #include <pthread.h> #include <sys/shm.h> #include "filebench.h" #include "fb_cvar.h" filebench_shm_t *filebench_shm = NULL; char shmpath[128] = "/tmp/filebench-shm-XXXXXX"; /* * Interprocess Communication mechanisms. If multiple processes * are used, filebench opens a shared file in memory mapped mode to hold * a variety of global variables and data structures. If only using * multiple threads, it just allocates a region of local memory. A * region of interprocess shared memory and a set of shared semaphores * are also created. Routines are provided to manage the creation, * destruction, and allocation of these resoures. */ /* * Locks a mutex and logs any errors. */ int ipc_mutex_lock(pthread_mutex_t *mutex) { int error; error = pthread_mutex_lock(mutex); #ifdef HAVE_ROBUST_MUTEX if (error == EOWNERDEAD) { if (pthread_mutex_consistent_np(mutex) != 0) { filebench_log(LOG_FATAL, "mutex make consistent " "failed: %s", strerror(error)); return (-1); } return (0); } #endif /* HAVE_ROBUST_MUTEX */ if (error != 0) { filebench_log(LOG_FATAL, "mutex lock failed: %s", strerror(error)); } return (error); } /* * Unlocks a mutex and logs any errors. */ int ipc_mutex_unlock(pthread_mutex_t *mutex) { int error; error = pthread_mutex_unlock(mutex); #ifdef HAVE_ROBUST_MUTEX if (error == EOWNERDEAD) { if (pthread_mutex_consistent_np(mutex) != 0) { filebench_log(LOG_FATAL, "mutex make consistent " "failed: %s", strerror(error)); return (-1); } return (0); } #endif /* HAVE_ROBUST_MUTEX */ if (error != 0) { filebench_log(LOG_FATAL, "mutex unlock failed: %s", strerror(error)); } return (error); } /* * Initialize mutex attributes for the various flavors of mutexes */ static void ipc_mutexattr_init(int mtx_type) { pthread_mutexattr_t *mtx_attrp; mtx_attrp = &(filebench_shm->shm_mutexattr[mtx_type]); (void) pthread_mutexattr_init(mtx_attrp); #ifdef HAVE_PROCSCOPE_PTHREADS if (pthread_mutexattr_setpshared(mtx_attrp, PTHREAD_PROCESS_SHARED) != 0) { filebench_log(LOG_ERROR, "cannot set mutex attr " "PROCESS_SHARED on this platform"); // filebench_shutdown(1); } #ifdef HAVE_PTHREAD_MUTEXATTR_SETPROTOCOL if (mtx_type & IPC_MUTEX_PRIORITY) { if (pthread_mutexattr_setprotocol(mtx_attrp, PTHREAD_PRIO_INHERIT) != 0) { filebench_log(LOG_ERROR, "cannot set mutex attr " "PTHREAD_PRIO_INHERIT on this platform"); // filebench_shutdown(1); } } #endif /* HAVE_PTHREAD_MUTEXATTR_SETPROTOCOL */ #endif /* HAVE_PROCSCOPE_PTHREADS */ #ifdef HAVE_ROBUST_MUTEX if (mtx_type & IPC_MUTEX_ROBUST) { if (pthread_mutexattr_setrobust_np(mtx_attrp, PTHREAD_MUTEX_ROBUST_NP) != 0) { filebench_log(LOG_ERROR, "cannot set mutex attr " "PTHREAD_MUTEX_ROBUST_NP on this platform"); filebench_shutdown(1); } if (pthread_mutexattr_settype(mtx_attrp, PTHREAD_MUTEX_ERRORCHECK) != 0) { filebench_log(LOG_ERROR, "cannot set mutex attr " "PTHREAD_MUTEX_ERRORCHECK " "on this platform"); filebench_shutdown(1); } } #endif /* HAVE_ROBUST_MUTEX */ } /* * On first invocation, allocates a mutex attributes structure * and initializes it with appropriate attributes. In all cases, * returns a pointer to the structure. */ pthread_mutexattr_t * ipc_mutexattr(int mtx_type) { if ((mtx_type >= IPC_NUM_MUTEX_ATTRS) || (mtx_type < IPC_MUTEX_NORMAL)) { filebench_log(LOG_ERROR, "ipc_mutexattr called with undefined attr selector %d", mtx_type); return (&(filebench_shm->shm_mutexattr[IPC_MUTEX_NORMAL])); } return (&(filebench_shm->shm_mutexattr[mtx_type])); } static pthread_condattr_t *condattr = NULL; /* * On first invocation, allocates a condition variable attributes * structure and initializes it with appropriate attributes. In * all cases, returns a pointer to the structure. */ pthread_condattr_t * ipc_condattr(void) { if (condattr == NULL) { if ((condattr = malloc(sizeof (pthread_condattr_t))) == NULL) { filebench_log(LOG_ERROR, "cannot alloc cond attr"); filebench_shutdown(1); } (void) pthread_condattr_init(condattr); #ifdef HAVE_PROCSCOPE_PTHREADS if (pthread_condattr_setpshared(condattr, PTHREAD_PROCESS_SHARED) != 0) { filebench_log(LOG_ERROR, "cannot set cond attr PROCESS_SHARED"); // filebench_shutdown(1); } #endif /* HAVE_PROCSCOPE_PTHREADS */ } return (condattr); } static pthread_rwlockattr_t *rwlockattr = NULL; /* * On first invocation, allocates a readers/writers attributes * structure and initializes it with appropriate attributes. * In all cases, returns a pointer to the structure. */ static pthread_rwlockattr_t * ipc_rwlockattr(void) { if (rwlockattr == NULL) { if ((rwlockattr = malloc(sizeof (pthread_rwlockattr_t))) == NULL) { filebench_log(LOG_ERROR, "cannot alloc rwlock attr"); filebench_shutdown(1); } (void) pthread_rwlockattr_init(rwlockattr); #ifdef HAVE_PROCSCOPE_PTHREADS if (pthread_rwlockattr_setpshared(rwlockattr, PTHREAD_PROCESS_SHARED) != 0) { filebench_log(LOG_ERROR, "cannot set rwlock attr PROCESS_SHARED"); // filebench_shutdown(1); } #endif /* HAVE_PROCSCOPE_PTHREADS */ } return (rwlockattr); } /* * Calls semget() to get a set of shared system V semaphores. */ void ipc_seminit(void) { key_t key = filebench_shm->shm_semkey; int sys_semid; /* Already done? */ if (filebench_shm->shm_sys_semid >= 0) return; if ((sys_semid = semget(key, FILEBENCH_NSEMS, IPC_CREAT | S_IRUSR | S_IWUSR)) == -1) { filebench_log(LOG_ERROR, "could not create sysv semaphore set " "(need to increase sems?): %s", strerror(errno)); filebench_shutdown(1); } filebench_shm->shm_sys_semid = sys_semid; } /* * Initialize the Interprocess Communication system and its associated shared * memory structure. It first creates a temporary file using the mkstemp() * function. It than sets the file large enough to hold the filebench_shm and an * additional megabyte. (Additional megabyte is required to make sure that all * sizeof(filebench_shm) bytes plus page alignment bytes will fit in the file.) * The file is then memory mapped. Once the shared memory region is created, * ipc_init initializes various locks, pointers, and variables in the shared * memory. It also uses ftok() to get a shared memory semaphore key for later * use in allocating shared semaphores. */ void ipc_init(void) { int shmfd; char tmpbuf[MB]; key_t key; #ifdef HAVE_SEM_RMID int sys_semid; #endif shmfd = mkstemp(shmpath); if (shmfd < 0) { filebench_log(LOG_FATAL, "Could not create shared memory " "file %s: %s", shmpath, strerror(errno)); exit(1); } (void)lseek(shmfd, sizeof(filebench_shm_t), SEEK_SET); if (write(shmfd, tmpbuf, MB) != MB) { filebench_log(LOG_FATAL, "Could not write to the shared memory " "file: %s", strerror(errno)); exit(1); } if ((filebench_shm = (filebench_shm_t *)mmap(NULL, sizeof(filebench_shm_t), PROT_READ | PROT_WRITE, MAP_SHARED, shmfd, 0)) == MAP_FAILED) { filebench_log(LOG_FATAL, "Could not mmap the shared " "memory file: %s", strerror(errno)); exit(1); } (void) memset(filebench_shm, 0, (char *)&filebench_shm->shm_marker - (char *)filebench_shm); /* * First, initialize all the structures needed for the filebench_log() * function to work correctly with the log levels other than LOG_FATAL */ filebench_shm->shm_epoch = gethrtime(); filebench_shm->shm_debug_level = LOG_INFO; /* Setup mutexes for object lists */ ipc_mutexattr_init(IPC_MUTEX_NORMAL); ipc_mutexattr_init(IPC_MUTEX_PRIORITY); ipc_mutexattr_init(IPC_MUTEX_ROBUST); ipc_mutexattr_init(IPC_MUTEX_PRI_ROB); (void) pthread_mutex_init(&filebench_shm->shm_msg_lock, ipc_mutexattr(IPC_MUTEX_NORMAL)); filebench_log(LOG_INFO, "Allocated %lldMB of shared memory", (sizeof(filebench_shm_t) + MB) / MB); filebench_shm->shm_rmode = FILEBENCH_MODE_TIMEOUT; filebench_shm->shm_string_ptr = &filebench_shm->shm_strings[0]; filebench_shm->shm_ptr = (char *)filebench_shm->shm_addr; filebench_shm->shm_path_ptr = &filebench_shm->shm_filesetpaths[0]; (void) pthread_mutex_init(&filebench_shm->shm_fileset_lock, ipc_mutexattr(IPC_MUTEX_NORMAL)); (void) pthread_mutex_init(&filebench_shm->shm_procflow_lock, ipc_mutexattr(IPC_MUTEX_NORMAL)); (void) pthread_mutex_init(&filebench_shm->shm_procs_running_lock, ipc_mutexattr(IPC_MUTEX_NORMAL)); (void) pthread_mutex_init(&filebench_shm->shm_threadflow_lock, ipc_mutexattr(IPC_MUTEX_NORMAL)); (void) pthread_mutex_init(&filebench_shm->shm_flowop_lock, ipc_mutexattr(IPC_MUTEX_NORMAL)); (void) pthread_mutex_init(&filebench_shm->shm_eventgen_lock, ipc_mutexattr(IPC_MUTEX_PRI_ROB)); (void) pthread_mutex_init(&filebench_shm->shm_malloc_lock, ipc_mutexattr(IPC_MUTEX_NORMAL)); (void) pthread_mutex_init(&filebench_shm->shm_ism_lock, ipc_mutexattr(IPC_MUTEX_NORMAL)); (void) ipc_mutex_lock(&filebench_shm->shm_ism_lock); (void) pthread_cond_init(&filebench_shm->shm_eventgen_cv, ipc_condattr()); (void) pthread_rwlock_init(&filebench_shm->shm_flowop_find_lock, ipc_rwlockattr()); (void) pthread_rwlock_init(&filebench_shm->shm_run_lock, ipc_rwlockattr()); /* Create semaphore */ if ((key = ftok(shmpath, 1)) < 0) { filebench_log(LOG_ERROR, "cannot create sem: %s", strerror(errno)); exit(1); } #ifdef HAVE_SEM_RMID if ((sys_semid = semget(key, 0, 0)) != -1) (void) semctl(sys_semid, 0, IPC_RMID); #endif filebench_shm->shm_semkey = key; filebench_shm->shm_sys_semid = -1; filebench_shm->shm_dump_fd = -1; filebench_shm->shm_eventgen_hz = 0; filebench_shm->shm_id = -1; filebench_shm->shm_filesys_type = LOCAL_FS_PLUG; } void ipc_fini(void) { #ifdef HAVE_SEM_RMID if (filebench_shm->shm_sys_semid != -1) { (void) semctl(filebench_shm->shm_sys_semid, 0, IPC_RMID); filebench_shm->shm_sys_semid = -1; } #endif (void) unlink(shmpath); } /* * Attach worker process to the shared memory. Used to open and mmap * the shared memory region. If successful, it initializes the worker * process' filebench_shm to point to the shared memory region and * returns 0. Otherwise it returns -1. */ int ipc_attach(void *shmaddr, char *shmpath) { int shmfd; if ((shmfd = open(shmpath, O_RDWR)) < 0) { filebench_log(LOG_FATAL, "Could not open shared memory " "file %s: %s", shmpath, strerror(errno)); return (-1); } if ((filebench_shm = (filebench_shm_t *)mmap(shmaddr, sizeof (filebench_shm_t), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_FIXED, shmfd, 0)) == MAP_FAILED) { filebench_log(LOG_FATAL, "Could not mmap the shared " "memory file: %s", strerror(errno)); return (-1); } if (filebench_shm != shmaddr) { filebench_log(LOG_FATAL, "Could not mmap the shared " "memory file to the same location as master process: %s", strerror(errno)); return (-1); } return (0); } /* * Returns the number of preallocated objects in the filebench_shm region */ static int preallocated_entries(int obj_type) { int entries; switch(obj_type) { case FILEBENCH_FILESET: entries = sizeof(filebench_shm->shm_fileset) / sizeof(fileset_t); break; case FILEBENCH_FILESETENTRY: entries = sizeof(filebench_shm->shm_filesetentry) / sizeof(filesetentry_t); break; case FILEBENCH_PROCFLOW: entries = sizeof(filebench_shm->shm_procflow) / sizeof(procflow_t); break; case FILEBENCH_THREADFLOW: entries = sizeof(filebench_shm->shm_threadflow) / sizeof(threadflow_t); break; case FILEBENCH_FLOWOP: entries = sizeof(filebench_shm->shm_flowop) / sizeof(flowop_t); break; case FILEBENCH_VARIABLE: entries = sizeof(filebench_shm->shm_var) / sizeof(var_t); break; case FILEBENCH_AVD: entries = sizeof(filebench_shm->shm_avd_ptrs) / sizeof(avd_t); break; case FILEBENCH_RANDDIST: entries = sizeof(filebench_shm->shm_randdist) / sizeof(randdist_t); break; case FILEBENCH_CVAR: entries = sizeof(filebench_shm->shm_cvar) / sizeof(cvar_t); break; case FILEBENCH_CVAR_LIB_INFO: entries = sizeof(filebench_shm->shm_cvar_lib_info) / sizeof(cvar_library_info_t); break; default: entries = -1; filebench_log(LOG_ERROR, "preallocated_entries: " "unknown object type"); filebench_shutdown(1); break; } return entries; } /* * Allocates filebench objects from pre allocated region of * shareable memory. The memory region is partitioned into sets * of objects during initialization. This routine scans for * the first unallocated object of type "type" in the set of * available objects, and makes it as allocated. The routine * returns a pointer to the object, or NULL if all objects have * been allocated. */ void * ipc_malloc(int obj_type) { int start_idx; int max_idx; int i; (void) ipc_mutex_lock(&filebench_shm->shm_malloc_lock); start_idx = filebench_shm->shm_lastbitmapindex[obj_type]; max_idx = preallocated_entries(obj_type) - 1; i = start_idx; do { i++; if (i > max_idx) i = 0; if (filebench_shm->shm_bitmap[obj_type][i] == 0) break; } while (i != start_idx); if (i == start_idx) { filebench_log(LOG_ERROR, "Out of shared memory (%d)!", obj_type); (void) ipc_mutex_unlock(&filebench_shm->shm_malloc_lock); return (NULL); } filebench_shm->shm_bitmap[obj_type][i] = 1; filebench_shm->shm_lastbitmapindex[obj_type] = i; switch (obj_type) { case FILEBENCH_FILESET: (void) memset((char *)&filebench_shm->shm_fileset[i], 0, sizeof (fileset_t)); (void) ipc_mutex_unlock(&filebench_shm->shm_malloc_lock); return ((char *)&filebench_shm->shm_fileset[i]); case FILEBENCH_FILESETENTRY: (void) memset((char *)&filebench_shm->shm_filesetentry[i], 0, sizeof (filesetentry_t)); (void) ipc_mutex_unlock(&filebench_shm->shm_malloc_lock); return ((char *)&filebench_shm->shm_filesetentry[i]); case FILEBENCH_PROCFLOW: (void) memset((char *)&filebench_shm->shm_procflow[i], 0, sizeof (procflow_t)); (void) ipc_mutex_unlock(&filebench_shm->shm_malloc_lock); return ((char *)&filebench_shm->shm_procflow[i]); case FILEBENCH_THREADFLOW: (void) memset((char *)&filebench_shm->shm_threadflow[i], 0, sizeof (threadflow_t)); (void) ipc_mutex_unlock(&filebench_shm->shm_malloc_lock); return ((char *)&filebench_shm->shm_threadflow[i]); case FILEBENCH_FLOWOP: (void) memset((char *)&filebench_shm->shm_flowop[i], 0, sizeof (flowop_t)); (void) ipc_mutex_unlock(&filebench_shm->shm_malloc_lock); return ((char *)&filebench_shm->shm_flowop[i]); case FILEBENCH_VARIABLE: (void) memset((char *)&filebench_shm->shm_var[i], 0, sizeof (var_t)); (void) ipc_mutex_unlock(&filebench_shm->shm_malloc_lock); return ((char *)&filebench_shm->shm_var[i]); case FILEBENCH_AVD: filebench_shm->shm_avd_ptrs[i].avd_type = AVD_INVALID; filebench_shm->shm_avd_ptrs[i].avd_val.varptr = NULL; (void) ipc_mutex_unlock(&filebench_shm->shm_malloc_lock); return ((char *)&filebench_shm->shm_avd_ptrs[i]); case FILEBENCH_RANDDIST: (void) memset((char *)&filebench_shm->shm_randdist[i], 0, sizeof (randdist_t)); (void) ipc_mutex_unlock(&filebench_shm->shm_malloc_lock); return ((char *)&filebench_shm->shm_randdist[i]); case FILEBENCH_CVAR: (void) memset((char *)&filebench_shm->shm_cvar[i], 0, sizeof(cvar_t)); (void) ipc_mutex_unlock(&filebench_shm->shm_malloc_lock); return ((char *)&filebench_shm->shm_cvar[i]); case FILEBENCH_CVAR_LIB_INFO: (void) memset((char *)&filebench_shm->shm_cvar_lib_info[i], 0, sizeof(cvar_library_info_t)); (void) ipc_mutex_unlock(&filebench_shm->shm_malloc_lock); return ((char *)&filebench_shm->shm_cvar_lib_info[i]); } filebench_log(LOG_ERROR, "Attempt to ipc_malloc unknown object type (%d)!", obj_type); (void) ipc_mutex_unlock(&filebench_shm->shm_malloc_lock); return (NULL); } /* * Frees a filebench object of type "type" at the location * pointed to by "addr". It uses the type and address to * calculate which object is being freed, and clears its * allocation map entry. */ void ipc_free(int type, char *addr) { int item; caddr_t base = 0; size_t offset; size_t size = 0; if (addr == NULL) { filebench_log(LOG_ERROR, "Freeing type %d %zx", type, addr); return; } switch (type) { case FILEBENCH_FILESET: base = (caddr_t)&filebench_shm->shm_fileset[0]; size = sizeof (fileset_t); break; case FILEBENCH_FILESETENTRY: base = (caddr_t)&filebench_shm->shm_filesetentry[0]; size = sizeof (filesetentry_t); break; case FILEBENCH_PROCFLOW: base = (caddr_t)&filebench_shm->shm_procflow[0]; size = sizeof (procflow_t); break; case FILEBENCH_THREADFLOW: base = (caddr_t)&filebench_shm->shm_threadflow[0]; size = sizeof (threadflow_t); break; case FILEBENCH_FLOWOP: base = (caddr_t)&filebench_shm->shm_flowop[0]; size = sizeof (flowop_t); break; case FILEBENCH_VARIABLE: base = (caddr_t)&filebench_shm->shm_var[0]; size = sizeof (var_t); break; case FILEBENCH_AVD: base = (caddr_t)&filebench_shm->shm_avd_ptrs[0]; size = sizeof (avd_t); break; case FILEBENCH_RANDDIST: base = (caddr_t)&filebench_shm->shm_randdist[0]; size = sizeof (randdist_t); break; case FILEBENCH_CVAR: base = (caddr_t)&filebench_shm->shm_cvar[0]; size = sizeof (cvar_t); break; case FILEBENCH_CVAR_LIB_INFO: base = (caddr_t)&filebench_shm->shm_cvar_lib_info[0]; size = sizeof(cvar_library_info_t); break; } offset = ((size_t)addr - (size_t)base); item = offset / size; (void) ipc_mutex_lock(&filebench_shm->shm_malloc_lock); filebench_shm->shm_bitmap[type][item] = 0; (void) ipc_mutex_unlock(&filebench_shm->shm_malloc_lock); } /* * Allocate a string from filebench string memory. The length * of the allocated string is the same as the length of the * supplied string "string", and the contents of string are * copied to the newly allocated string. */ char * ipc_stralloc(const char *string) { char *allocstr = filebench_shm->shm_string_ptr; filebench_shm->shm_string_ptr += strlen(string) + 1; if ((filebench_shm->shm_string_ptr - &filebench_shm->shm_strings[0]) > FILEBENCH_STRINGMEMORY) { filebench_log(LOG_ERROR, "Out of ipc string memory"); return (NULL); } (void) strncpy(allocstr, string, strlen(string)); return (allocstr); } /* * Allocate a path string from filebench path string memory. * Specifically used for allocating fileset paths. The length * of the allocated path string is the same as the length of * the supplied path string "path", and the contents of path * are copied to the newly allocated path string. Checks for * out-of-path-string-memory condition and returns NULL if so. * Otherwise it returns a pointer to the newly allocated path * string. */ char * ipc_pathalloc(char *path) { char *allocpath = filebench_shm->shm_path_ptr; filebench_shm->shm_path_ptr += strlen(path) + 1; if ((filebench_shm->shm_path_ptr - &filebench_shm->shm_filesetpaths[0]) > FILEBENCH_FILESETPATHMEMORY) { filebench_log(LOG_ERROR, "Out of fileset path memory"); return (NULL); } (void) strncpy(allocpath, path, strlen(path)); return (allocpath); } /* * This is a limited functionality deallocator for path * strings - it can only free all path strings at once, * in order to avoid fragmentation. */ void ipc_freepaths(void) { filebench_shm->shm_path_ptr = &filebench_shm->shm_filesetpaths[0]; } /* * Limited functionality allocator for use by custom variables to allocate * state. */ void *ipc_cvar_heapalloc(size_t size) { void *memory; (void) ipc_mutex_lock(&filebench_shm->shm_malloc_lock); if ((filebench_shm->shm_cvar_heapsize + size) <= FILEBENCH_CVAR_HEAPSIZE) { memory = filebench_shm->shm_cvar_heap + filebench_shm->shm_cvar_heapsize; filebench_shm->shm_cvar_heapsize += size; } else memory = NULL; (void) ipc_mutex_unlock(&filebench_shm->shm_malloc_lock); return memory; } void ipc_cvar_heapfree(void *ptr) { /* Since Filebench will shutdown when the allocation of a custom variable * handle fails, there's no immediate need to implement free functionality * here. */ return; } /* * Allocates a semid from the table of semids for pre intialized * semaphores. Searches for the first available semaphore, and * sets the entry in the table to "1" to indicate allocation. * Returns the allocated semid. Stops the run if all semaphores * are already in use. */ int ipc_semidalloc(void) { int semid; for (semid = 0; filebench_shm->shm_semids[semid] == 1; semid++) ; if (semid == FILEBENCH_NSEMS) { filebench_log(LOG_ERROR, "Out of semaphores, increase system tunable limit"); filebench_shutdown(1); } filebench_shm->shm_semids[semid] = 1; return (semid); } /* * Frees up the supplied semid by seting its position in the * allocation table to "0". */ void ipc_semidfree(int semid) { filebench_shm->shm_semids[semid] = 0; } /* * Create a pool of shared memory to fit the per-thread * allocations. Uses shmget() to create a shared memory region * of size "size", attaches to it using shmat(), and stores * the returned address of the region in filebench_shm->shm_addr. * The pool is only created on the first call. The routine * returns 0 if successful or the pool already exists, * -1 otherwise. */ int ipc_ismcreate(size_t size) { #ifdef HAVE_SHM_SHARE_MMU int flag = SHM_SHARE_MMU; #else int flag = 0; #endif /* HAVE_SHM_SHARE_MMU */ /* Already done? */ if (filebench_shm->shm_id != -1) return (0); filebench_log(LOG_VERBOSE, "Creating %zd bytes of ISM Shared Memory...", size); if ((filebench_shm->shm_id = shmget(0, size, IPC_CREAT | 0666)) == -1) { filebench_log(LOG_ERROR, "Failed to create %zd bytes of ISM shared memory (ret = %d)", size, errno); return (-1); } if ((filebench_shm->shm_addr = (caddr_t)shmat(filebench_shm->shm_id, 0, flag)) == (void *)-1) { filebench_log(LOG_ERROR, "Failed to attach %zd bytes of created ISM shared memory", size); return (-1); } filebench_shm->shm_ptr = (char *)filebench_shm->shm_addr; filebench_log(LOG_VERBOSE, "Allocated %zd bytes of ISM Shared Memory... at %zx", size, filebench_shm->shm_addr); /* Locked until allocated to block allocs */ (void) ipc_mutex_unlock(&filebench_shm->shm_ism_lock); return (0); } /* Per addr space ism */ static int ism_attached = 0; /* * Attach to interprocess shared memory. If already attached * just return, otherwise use shmat() to attached to the region * with ID of filebench_shm->shm_id. Returns -1 if shmat() * fails, otherwise 0. */ static int ipc_ismattach(void) { #ifdef HAVE_SHM_SHARE_MMU int flag = SHM_SHARE_MMU; #else int flag = 0; #endif /* HAVE_SHM_SHARE_MMU */ if (ism_attached) return (0); /* Does it exist? */ if (filebench_shm->shm_id == 999) return (0); if (shmat(filebench_shm->shm_id, filebench_shm->shm_addr, flag) == NULL) return (-1); ism_attached = 1; return (0); } /* * Allocate from interprocess shared memory. Attaches to ism * if necessary, then allocates "size" bytes, updates allocation * information and returns a pointer to the allocated memory. */ /* * XXX No check is made for out-of-memory condition */ char * ipc_ismmalloc(size_t size) { char *allocstr; (void) ipc_mutex_lock(&filebench_shm->shm_ism_lock); /* Map in shared memory */ (void) ipc_ismattach(); allocstr = filebench_shm->shm_ptr; filebench_shm->shm_ptr += size; filebench_shm->shm_allocated += size; (void) ipc_mutex_unlock(&filebench_shm->shm_ism_lock); return (allocstr); } /* * Deletes shared memory region and resets shared memory region * information in filebench_shm. */ void ipc_ismdelete(void) { if (filebench_shm->shm_id == -1) return; filebench_log(LOG_VERBOSE, "Deleting ISM..."); (void) ipc_mutex_lock(&filebench_shm->shm_ism_lock); #ifdef HAVE_SEM_RMID (void) shmctl(filebench_shm->shm_id, IPC_RMID, 0); #endif filebench_shm->shm_ptr = (char *)filebench_shm->shm_addr; filebench_shm->shm_id = -1; filebench_shm->shm_allocated = 0; (void) ipc_mutex_unlock(&filebench_shm->shm_ism_lock); }
25,368
25.930998
81
c
filebench
filebench-master/ipc.h
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _FB_IPC_H #define _FB_IPC_H #include "filebench.h" /* Mutex Priority Inheritance and Robustness flags */ #define IPC_MUTEX_NORMAL 0x0 #define IPC_MUTEX_PRIORITY 0x1 #define IPC_MUTEX_ROBUST 0x2 #define IPC_MUTEX_PRI_ROB 0x3 #define IPC_NUM_MUTEX_ATTRS 4 #define FILEBENCH_NSEMS 128 #define FILEBENCH_ABORT_ERROR 1 #define FILEBENCH_ABORT_DONE 2 #define FILEBENCH_ABORT_RSRC 3 #define FILEBENCH_ABORT_FINI 4 /* run modes */ #define FILEBENCH_MODE_TIMEOUT 0x0 #define FILEBENCH_MODE_Q1STDONE 0x1 #define FILEBENCH_MODE_QALLDONE 0x2 /* misc. modes */ #define FILEBENCH_MODE_NOUSAGE 0x01 /* * Types of IPC shared memory pools we have. * ipc_malloc() gets the type as an argument and * allocates a slot from the appropriate pool. * */ #define FILEBENCH_FILESET 0 #define FILEBENCH_FILESETENTRY 1 #define FILEBENCH_PROCFLOW 2 #define FILEBENCH_THREADFLOW 3 #define FILEBENCH_FLOWOP 4 #define FILEBENCH_VARIABLE 5 #define FILEBENCH_AVD 6 #define FILEBENCH_RANDDIST 7 #define FILEBENCH_CVAR 8 #define FILEBENCH_CVAR_LIB_INFO 9 #define FILEBENCH_MAXTYPE (FILEBENCH_CVAR_LIB_INFO + 1) /* * The values below are selected by intuition: these limits * seem to be reasonable for medium-scale workloads. If * one needs more processes, threads, flowops, etc., one * has to increase these values */ #define FILEBENCH_NFILESETS (16) #define FILEBENCH_NFILESETENTRIES (1024 * 1024) #define FILEBENCH_NPROCFLOWS (1024) #define FILEBENCH_NTHREADFLOWS (1024) /* 16 flowops per threadflow seems reasonable */ #define FILEBENCH_NFLOWOPS (16 * 1024) /* variables are not the only one that are specified explicitly in the .f file. Some special variables are used within FB itself. So, let's put this value to some save large value */ #define FILEBENCH_NVARIABLES (1024) #define FILEBENCH_NAVDS (4096) #define FILEBENCH_NRANDDISTS (16) #define FILEBENCH_NCVARS (16) #define FILEBENCH_NCVAR_LIB_INFO (32) #define FILEBENCH_MAXBITMAP FILEBENCH_NFILESETENTRIES /* these below are not regular pools and are allocated separately from ipc_malloc() */ #define FILEBENCH_FILESETPATHMEMORY (FILEBENCH_NFILESETENTRIES * FSE_MAXPATHLEN) #define FILEBENCH_STRINGMEMORY (FILEBENCH_NVARIABLES * 128) #define FILEBENCH_CVAR_HEAPSIZE (FILEBENCH_NCVARS * 4096) typedef struct filebench_shm { /* * All fields down to shm_marker are set to zero during * filebench initialization in ipc_init() function. */ /* * Global lists and locks for main Filebench objects: * filesets, procflows, threaflows, and flowops. */ fileset_t *shm_filesetlist; pthread_mutex_t shm_fileset_lock; procflow_t *shm_procflowlist; pthread_mutex_t shm_procflow_lock; /* threadflow_t *shm_threadflowlist; (this one is per procflow) */ pthread_mutex_t shm_threadflow_lock; flowop_t *shm_flowoplist; pthread_mutex_t shm_flowop_lock; /* * parallel file allocation control. Restricts number of spawned * allocation threads and allows waiting for allocation to finish. */ pthread_cond_t shm_fsparalloc_cv; /* cv to wait for alloc threads */ int shm_fsparalloc_count; /* active alloc thread count */ pthread_mutex_t shm_fsparalloc_lock; /* lock to protect count */ /* * Procflow and process state */ int shm_procs_running; /* count of running processes */ pthread_mutex_t shm_procs_running_lock; /* protects shm_procs_running */ int shm_f_abort; /* stop the run NOW! */ pthread_rwlock_t shm_run_lock; /* used as barrier to sync run */ flag_t shm_procflows_defined_flag; /* indicates that process creator thread has defined all the procflows */ /* * flowop state */ pthread_rwlock_t shm_flowop_find_lock; /* prevents flowop_find() */ /* during initial flowop creation */ /* * Variable lits. */ var_t *shm_var_list; /* normal variables */ var_t *shm_var_loc_list; /* variables local to composite flowops */ /* List of randdist instances (randdist for every random variable) */ randdist_t *shm_rand_list; cvar_t *shm_cvar_list; /* custom variables */ cvar_library_info_t *shm_cvar_lib_info_list; /* * log and statistics dumping controls and state */ int shm_debug_level; int shm_bequiet; /* pause run while collecting stats */ int shm_dump_fd; /* dump file descriptor */ char shm_dump_filename[MAXPATHLEN]; /* * Event generator state */ int shm_eventgen_enabled; /* event gen in operation */ avd_t shm_eventgen_hz; /* number of events per sec. */ uint64_t shm_eventgen_q; /* count of unclaimed events */ pthread_mutex_t shm_eventgen_lock; /* lock protecting count */ pthread_cond_t shm_eventgen_cv; /* cv to wait on for more events */ /* * System 5 semaphore state */ key_t shm_semkey; int shm_sys_semid; char shm_semids[FILEBENCH_NSEMS]; /* * Misc. pointers and state */ char shm_fscriptname[1024]; int shm_id; int shm_rmode; /* run mode settings */ int shm_mmode; /* misc. mode settings */ int shm_1st_err; pthread_mutex_t shm_msg_lock; pthread_mutexattr_t shm_mutexattr[IPC_NUM_MUTEX_ATTRS]; char *shm_string_ptr; char *shm_path_ptr; hrtime_t shm_epoch; hrtime_t shm_starttime; int shm_utid; int lathist_enabled; int shm_cvar_heapsize; /* * Shared memory allocation control */ pthread_mutex_t shm_ism_lock; size_t shm_required; size_t shm_allocated; caddr_t shm_addr; char *shm_ptr; /* * Type of plug-in file system client to use. Defaults to * local file system, which is type "0". */ fb_plugin_type_t shm_filesys_type; /* * IPC shared memory pools allocation/deallocation control: * - bitmap (if fact, bit is an integer here) * - last allocated index * - lock for the operations on the pool */ int shm_bitmap[FILEBENCH_MAXTYPE][FILEBENCH_MAXBITMAP]; int shm_lastbitmapindex[FILEBENCH_MAXTYPE]; pthread_mutex_t shm_malloc_lock; /* * end of pre-zeroed data. We do not bzero pools, because * otherwise we will touch every page in the pools and * consequently use a lot of physical memory, while * in fact, we might not need so much memory later. */ int shm_marker[0]; /* * IPC shared memory pools. Allocated to users * when ipc_malloc() is called. Not zeroed, but * ipc_malloc() will bzero each allocated slot. */ fileset_t shm_fileset[FILEBENCH_NFILESETS]; filesetentry_t shm_filesetentry[FILEBENCH_NFILESETENTRIES]; procflow_t shm_procflow[FILEBENCH_NPROCFLOWS]; threadflow_t shm_threadflow[FILEBENCH_NTHREADFLOWS]; flowop_t shm_flowop[FILEBENCH_NFLOWOPS]; var_t shm_var[FILEBENCH_NVARIABLES]; struct avd shm_avd_ptrs[FILEBENCH_NAVDS]; randdist_t shm_randdist[FILEBENCH_NRANDDISTS]; cvar_t shm_cvar[FILEBENCH_NCVARS]; cvar_library_info_t shm_cvar_lib_info[FILEBENCH_NCVAR_LIB_INFO]; /* these below are not regular pools and are allocated separately from ipc_malloc() */ char shm_strings[FILEBENCH_STRINGMEMORY]; char shm_filesetpaths[FILEBENCH_FILESETPATHMEMORY]; char shm_cvar_heap[FILEBENCH_CVAR_HEAPSIZE]; } filebench_shm_t; extern char shmpath[128]; extern void ipc_init(void); extern int ipc_attach(void *shmaddr, char *shmpath); void *ipc_malloc(int type); void ipc_free(int type, char *addr); pthread_mutexattr_t *ipc_mutexattr(int); pthread_condattr_t *ipc_condattr(void); int ipc_semidalloc(void); void ipc_semidfree(int semid); char *ipc_stralloc(const char *string); char *ipc_pathalloc(char *string); void *ipc_cvar_heapalloc(size_t size); void ipc_cvar_heapfree(void *ptr); int ipc_mutex_lock(pthread_mutex_t *mutex); int ipc_mutex_unlock(pthread_mutex_t *mutex); void ipc_seminit(void); char *ipc_ismmalloc(size_t size); int ipc_ismcreate(size_t size); void ipc_ismdelete(void); void ipc_fini(void); extern filebench_shm_t *filebench_shm; #endif /* _FB_IPC_H */
8,677
30.215827
87
h
filebench
filebench-master/misc.c
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #include <stdio.h> #include <fcntl.h> #include <limits.h> #include <time.h> #include <libgen.h> #include <unistd.h> #include <strings.h> #include <sys/time.h> #include "filebench.h" #include "ipc.h" #include "eventgen.h" #include "utils.h" #include "fsplug.h" #include "fbtime.h" /* File System functions vector */ fsplug_func_t *fs_functions_vec; extern int lex_lineno; /* * Writes a message consisting of information formated by * "fmt" to the log file, dump file or stdout. The supplied * "level" argument determines which file to write to and * what other actions to take. * The level LOG_DUMP writes to the "dump" file, * and will open it on the first invocation. Other levels * print to the stdout device, with the amount of information * dependent on the error level and the current error level * setting in filebench_shm->shm_debug_level. */ void filebench_log __V((int level, const char *fmt, ...)) { va_list args; hrtime_t now = 0; char line[131072]; char buf[131072]; /* we want to be able to use filebench_log() eveing before filebench_shm is initialized. In this case, all logs have FATAL level. */ if (!filebench_shm) level = LOG_FATAL; if (level == LOG_FATAL) goto fatal; /* open dumpfile if not already open and writing to it */ if ((level == LOG_DUMP) && (*filebench_shm->shm_dump_filename == 0)) return; if ((level == LOG_DUMP) && (filebench_shm->shm_dump_fd < 0)) { filebench_shm->shm_dump_fd = open(filebench_shm->shm_dump_filename, O_RDWR | O_CREAT | O_TRUNC, 0666); } if ((level == LOG_DUMP) && (filebench_shm->shm_dump_fd < 0)) { (void) snprintf(line, sizeof (line), "Open logfile failed: %s", strerror(errno)); level = LOG_ERROR; } /* Quit if this is a LOG_ERROR messages and they are disabled */ if ((filebench_shm->shm_1st_err) && (level == LOG_ERROR)) return; if (level == LOG_ERROR1) { if (filebench_shm->shm_1st_err) return; /* A LOG_ERROR1 temporarily disables LOG_ERROR messages */ filebench_shm->shm_1st_err = 1; level = LOG_ERROR; } /* Only log greater or equal than debug setting */ if ((level != LOG_DUMP) && (level > filebench_shm->shm_debug_level)) return; now = gethrtime(); fatal: #ifdef __STDC__ va_start(args, fmt); #else char *fmt; va_start(args); fmt = va_arg(args, char *); #endif (void) vsprintf(line, fmt, args); va_end(args); if (level == LOG_FATAL) { (void) fprintf(stderr, "%s\n", line); return; } /* Serialize messages to log */ (void) ipc_mutex_lock(&filebench_shm->shm_msg_lock); if (level == LOG_DUMP) { if (filebench_shm->shm_dump_fd != -1) { (void) snprintf(buf, sizeof (buf), "%s\n", line); /* We ignore the return value of write() */ if (write(filebench_shm->shm_dump_fd, buf, strlen(buf))); (void) fsync(filebench_shm->shm_dump_fd); (void) ipc_mutex_unlock(&filebench_shm->shm_msg_lock); return; } } else if (filebench_shm->shm_debug_level > LOG_INFO) { if (level < LOG_INFO) (void) fprintf(stderr, "%5d: ", (int)my_pid); else (void) fprintf(stdout, "%5d: ", (int)my_pid); } if (level < LOG_INFO) { (void) fprintf(stderr, "%4.3f: %s", (now - filebench_shm->shm_epoch) / SEC2NS_FLOAT, line); if (my_procflow == NULL) (void) fprintf(stderr, " around line %d", lex_lineno); (void) fprintf(stderr, "\n"); (void) fflush(stderr); } else { (void) fprintf(stdout, "%4.3f: %s", (now - filebench_shm->shm_epoch) / SEC2NS_FLOAT, line); (void) fprintf(stdout, "\n"); (void) fflush(stdout); } (void) ipc_mutex_unlock(&filebench_shm->shm_msg_lock); } /* * Stops the run and exits filebench. If filebench is * currently running a workload, calls procflow_shutdown() * to stop the run. Also closes and deletes shared memory. */ void filebench_shutdown(int error) { if (error) { filebench_log(LOG_DEBUG_IMPL, "Shutdown on error %d", error); (void) ipc_mutex_lock(&filebench_shm->shm_procflow_lock); if (filebench_shm->shm_f_abort == FILEBENCH_ABORT_FINI) { (void) ipc_mutex_unlock( &filebench_shm->shm_procflow_lock); return; } filebench_shm->shm_f_abort = FILEBENCH_ABORT_ERROR; (void) ipc_mutex_unlock(&filebench_shm->shm_procflow_lock); } else { filebench_log(LOG_DEBUG_IMPL, "Shutdown"); } procflow_shutdown(); (void) unlink("/tmp/filebench_shm"); ipc_ismdelete(); exit(error); }
5,319
25.206897
70
c
filebench
filebench-master/misc.h
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _FB_MISC_H #define _FB_MISC_H #pragma ident "%Z%%M% %I% %E% SMI" #define LOG_ERROR 0 /* a major error */ #define LOG_ERROR1 1 /* also major error, but turn off error reporting */ /* for now */ #define LOG_INFO 2 /* some useful information. Default is to print */ #define LOG_VERBOSE 3 /* four more levels of detailed information */ #define LOG_DEBUG_SCRIPT 4 #define LOG_DEBUG_IMPL 6 #define LOG_DEBUG_NEVER 10 #define LOG_FATAL 999 /* really bad error, shut down */ #define LOG_DUMP 1001 #endif /* _FB_MISC_H */
1,454
32.837209
73
h
filebench
filebench-master/multi_client_sync.c
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #include "filebench.h" #include "multi_client_sync.h" #include <netdb.h> #include <netinet/in.h> #include <arpa/inet.h> #include <errno.h> #define MCS_NAMELENGTH 128 #define MCS_MSGLENGTH (MCS_NAMELENGTH * 8) static int mc_sync_sock_id; static char this_client_name[MCS_NAMELENGTH]; /* * Open a socket to the master synchronization host */ int mc_sync_open_sock(char *master_name, int master_port, char *my_name) { struct sockaddr_in client_in; struct sockaddr_in master_in; struct hostent *master_info; //int error_num; //char buffer[MCS_MSGLENGTH]; (void) strncpy(this_client_name, my_name, MCS_NAMELENGTH); if ((mc_sync_sock_id = socket(PF_INET, SOCK_STREAM, 0)) == -1) { filebench_log(LOG_ERROR, "could not create a client socket"); return (FILEBENCH_ERROR); } client_in.sin_family = AF_INET; client_in.sin_port = INADDR_ANY; client_in.sin_addr.s_addr = INADDR_ANY; if (bind(mc_sync_sock_id, (struct sockaddr *)&client_in, sizeof (client_in)) == -1) { filebench_log(LOG_ERROR, "could not bind to client socket"); return (FILEBENCH_ERROR); } master_info = gethostbyname(master_name); /* if (gethostbyname_r(master_name, &master_info, buffer, MCS_MSGLENGTH, &error_num) == NULL) { filebench_log(LOG_ERROR, "could not locate sync master"); return (FILEBENCH_ERROR); } */ master_in.sin_family = AF_INET; master_in.sin_port = htons((uint16_t)master_port); (void) memcpy(&master_in.sin_addr.s_addr, *(master_info->h_addr_list), sizeof (master_in.sin_addr.s_addr)); if (connect(mc_sync_sock_id, (struct sockaddr *)&master_in, sizeof (master_in)) == -1) { filebench_log(LOG_ERROR, "connection refused to sync master, error %d", errno); return (FILEBENCH_ERROR); } return (FILEBENCH_OK); } /* * Send a synchronization message and wait for a reply */ int mc_sync_synchronize(int sync_point) { char msg[MCS_MSGLENGTH]; int amnt; (void) snprintf(msg, MCS_MSGLENGTH, "cmd=SYNC,id=xyzzy,name=%s,sample=%d\n", this_client_name, sync_point); (void) send(mc_sync_sock_id, msg, strlen(msg), 0); amnt = 0; msg[0] = 0; while (strchr(msg, '\n') == NULL) amnt += recv(mc_sync_sock_id, msg, sizeof (msg), 0); filebench_log(LOG_INFO, "sync point %d succeeded!\n", sync_point); return (FILEBENCH_OK); }
3,217
26.741379
71
c
filebench
filebench-master/multi_client_sync.h
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _MULTI_CLIENT_SYNC_H #define _MULTI_CLIENT_SYNC_H #include <sys/types.h> #if defined(HAVE_SYS_SOCKET_H) #include <sys/socket.h> #endif int mc_sync_open_sock(char *master_name, int master_port, char *client_name); int mc_sync_synchronize(int synch_point); #endif /* _MULTI_CLIENT_SYNC_H */
1,227
31.315789
77
h
filebench
filebench-master/parsertypes.h
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _FB_PARSERTYPES_H #define _FB_PARSERTYPES_H #include "filebench.h" #define DOFILE_FALSE 0 #define DOFILE_TRUE 1 #define FSE_SYSTEM 1 typedef struct list { struct list *list_next; avd_t list_string; avd_t list_integer; } list_t; typedef struct attr { int attr_name; struct attr *attr_next; avd_t attr_avd; void *attr_obj; } attr_t; typedef struct cmd { void (*cmd)(struct cmd *); char *cmd_name; char *cmd_tgt1; char *cmd_tgt2; char *cmd_tgt3; char *thread_name; int cmd_subtype; uint64_t cmd_qty; int64_t cmd_qty1; struct cmd *cmd_list; struct cmd *cmd_next; attr_t *cmd_attr_list; list_t *cmd_param_list; list_t *cmd_param_list2; } cmd_t; typedef union { int64_t i; unsigned char b; char *s; } fs_u; typedef struct pidlist { struct pidlist *pl_next; int pl_fd; pid_t pl_pid; } pidlist_t; typedef void (*cmdfunc)(cmd_t *); int yy_switchfileparent(FILE *file); int yy_switchfilescript(FILE *file); #endif /* _FB_PARSERTYPES_H */
1,922
21.892857
70
h
filebench
filebench-master/procflow.c
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * Portions Copyright 2008 Denis Cheng */ #include <signal.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/wait.h> #include "filebench.h" #include "procflow.h" #include "flowop.h" #include "ipc.h" #include "eventgen.h" /* pid and procflow pointer for this process */ pid_t my_pid; procflow_t *my_procflow = NULL; static procflow_t *procflow_define_common(procflow_t **list, char *name, procflow_t *inherit, int instance); static void procflow_sleep(procflow_t *procflow, int wait_cnt); /* * Procflows are filebench entities which manage processes. Each * worker procflow spawns a separate filebench process, with attributes * inherited from a FLOW_MASTER procflow created during f model language * parsing. This section contains routines to define, create, control, * and delete procflows. * * Each process defined in the f model creates a FLOW_MASTER * procflow which encapsulates the defined attributes, and threads of * the f process, including the number of instances to create. At * runtime, a worker procflow instance with an associated filebench * process is created, which runs until told to quite by the original * filebench process or is specifically deleted. */ /* * This routine forks a child process and uses either system() or exec() to * start up a new instance of filebench, passing it the procflow name, instance * number and shared memory region address. */ static int procflow_createproc(procflow_t *procflow) { pid_t pid = 0; char instance[128]; char shmaddr[128]; char procname[128]; (void) snprintf(instance, sizeof (instance), "%d", procflow->pf_instance); (void) snprintf(procname, sizeof (procname), "%s", procflow->pf_name); (void) snprintf(shmaddr, sizeof (shmaddr), "%p", filebench_shm); filebench_log(LOG_DEBUG_IMPL, "creating process %s", procflow->pf_name); procflow->pf_running = 0; #ifdef HAVE_FORK1 if ((pid = fork1()) < 0) { filebench_log(LOG_ERROR, "procflow_createproc fork failed: %s", strerror(errno)); return (-1); } #else if ((pid = fork()) < 0) { filebench_log(LOG_ERROR, "procflow_createproc fork failed: %s", strerror(errno)); return (-1); } #endif /* HAVE_FORK1 */ /* if child, start up new copy of filebench */ if (pid == 0) { #ifdef USE_SYSTEM char syscmd[1024]; #endif (void) sigignore(SIGINT); filebench_log(LOG_DEBUG_SCRIPT, "Starting %s-%d", procflow->pf_name, procflow->pf_instance); /* Child */ #ifdef USE_SYSTEM (void) snprintf(syscmd, sizeof (syscmd), "%s -a %s -i %s -s %s", execname, procname, instance, shmaddr); if (system(syscmd) < 0) { filebench_log(LOG_ERROR, "procflow exec proc failed: %s", strerror(errno)); filebench_shutdown(1); } #else if (execlp(execname, procname, "-a", procname, "-i", instance, "-s", shmaddr, "-m", shmpath, NULL) < 0) { filebench_log(LOG_ERROR, "procflow exec proc failed: %s", strerror(errno)); filebench_shutdown(1); } #endif exit(1); } else { /* if parent, save pid and return */ procflow->pf_pid = pid; } filebench_log(LOG_DEBUG_IMPL, "procflow_createproc created pid %d", pid); return (0); } /* * Iterates over all defined (MASTER) procflows, allocates procflow instances, * creates worker monitor processes that correspond to these instances * and waits until monitors define all threadflows. There is now guarantee * after this function that all threads are running, but there is a guarantee * that all threadflow instances are defined and are in corresponding lists. */ static int procflow_create_all_procs(void) { procflow_t *procflow; int ret = 0; procflow = filebench_shm->shm_procflowlist; while (procflow) { int instances; int i; instances = (int)avd_get_int(procflow->pf_instances); filebench_log(LOG_INFO, "Starting %d %s instances", instances, procflow->pf_name); /* Create instances of procflow */ for (i = 0; (i < instances) && (ret == 0); i++) { procflow_t *newproc; /* Define procflows and add them to the list */ newproc = procflow_define_common(&filebench_shm->shm_procflowlist, procflow->pf_name, procflow, i + 1); /* * We clear pf_threads_defined_flag in the procflow * structure before starting a worker monitor * process. Each worker monitor process will set this flag * later as soon as it defines _all_ threadflows (and puts them * into the corresponding list). Than this thread will wait * on this flag to make sure that all threadflows were defined. */ if (!newproc) { ret = -1; } else { clear_flag(&newproc->pf_threads_defined_flag); ret = procflow_createproc(newproc); } } if (ret) break; procflow = procflow->pf_next; } /* Wait here for all monitor threads to define threadflows */ procflow = filebench_shm->shm_procflowlist; while (procflow) { if (procflow->pf_instance && (procflow->pf_instance == FLOW_MASTER)) { procflow = procflow->pf_next; continue; } wait_flag(&procflow->pf_threads_defined_flag); procflow = procflow->pf_next; } return (ret); } /* * Find a procflow of name "name" and instance "instance" on the * master procflow list, filebench_shm->shm_procflowlist. Locks the list * and scans through it searching for a procflow with matching * name and instance number. If found returns a pointer to the * procflow, otherwise returns NULL. */ static procflow_t * procflow_find(char *name, int instance) { procflow_t *procflow; (void)ipc_mutex_lock(&filebench_shm->shm_procflow_lock); procflow = filebench_shm->shm_procflowlist; while (procflow) { if ((strcmp(name, procflow->pf_name) == 0) && (instance == procflow->pf_instance)) { (void)ipc_mutex_unlock(&filebench_shm->shm_procflow_lock); return (procflow); } procflow = procflow->pf_next; } (void)ipc_mutex_unlock(&filebench_shm->shm_procflow_lock); return (NULL); } /* * Used to start up threads on a child process, when filebench is * compiled to support multiple processes. Uses the name string * and instance number passed to the child to find the previously * created procflow entity. Then uses nice() to reduce the * process' priority by at least 10. A call is then made to * threadflow_init() which creates and runs the process' threads * and flowops to completion. When threadflow_init() returns, * a call to exit() terminates the child process. */ int procflow_exec(char *name, int instance) { procflow_t *procflow; int proc_nice; #ifdef HAVE_SETRLIMIT struct rlimit rlp; #endif int ret; if ((procflow = procflow_find(name, instance)) == NULL) { filebench_log(LOG_FATAL, "procflow_exec could not find %s-%d", name, instance); return (-1); } /* set the slave process' procflow pointer */ my_procflow = procflow; /* set its pid from value stored by main() */ procflow->pf_pid = my_pid; filebench_log(LOG_DEBUG_IMPL, "Started up %s pid %d", procflow->pf_name, my_pid); filebench_log(LOG_DEBUG_IMPL, "nice = %llx", procflow->pf_nice); proc_nice = avd_get_int(procflow->pf_nice); if (proc_nice) filebench_log(LOG_DEBUG_IMPL, "Setting pri of %s-%d to %d", name, instance, nice(proc_nice)); procflow->pf_running = 1; #ifdef HAVE_SETRLIMIT /* Get resource limits */ (void) getrlimit(RLIMIT_NOFILE, &rlp); filebench_log(LOG_DEBUG_SCRIPT, "%d file descriptors", rlp.rlim_cur); #endif if ((ret = threadflow_init(procflow)) != FILEBENCH_OK) { if (ret < 0) { filebench_log(LOG_ERROR, "Failed to start threads for %s pid %d", procflow->pf_name, my_pid); } } else { filebench_log(LOG_DEBUG_IMPL, "procflow_createproc exiting..."); } (void) ipc_mutex_lock(&filebench_shm->shm_procs_running_lock); filebench_shm->shm_procs_running --; (void) ipc_mutex_unlock(&filebench_shm->shm_procs_running_lock); procflow->pf_running = 0; return (ret); } /* * A special thread from which worker (child) processes are created, and which * then waits for worker processes to die. If they die unexpectedly, * then report an error and terminate the run. */ static void * procflow_createnwait(void *unused) { /* XXX: do not disregard potential error return!!! */ procflow_create_all_procs(); /* * After procflow_create_all_procs returns, we can be sure * that all procflows and threadflows were defined and put into * the corresponding lists. So, we can allow main thread to * continue. It will iterate over the procflow/threadflow lists * to ensure that all processes and threads have been started. */ set_flag(&filebench_shm->shm_procflows_defined_flag); /* CONSTCOND */ while (1) { /* wait for any child process to exit */ #ifdef HAVE_WAITID siginfo_t status; if (waitid(P_ALL, 0, &status, WEXITED) != 0) #else /* HAVE_WAITID */ int status; if (waitpid(-1, &status, 0) < 0) #endif pthread_exit(0); (void) ipc_mutex_lock(&filebench_shm->shm_procflow_lock); /* if normal shutdown in progress, just quit */ if (filebench_shm->shm_f_abort) { (void) ipc_mutex_unlock( &filebench_shm->shm_procflow_lock); pthread_exit(0); } /* if nothing running, exit */ if (filebench_shm->shm_procs_running == 0) { filebench_shm->shm_f_abort = FILEBENCH_ABORT_RSRC; (void) ipc_mutex_unlock( &filebench_shm->shm_procflow_lock); pthread_exit(0); } (void) ipc_mutex_unlock(&filebench_shm->shm_procflow_lock); #ifdef HAVE_WAITID if (status.si_code == CLD_EXITED) { /* A process called exit(); check returned status */ if (status.si_status != 0) { filebench_log(LOG_ERROR, "Unexpected Process termination; exiting", status.si_status); filebench_shutdown(1); } } else { /* A process quit because of some fatal error */ filebench_log(LOG_ERROR, "Unexpected Process termination Code %d, Errno %d", status.si_code, status.si_errno); filebench_shutdown(1); } #else /* HAVE_WAITID */ /* child did not exit, but got a signal, so just continue waiting */ if (WIFSTOPPED(status)) continue; #ifdef WIFCONTINUED /* some versions (NetBSD before version 8.0) do not support WIFCONTINUED */ if (WIFCONTINUED(status)) continue; #endif if (WIFEXITED(status)) { /* A process called exit(); check returned status */ if (WEXITSTATUS(status) != 0) { filebench_log(LOG_ERROR, "Unexpected Process termination; exiting", WEXITSTATUS(status)); filebench_shutdown(1); } } else { /* A process quit because of some fatal error */ filebench_log(LOG_ERROR, "Unexpected Process termination Code %d", WTERMSIG(status)); filebench_shutdown(1); } #endif } /* NOTREACHED */ return (NULL); } /* * Cancel all threads within a processes, as well as the process itself. * Called by ^c or by sig_kill */ /* ARGSUSED */ static void procflow_cancel(int arg1) { filebench_log(LOG_DEBUG_IMPL, "Process signal handler on pid %", my_procflow->pf_pid); procflow_sleep(my_procflow, SHUTDOWN_WAIT_SECONDS); threadflow_delete_all(&my_procflow->pf_threads); /* quit the main procflow thread and hence the process */ exit(0); } /* * Creates a process creator thread and waits until * it defines all the procflows (and threadflows in turn). */ static int procflow_init(void) { procflow_t *procflow; pthread_t tid; int ret = 0; procflow = filebench_shm->shm_procflowlist; if (!procflow) { filebench_log(LOG_ERROR, "Workload has no processes"); return (FILEBENCH_ERROR); } filebench_log(LOG_DEBUG_IMPL, "procflow_init %s, %llu", procflow->pf_name, (u_longlong_t)avd_get_int(procflow->pf_instances)); /* * This (main) process clears the shm_procflows_defined_flag here. * Later, procflow creator thread will set this flag only after all procflows * and threadflows are defined and put into the corresponding lists. */ clear_flag(&filebench_shm->shm_procflows_defined_flag); ret = pthread_create(&tid, NULL, procflow_createnwait, NULL); if (ret) return ret; (void) signal(SIGUSR1, procflow_cancel); /* * Wait for the process creator thread to define * all procflows (and threadflows in turn). */ wait_flag(&filebench_shm->shm_procflows_defined_flag); return (ret); } /* * Waits for child processes to finish and returns their exit status. Used by * procflow_delete() to wait for a deleted process to exit. */ static void procflow_wait(pid_t pid) { pid_t wpid; int stat; (void) waitpid(pid, &stat, 0); while ((wpid = waitpid(getpid() * -1, &stat, WNOHANG)) > 0) filebench_log(LOG_DEBUG_IMPL, "Waited for pid %d", (int)wpid); } /* * Common routine to sleep for wait_cnt seconds or for pf_running to * go false. Checks once a second to see if pf_running has gone false. */ static void procflow_sleep(procflow_t *procflow, int wait_cnt) { while (procflow->pf_running & wait_cnt) { (void) sleep(1); wait_cnt--; } } /* * Deletes the designated procflow. Finally it frees the * procflow entity. filebench_shm->shm_procflow_lock must be held on entry. * * If the designated procflow is not found on the list it returns -1 and * the procflow is not deleted. Otherwise it returns 0. */ static int procflow_cleanup(procflow_t *procflow) { procflow_t *entry; filebench_log(LOG_DEBUG_SCRIPT, "Deleted proc: (%s-%d) pid %d", procflow->pf_name, procflow->pf_instance, procflow->pf_pid); procflow->pf_running = 0; /* remove entry from proclist */ entry = filebench_shm->shm_procflowlist; /* unlink procflow entity from proclist */ if (entry == procflow) { /* at head of list */ filebench_shm->shm_procflowlist = procflow->pf_next; } else { /* search list for procflow */ while (entry && entry->pf_next != procflow) entry = entry->pf_next; /* if entity found, unlink it */ if (entry == NULL) return (-1); else entry->pf_next = procflow->pf_next; } /* free up the procflow entity */ ipc_free(FILEBENCH_PROCFLOW, (char *)procflow); return (0); } /* * Waits till all threadflows are started, or a timeout occurs. * Checks through the list of procflows, waiting up to 30 * seconds for each one to set its pf_running flag to 1. If not * set after 30 seconds, continues on to the next procflow * anyway after logging the fact. Once pf_running is set * to 1 for a given procflow or the timeout is reached, * threadflow_allstarted() is called to start the threads. * Returns 0 (OK), unless filebench_shm->shm_f_abort is signaled, * in which case it returns -1. */ static int procflow_allstarted() { procflow_t *procflow = filebench_shm->shm_procflowlist; int running_procs = 0; int ret = 0; (void) ipc_mutex_lock(&filebench_shm->shm_procflow_lock); (void) sleep(1); while (procflow) { int waits; if (procflow->pf_instance && (procflow->pf_instance == FLOW_MASTER)) { procflow = procflow->pf_next; continue; } waits = 10; while (waits && procflow->pf_running == 0) { (void) ipc_mutex_unlock( &filebench_shm->shm_procflow_lock); if (filebench_shm->shm_f_abort == 1) return (-1); if (waits < 3) filebench_log(LOG_INFO, "Waiting for process %s-%d %d", procflow->pf_name, procflow->pf_instance, procflow->pf_pid); (void) sleep(3); waits--; (void) ipc_mutex_lock( &filebench_shm->shm_procflow_lock); } if (waits == 0) filebench_log(LOG_INFO, "Failed to start process %s-%d", procflow->pf_name, procflow->pf_instance); running_procs++; threadflow_allstarted(procflow->pf_pid, procflow->pf_threads); procflow = procflow->pf_next; } (void) ipc_mutex_lock(&filebench_shm->shm_procs_running_lock); filebench_shm->shm_procs_running = running_procs; (void) ipc_mutex_unlock(&filebench_shm->shm_procs_running_lock); (void) ipc_mutex_unlock(&filebench_shm->shm_procflow_lock); return (ret); } /* * Sets the f_abort flag and clears the running count to stop * all the flowop execution threads from running. Iterates * through the procflow list and deletes all procflows except * for the FLOW_MASTER procflow. Resets the f_abort flag when * finished. * */ void procflow_shutdown(void) { procflow_t *procflow, *next_procflow; int wait_cnt = SHUTDOWN_WAIT_SECONDS; (void) ipc_mutex_lock(&filebench_shm->shm_procs_running_lock); if (filebench_shm->shm_procs_running <= 0) { /* No processes running, so no need to do anything */ (void) ipc_mutex_unlock(&filebench_shm->shm_procs_running_lock); return; } (void) ipc_mutex_unlock(&filebench_shm->shm_procs_running_lock); (void) ipc_mutex_lock(&filebench_shm->shm_procflow_lock); if (filebench_shm->shm_f_abort == FILEBENCH_ABORT_FINI) { (void) ipc_mutex_unlock( &filebench_shm->shm_procflow_lock); return; } procflow = filebench_shm->shm_procflowlist; if (filebench_shm->shm_f_abort == FILEBENCH_OK) filebench_shm->shm_f_abort = FILEBENCH_ABORT_DONE; while (procflow) { if (procflow->pf_instance && (procflow->pf_instance == FLOW_MASTER)) { procflow = procflow->pf_next; continue; } filebench_log(LOG_DEBUG_IMPL, "Deleting process %s-%d %d", procflow->pf_name, procflow->pf_instance, procflow->pf_pid); next_procflow = procflow->pf_next; /* * Signalling the process with SIGUSR1 will result in it * gracefully shutting down and exiting */ procflow_sleep(procflow, wait_cnt); if (procflow->pf_running) { pid_t pid; pid = procflow->pf_pid; #ifdef HAVE_SIGSEND (void) sigsend(P_PID, pid, SIGUSR1); #else (void) kill(pid, SIGUSR1); #endif procflow_wait(pid); } (void) procflow_cleanup(procflow); procflow = next_procflow; if (wait_cnt > 0) wait_cnt--; } filebench_shm->shm_f_abort = FILEBENCH_ABORT_FINI; (void) ipc_mutex_unlock(&filebench_shm->shm_procflow_lock); /* indicate all processes are stopped, even if some are "stuck" */ (void) ipc_mutex_lock(&filebench_shm->shm_procs_running_lock); filebench_shm->shm_procs_running = 0; (void) ipc_mutex_unlock(&filebench_shm->shm_procs_running_lock); } /* * Create an in-memory process object. Allocates a procflow * entity, initialized from the "inherit" procflow if supplied. * The name and instance number are set from the supplied name * and instance number and the procflow is added to the head of * the master procflow list. Returns pointer to the allocated * procflow, or NULL if a name isn't supplied or the procflow * entity cannot be allocated. * * The calling routine must hold the filebench_shm->shm_procflow_lock. */ static procflow_t * procflow_define_common(procflow_t **list, char *name, procflow_t *inherit, int instance) { procflow_t *procflow; if (name == NULL) return (NULL); procflow = (procflow_t *)ipc_malloc(FILEBENCH_PROCFLOW); if (procflow == NULL) return (NULL); if (inherit) (void) memcpy(procflow, inherit, sizeof (procflow_t)); else (void) memset(procflow, 0, sizeof (procflow_t)); procflow->pf_instance = instance; (void) strcpy(procflow->pf_name, name); filebench_log(LOG_DEBUG_IMPL, "defining process %s-%d", name, instance); /* Add procflow to list, lock is being held already */ if (*list == NULL) { *list = procflow; procflow->pf_next = NULL; } else { procflow->pf_next = *list; *list = procflow; } filebench_log(LOG_DEBUG_IMPL, "process %s-%d proclist %zx", name, instance, filebench_shm->shm_procflowlist); return (procflow); } /* * Create an in-memory process object as described by the syntax. * Acquires the filebench_shm->shm_procflow_lock and calls * procflow_define_common() to create and initialize a * FLOW_MASTER procflow entity from the optional "inherit" * procflow with the given name and configured for "instances" * number of worker procflows. Currently only called from * parser_proc_define(). */ procflow_t * procflow_define(char *name, avd_t instances) { procflow_t *procflow; (void) ipc_mutex_lock(&filebench_shm->shm_procflow_lock); procflow = procflow_define_common(&filebench_shm->shm_procflowlist, name, NULL, FLOW_MASTER); procflow->pf_instances = instances; (void) ipc_mutex_unlock(&filebench_shm->shm_procflow_lock); return (procflow); } /* * Creates and starts all defined procflow processes. The call to * procflow_init() results in creation of the requested number of * process instances for each previously defined procflow. The * child processes exec() a new instance of filebench, passing it * the instance number and address of the shared memory region. * The child processes will then create their threads and flowops. * The routine then unlocks the run_lock to allow all the processes' * threads to start and waits for all of them to begin execution. * Finally, it records the start time and resets the event generation * system. */ void proc_create() { filebench_shm->shm_1st_err = 0; filebench_shm->shm_f_abort = FILEBENCH_OK; (void) pthread_rwlock_rdlock(&filebench_shm->shm_run_lock); if (procflow_init() != 0) { filebench_log(LOG_ERROR, "Failed to create processes\n"); filebench_shutdown(1); } /* Wait for all threads to start */ if (procflow_allstarted() != 0) { filebench_log(LOG_ERROR, "Could not start run"); return; } /* * Make sure we create the shared memory before we wake up worker * processes, which will alloc memory from this shm. */ if (filebench_shm->shm_required && (ipc_ismcreate(filebench_shm->shm_required) < 0)) { filebench_log(LOG_ERROR, "Could not allocate shared memory"); return; } /* Release the read lock, allowing threads to start */ (void) pthread_rwlock_unlock(&filebench_shm->shm_run_lock); filebench_shm->shm_starttime = gethrtime(); eventgen_reset(); } /* * Shuts down all processes and their associated threads. When finished * it deletes interprocess shared memory and resets the event generator. * It does not exit the filebench program though. */ void proc_shutdown() { filebench_log(LOG_INFO, "Shutting down processes"); procflow_shutdown(); if (filebench_shm->shm_required) ipc_ismdelete(); eventgen_reset(); }
23,056
26.38361
95
c
filebench
filebench-master/procflow.h
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _FB_PROCFLOW_H #define _FB_PROCFLOW_H #pragma ident "%Z%%M% %I% %E% SMI" #include "filebench.h" typedef struct procflow { char pf_name[128]; int pf_instance; avd_t pf_instances; int pf_running; flag_t pf_threads_defined_flag; struct procflow *pf_next; pid_t pf_pid; pthread_t pf_tid; struct threadflow *pf_threads; int pf_attrs; avd_t pf_nice; } procflow_t; procflow_t *procflow_define(char *name, avd_t instances); void proc_create(void); void procflow_shutdown(void); void proc_shutdown(void); int procflow_exec(char *name, int instance); #endif /* _FB_PROCFLOW_H */
1,536
27.462963
70
h
filebench
filebench-master/stats.c
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #include <stdio.h> #include <fcntl.h> #include <sys/types.h> #include <stdarg.h> #include <limits.h> #include "filebench.h" #include "flowop.h" #include "vars.h" #include "stats.h" #include "fbtime.h" /* * A set of routines for collecting and dumping various filebench * run statistics. */ /* Global statistics */ static struct flowstats *globalstats = NULL; /* * Add a flowstat b to a, leave sum in a. */ static void stats_add(struct flowstats *a, struct flowstats *b) { int i; a->fs_count += b->fs_count; a->fs_rcount += b->fs_rcount; a->fs_wcount += b->fs_wcount; a->fs_bytes += b->fs_bytes; a->fs_rbytes += b->fs_rbytes; a->fs_wbytes += b->fs_wbytes; a->fs_total_lat += b->fs_total_lat; if (b->fs_maxlat > a->fs_maxlat) a->fs_maxlat = b->fs_maxlat; if (b->fs_minlat < a->fs_minlat) a->fs_minlat = b->fs_minlat; for (i = 0; i < OSPROF_BUCKET_NUMBER; i++) a->fs_distribution[i] += b->fs_distribution[i]; } /* * Takes a "snapshot" of the global statistics. Actually, it calculates * them from the local statistics maintained by each flowop. * First the routine pauses filebench, then rolls the statistics for * each flowop into its associated FLOW_MASTER flowop. * Next all the FLOW_MASTER flowops' statistics are written * to the log file followed by the global totals. Then filebench * operation is allowed to resume. */ void stats_snap(void) { struct flowstats *iostat = &globalstats[FLOW_TYPE_IO]; struct flowstats *aiostat = &globalstats[FLOW_TYPE_AIO]; hrtime_t orig_starttime; flowop_t *flowop; char *str; double total_time_sec; if (!globalstats) { filebench_log(LOG_ERROR, "'stats snap' called before 'stats clear'"); return; } /* don't print out if run ended in error */ if (filebench_shm->shm_f_abort == FILEBENCH_ABORT_ERROR) { filebench_log(LOG_ERROR, "NO VALID RESULTS! Filebench run terminated prematurely"); return; } /* Freeze statistics during update */ filebench_shm->shm_bequiet = 1; /* We want to have blank global statistics each * time we start the summation process, but the * statistics collection start time must remain * unchanged (it's a snapshot compared to the original * start time). */ orig_starttime = globalstats->fs_stime; (void) memset(globalstats, 0, FLOW_TYPES * sizeof(struct flowstats)); globalstats->fs_stime = orig_starttime; globalstats->fs_etime = gethrtime(); total_time_sec = (globalstats->fs_etime - globalstats->fs_stime) / SEC2NS_FLOAT; filebench_log(LOG_DEBUG_SCRIPT, "Stats period = %.0f sec", total_time_sec); /* Similarly we blank the master flowop statistics */ flowop = filebench_shm->shm_flowoplist; while (flowop) { if (flowop->fo_instance == FLOW_MASTER) { (void) memset(&flowop->fo_stats, 0, sizeof(struct flowstats)); flowop->fo_stats.fs_minlat = ULLONG_MAX; } flowop = flowop->fo_next; } /* Roll up per-flowop statistics in globalstats and master flowops */ flowop = filebench_shm->shm_flowoplist; while (flowop) { flowop_t *flowop_master; if (flowop->fo_instance <= FLOW_DEFINITION) { flowop = flowop->fo_next; continue; } /* Roll up per-flowop into global stats */ stats_add(&globalstats[flowop->fo_type], &flowop->fo_stats); stats_add(&globalstats[FLOW_TYPE_GLOBAL], &flowop->fo_stats); flowop_master = flowop_find_one(flowop->fo_name, FLOW_MASTER); if (flowop_master) { /* Roll up per-flowop stats into master */ stats_add(&flowop_master->fo_stats, &flowop->fo_stats); } else { filebench_log(LOG_DEBUG_NEVER, "flowop_stats could not find %s", flowop->fo_name); } filebench_log(LOG_DEBUG_SCRIPT, "flowop %-20s-%4d - %5d ops %5.1lf ops/sec %5.1lfmb/s " "%8.3fms/op", flowop->fo_name, flowop->fo_instance, flowop->fo_stats.fs_count, flowop->fo_stats.fs_count / total_time_sec, (flowop->fo_stats.fs_bytes / MB_FLOAT) / total_time_sec, flowop->fo_stats.fs_count ? flowop->fo_stats.fs_total_lat / (flowop->fo_stats.fs_count * SEC2MS_FLOAT) : 0); flowop = flowop->fo_next; } flowop = filebench_shm->shm_flowoplist; str = malloc(1048576); *str = '\0'; (void) strcpy(str, "Per-Operation Breakdown\n"); while (flowop) { char line[1024]; char histogram[1024]; char hist_reading[20]; int i = 0; if (flowop->fo_instance != FLOW_MASTER) { flowop = flowop->fo_next; continue; } (void) snprintf(line, sizeof(line), "%-20s %dops %8.0lfops/s " "%5.1lfmb/s %8.3fms/op", flowop->fo_name, flowop->fo_stats.fs_count, flowop->fo_stats.fs_count / total_time_sec, (flowop->fo_stats.fs_bytes / MB_FLOAT) / total_time_sec, flowop->fo_stats.fs_count ? flowop->fo_stats.fs_total_lat / (flowop->fo_stats.fs_count * SEC2MS_FLOAT) : 0); (void) strcat(str, line); (void) snprintf(line, sizeof(line)," [%.3fms - %5.3fms]", flowop->fo_stats.fs_minlat / SEC2MS_FLOAT, flowop->fo_stats.fs_maxlat / SEC2MS_FLOAT); (void) strcat(str, line); if (filebench_shm->lathist_enabled) { (void) sprintf(histogram, "\t[ "); for (i = 0; i < OSPROF_BUCKET_NUMBER; i++) { (void) sprintf(hist_reading, "%lu ", flowop->fo_stats.fs_distribution[i]); (void) strcat(histogram, hist_reading); } (void) strcat(histogram, "]\n"); (void) strcat(str, histogram); } else (void) strcat(str, "\n"); flowop = flowop->fo_next; } /* removing last \n */ str[strlen(str) - 1] = '\0'; filebench_log(LOG_INFO, "%s", str); free(str); filebench_log(LOG_INFO, "IO Summary: %5d ops %5.3lf ops/s %0.0lf/%0.0lf rd/wr " "%5.1lfmb/s %5.3fms/op", iostat->fs_count + aiostat->fs_count, (iostat->fs_count + aiostat->fs_count) / total_time_sec, (iostat->fs_rcount + aiostat->fs_rcount) / total_time_sec, (iostat->fs_wcount + aiostat->fs_wcount) / total_time_sec, ((iostat->fs_bytes + aiostat->fs_bytes) / MB_FLOAT) / total_time_sec, (iostat->fs_count + aiostat->fs_count) ? (iostat->fs_total_lat + aiostat->fs_total_lat) / ((iostat->fs_count + aiostat->fs_count) * SEC2MS_FLOAT) : 0); filebench_shm->shm_bequiet = 0; } /* * Clears all the statistics variables (fo_stats) for every defined flowop. * It also creates a global flowstat table if one doesn't already exist and * clears it. */ void stats_clear(void) { flowop_t *flowop; if (globalstats == NULL) globalstats = malloc(FLOW_TYPES * sizeof (struct flowstats)); (void) memset(globalstats, 0, FLOW_TYPES * sizeof (struct flowstats)); flowop = filebench_shm->shm_flowoplist; while (flowop) { filebench_log(LOG_DEBUG_IMPL, "Clearing stats for %s-%d", flowop->fo_name, flowop->fo_instance); (void) memset(&flowop->fo_stats, 0, sizeof (struct flowstats)); flowop = flowop->fo_next; } (void) memset(globalstats, 0, sizeof(struct flowstats)); globalstats->fs_stime = gethrtime(); }
7,813
28.048327
75
c
filebench
filebench-master/stats.h
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _FB_STATS_H #define _FB_STATS_H #include "filebench.h" #include "fbtime.h" void stats_clear(void); void stats_snap(void); #define OSPROF_BUCKET_NUMBER 64 struct flowstats { /* Eight fields below are updated per each flowop and * added up in globalstats and master flowop at stats_snap() */ int fs_count; /* Number of ops */ uint64_t fs_rcount; /* Number of read ops */ uint64_t fs_wcount; /* Number of write ops */ uint64_t fs_bytes; /* Number of bytes read/written */ uint64_t fs_rbytes; /* Number of bytes read */ uint64_t fs_wbytes; /* Number of bytes written */ unsigned long fs_distribution[OSPROF_BUCKET_NUMBER]; /* Used for OSprof */ hrtime_t fs_total_lat; unsigned long long fs_maxlat; /* max flowop latency (nanoseconds) */ unsigned long long fs_minlat; /* min flowop latency (nanoseconds) */ /* These two fields are used only in globalstats variable * to note the total time of statistics collection: from * stats_clear() to stats_snap() */ hrtime_t fs_stime; hrtime_t fs_etime; }; #define IS_FLOW_IOP(x) (x->fo_stats.fs_rcount + x->fo_stats.fs_wcount) #define STAT_IOPS(x) ((x->fs_rcount) + (x->fs_wcount)) #define IS_FLOW_ACTIVE(x) (x->fo_stats.fs_count) #define STAT_CPUTIME(x) (x->fs_cpu_op) #define STAT_OHEADTIME(x) (x->fs_cpu_ohead) #endif /* _FB_STATS_H */
2,242
32.477612
75
h
filebench
filebench-master/threadflow.c
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * Portions Copyright 2008 Denis Cheng */ #include "config.h" #include <pthread.h> #include <signal.h> #include "filebench.h" #include "threadflow.h" #include "flowop.h" #include "ipc.h" static threadflow_t *threadflow_define_common(procflow_t *procflow, char *name, threadflow_t *inherit, int instance); /* * Threadflows are filebench entities which manage operating system * threads. Each worker threadflow spawns a separate filebench thread, * with attributes inherited from a FLOW_MASTER threadflow created during * f model language parsing. This section contains routines to define, * create, control, and delete threadflows. * * Each thread defined in the f model creates a FLOW_MASTER * threadflow which encapsulates the defined attributes and flowops of * the f language thread, including the number of instances to create. * At runtime, a worker threadflow instance with an associated filebench * thread is created, which runs until told to quit or is specifically * deleted. */ /* * Creates a thread for the supplied threadflow. If interprocess * shared memory is desired, then increments the amount of shared * memory needed by the amount specified in the threadflow's * tf_memsize parameter. The thread starts in routine * flowop_start() with a poineter to the threadflow supplied * as the argument. */ static int threadflow_createthread(threadflow_t *threadflow) { fbint_t memsize; memsize = avd_get_int(threadflow->tf_memsize); threadflow->tf_constmemsize = memsize; int ret; filebench_log(LOG_DEBUG_SCRIPT, "Creating thread %s, memory = %ld", threadflow->tf_name, memsize); if (threadflow->tf_attrs & THREADFLOW_USEISM) filebench_shm->shm_required += memsize; ret = pthread_create(&threadflow->tf_tid, NULL, (void *(*)(void*))flowop_start, threadflow); if (ret != 0) { filebench_log(LOG_ERROR, "thread create failed: %s", strerror(ret)); filebench_shutdown(1); return (FILEBENCH_ERROR); } return (FILEBENCH_OK); } /* * Creates threads for the threadflows associated with a procflow. * The routine iterates through the list of threadflows in the * supplied procflow's pf_threads list. For each threadflow on * the list, it defines tf_instances number of cloned * threadflows, and then calls threadflow_createthread() for * each to create and start the actual operating system thread. * Note that each of the newly defined threadflows will be linked * into the procflows threadflow list, but at the head of the * list, so they will not become part of the supplied set. After * all the threads have been created, threadflow_init enters * a join loop for all the threads in the newly defined * threadflows. Once all the created threads have exited, * threadflow_init will return 0. If errors are encountered, it * will return a non zero value. */ int threadflow_init(procflow_t *procflow) { threadflow_t *threadflow = procflow->pf_threads; int ret = 0; (void) ipc_mutex_lock(&filebench_shm->shm_threadflow_lock); while (threadflow) { threadflow_t *newthread; int instances; int i; instances = avd_get_int(threadflow->tf_instances); filebench_log(LOG_VERBOSE, "Starting %d %s threads", instances, threadflow->tf_name); for (i = 1; i < instances; i++) { /* Create threads */ newthread = threadflow_define_common(procflow, threadflow->tf_name, threadflow, i + 1); if (newthread == NULL) return (-1); ret |= threadflow_createthread(newthread); } newthread = threadflow_define_common(procflow, threadflow->tf_name, threadflow, 1); if (newthread == NULL) return (-1); /* Create each thread */ ret |= threadflow_createthread(newthread); threadflow = threadflow->tf_next; } threadflow = procflow->pf_threads; (void) ipc_mutex_unlock(&filebench_shm->shm_threadflow_lock); /* * All threadflows for this process were defined. * Inform process creator thread about that. * When all thread monitors set this flag (in their * corresponding procflow structures), the process creator * thread will set shm_procflows_defined_flag, which * will allow main process to continue. */ set_flag(&procflow->pf_threads_defined_flag); while (threadflow) { /* wait for all threads to finish */ if (threadflow->tf_tid) { void *status; if (pthread_join(threadflow->tf_tid, &status) == 0) ret += *(int *)status; } threadflow = threadflow->tf_next; } procflow->pf_running = 0; return (ret); } /* * Tells the threadflow's thread to stop and optionally signals * its associated process to end the thread. */ static void threadflow_kill(threadflow_t *threadflow) { int wait_cnt = 2; /* Tell thread to finish */ threadflow->tf_abort = 1; /* wait a bit for threadflow to stop */ while (wait_cnt && threadflow->tf_running) { (void) sleep(1); wait_cnt--; } if (threadflow->tf_running) { threadflow->tf_running = FALSE; (void) pthread_kill(threadflow->tf_tid, SIGKILL); } } /* * Deletes the specified threadflow from the specified threadflow * list after first terminating the threadflow's thread, deleting * the threadflow's flowops, and finally freeing the threadflow * entity. It also subtracts the threadflow's shared memory * requirements from the total amount required, shm_required. If * the specified threadflow is found, returns 0, otherwise * returns -1. */ static int threadflow_delete(threadflow_t **threadlist, threadflow_t *threadflow) { threadflow_t *entry = *threadlist; filebench_log(LOG_DEBUG_IMPL, "Deleting thread: (%s-%d)", threadflow->tf_name, threadflow->tf_instance); if (threadflow->tf_attrs & THREADFLOW_USEISM) filebench_shm->shm_required -= threadflow->tf_constmemsize; if (threadflow == *threadlist) { /* First on list */ filebench_log(LOG_DEBUG_IMPL, "Deleted thread: (%s-%d)", threadflow->tf_name, threadflow->tf_instance); threadflow_kill(threadflow); flowop_delete_all(&threadflow->tf_thrd_fops); *threadlist = threadflow->tf_next; (void) pthread_mutex_destroy(&threadflow->tf_lock); ipc_free(FILEBENCH_THREADFLOW, (char *)threadflow); return (0); } while (entry->tf_next) { filebench_log(LOG_DEBUG_IMPL, "Delete thread: (%s-%d) == (%s-%d)", entry->tf_next->tf_name, entry->tf_next->tf_instance, threadflow->tf_name, threadflow->tf_instance); if (threadflow == entry->tf_next) { /* Delete */ filebench_log(LOG_DEBUG_IMPL, "Deleted thread: (%s-%d)", entry->tf_next->tf_name, entry->tf_next->tf_instance); threadflow_kill(entry->tf_next); flowop_delete_all(&entry->tf_next->tf_thrd_fops); (void) pthread_mutex_destroy(&threadflow->tf_lock); ipc_free(FILEBENCH_THREADFLOW, (char *)threadflow); entry->tf_next = entry->tf_next->tf_next; return (0); } entry = entry->tf_next; } return (-1); } /* * Given a pointer to the thread list of a procflow, cycles * through all the threadflows on the list, deleting each one * except the FLOW_MASTER. */ void threadflow_delete_all(threadflow_t **threadlist) { threadflow_t *threadflow; (void) ipc_mutex_lock(&filebench_shm->shm_threadflow_lock); threadflow = *threadlist; filebench_log(LOG_DEBUG_IMPL, "Deleting all threads"); while (threadflow) { if (threadflow->tf_instance && (threadflow->tf_instance == FLOW_MASTER)) { threadflow = threadflow->tf_next; continue; } (void) threadflow_delete(threadlist, threadflow); threadflow = threadflow->tf_next; } (void) ipc_mutex_unlock(&filebench_shm->shm_threadflow_lock); } /* * Waits till all threadflows are started, or a timeout occurs. * Checks through the list of threadflows, waiting up to 10 * seconds for each one to set its tf_running flag to 1. If not * set after 10 seconds, continues on to the next threadflow * anyway. */ void threadflow_allstarted(pid_t pid, threadflow_t *threadflow) { (void) ipc_mutex_lock(&filebench_shm->shm_threadflow_lock); while (threadflow) { int waits; if ((threadflow->tf_instance == 0) || (threadflow->tf_instance == FLOW_MASTER)) { threadflow = threadflow->tf_next; continue; } filebench_log(LOG_DEBUG_IMPL, "Checking pid %d thread %s-%d", pid, threadflow->tf_name, threadflow->tf_instance); waits = 10; while (waits && (threadflow->tf_running == 0) && (filebench_shm->shm_f_abort == 0)) { (void) ipc_mutex_unlock( &filebench_shm->shm_threadflow_lock); if (waits < 3) filebench_log(LOG_INFO, "Waiting for pid %d thread %s-%d", pid, threadflow->tf_name, threadflow->tf_instance); (void) sleep(1); (void) ipc_mutex_lock( &filebench_shm->shm_threadflow_lock); waits--; } threadflow = threadflow->tf_next; } (void) ipc_mutex_unlock(&filebench_shm->shm_threadflow_lock); } /* * Create an in-memory thread object linked to a parent procflow. * A threadflow entity is allocated from shared memory and * initialized from the "inherit" threadflow if supplied, * otherwise to zeros. The threadflow is assigned a unique * thread id, the supplied instance number, the supplied name * and added to the procflow's pf_thread list. If no name is * supplied or the threadflow can't be allocated, NULL is * returned Otherwise a pointer to the newly allocated threadflow * is returned. * * The filebench_shm->shm_threadflow_lock must be held by the caller. */ static threadflow_t * threadflow_define_common(procflow_t *procflow, char *name, threadflow_t *inherit, int instance) { threadflow_t *threadflow; threadflow_t **threadlistp = &procflow->pf_threads; if (name == NULL) return (NULL); threadflow = (threadflow_t *)ipc_malloc(FILEBENCH_THREADFLOW); if (threadflow == NULL) return (NULL); if (inherit) (void) memcpy(threadflow, inherit, sizeof (threadflow_t)); else (void) memset(threadflow, 0, sizeof (threadflow_t)); threadflow->tf_utid = ++filebench_shm->shm_utid; threadflow->tf_instance = instance; (void) strcpy(threadflow->tf_name, name); threadflow->tf_process = procflow; (void) pthread_mutex_init(&threadflow->tf_lock, ipc_mutexattr(IPC_MUTEX_NORMAL)); filebench_log(LOG_DEBUG_IMPL, "Defining thread %s-%d", name, instance); /* Add threadflow to list */ if (*threadlistp == NULL) { *threadlistp = threadflow; threadflow->tf_next = NULL; } else { threadflow->tf_next = *threadlistp; *threadlistp = threadflow; } return threadflow; } /* * Create an in memory FLOW_MASTER thread object as described * by the syntax. Acquire the filebench_shm->shm_threadflow_lock and * call threadflow_define_common() to create a threadflow entity. * Set the number of instances to create at runtime, * tf_instances, to "instances". Return the threadflow pointer * returned by the threadflow_define_common call. */ threadflow_t * threadflow_define(procflow_t *procflow, char *name, threadflow_t *inherit, avd_t instances) { threadflow_t *threadflow; (void) ipc_mutex_lock(&filebench_shm->shm_threadflow_lock); if ((threadflow = threadflow_define_common(procflow, name, inherit, FLOW_MASTER)) == NULL) return (NULL); threadflow->tf_instances = instances; (void) ipc_mutex_unlock(&filebench_shm->shm_threadflow_lock); return (threadflow); } /* * Searches the provided threadflow list for the named threadflow. * A pointer to the threadflow is returned, or NULL if threadflow * is not found. */ threadflow_t * threadflow_find(threadflow_t *threadlist, char *name) { threadflow_t *threadflow = threadlist; (void) ipc_mutex_lock(&filebench_shm->shm_threadflow_lock); while (threadflow) { if (strcmp(name, threadflow->tf_name) == 0) { (void) ipc_mutex_unlock( &filebench_shm->shm_threadflow_lock); return (threadflow); } threadflow = threadflow->tf_next; } (void) ipc_mutex_unlock(&filebench_shm->shm_threadflow_lock); return (NULL); }
12,856
27.507761
73
c
filebench
filebench-master/threadflow.h
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _FB_THREADFLOW_H #define _FB_THREADFLOW_H #include "filebench.h" #define AL_READ 1 #define AL_WRITE 2 #ifdef HAVE_AIO typedef struct aiolist { int al_type; struct aiolist *al_next; struct aiolist *al_worknext; struct aiocb64 al_aiocb; } aiolist_t; #endif #define THREADFLOW_MAXFD 128 #define THREADFLOW_USEISM 0x1 typedef struct threadflow { char tf_name[128]; /* Name */ int tf_attrs; /* Attributes */ int tf_instance; /* Instance number */ int tf_running; /* Thread running indicator */ int tf_abort; /* Shutdown thread */ int tf_utid; /* Unique id for thread */ struct procflow *tf_process; /* Back pointer to process */ pthread_t tf_tid; /* Thread id */ pthread_mutex_t tf_lock; /* Mutex around threadflow */ avd_t tf_instances; /* Number of instances for this flow */ struct threadflow *tf_next; /* Next on proc list */ struct flowop *tf_thrd_fops; /* Flowop list */ caddr_t tf_mem; /* Private Memory */ avd_t tf_memsize; /* Private Memory size attribute */ fbint_t tf_constmemsize; /* constant copy of memory size */ fb_fdesc_t tf_fd[THREADFLOW_MAXFD + 1]; /* Thread local fd's */ filesetentry_t *tf_fse[THREADFLOW_MAXFD + 1]; /* Thread local files */ int tf_fdrotor; /* Rotating fd within set */ struct flowstats tf_stats; /* Thread statistics */ hrtime_t tf_stime; /* Start time of current flowop: used to measure the latency of the flowop */ #ifdef HAVE_AIO aiolist_t *tf_aiolist; /* List of async I/Os */ #endif avd_t tf_ioprio; /* ioprio attribute */ } threadflow_t; /* Thread attrs */ #define THREADFLOW_DEFAULTMEM 1024*1024LL; threadflow_t *threadflow_define(procflow_t *, char *name, threadflow_t *inherit, avd_t instances); threadflow_t *threadflow_find(threadflow_t *, char *); int threadflow_init(procflow_t *); void flowop_start(threadflow_t *threadflow); void threadflow_allstarted(pid_t pid, threadflow_t *threadflow); void threadflow_delete_all(threadflow_t **threadlist); #endif /* _FB_THREADFLOW_H */
2,915
32.906977
97
h
filebench
filebench-master/utils.c
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * Portions Copyright 2008 Denis Cheng */ #include <limits.h> #include <string.h> #include <stdlib.h> #include <stdarg.h> #include <stdio.h> #include <errno.h> #ifdef HAVE_STDINT_H #include <stdint.h> #endif #include "filebench.h" #include "utils.h" #include "parsertypes.h" /* * For now, just three routines: one to allocate a string in shared * memory, one to emulate a strlcpy() function and one to emulate a * strlcat() function, both the second and third only used in non * Solaris environments, * */ /* * Allocates space for a new string of the same length as * the supplied string "str". Copies the old string into * the new string and returns a pointer to the new string. * Returns NULL if memory allocation for the new string fails. */ char * fb_stralloc(char *str) { char *newstr; if ((newstr = malloc(strlen(str) + 1)) == NULL) return (NULL); (void) strcpy(newstr, str); return (newstr); } #ifndef HAVE_STRLCPY /* * Implements the strlcpy function when compilied for non Solaris * operating systems. On solaris the strlcpy() function is used * directly. */ size_t fb_strlcpy(char *dst, const char *src, size_t dstsize) { uint_t i; for (i = 0; i < (dstsize - 1); i++) { /* quit if at end of source string */ if (src[i] == '\0') break; dst[i] = src[i]; } /* set end of dst string to \0 */ dst[i] = '\0'; i++; return (i); } #endif /* HAVE_STRLCPY */ #ifndef HAVE_STRLCAT /* * Implements the strlcat function when compilied for non Solaris * operating systems. On solaris the strlcat() function is used * directly. */ size_t fb_strlcat(char *dst, const char *src, size_t dstsize) { uint_t i, j; /* find the end of the current destination string */ for (i = 0; i < (dstsize - 1); i++) { if (dst[i] == '\0') break; } /* append the source string to the destination string */ for (j = 0; i < (dstsize - 1); i++) { if (src[j] == '\0') break; dst[i] = src[j]; j++; } /* set end of dst string to \0 */ dst[i] = '\0'; i++; return (i); } #endif /* HAVE_STRLCAT */ #ifdef HAVE_PROC_SYS_KERNEL_SHMMAX /* * Increase the maximum shared memory segment size till some large value. We do * not restore it to the old value when the Filebench run is over. If we could * not change the value - we continue execution. */ void fb_set_shmmax(void) { FILE *f; int ret; f = fopen("/proc/sys/kernel/shmmax", "r+"); if (!f) { filebench_log(LOG_FATAL, "WARNING: Could not open " "/proc/sys/kernel/shmmax file!\n" "It means that you probably ran Filebench not " "as a root. Filebench will not increase shared\n" "region limits in this case, which can lead " "to the failures on certain workloads."); return; } /* writing new value */ #define SOME_LARGE_SHMAX "268435456" /* 256 MB */ ret = fwrite(SOME_LARGE_SHMAX, sizeof(SOME_LARGE_SHMAX), 1, f); if (ret != 1) filebench_log(LOG_ERROR, "Coud not write to " "/proc/sys/kernel/shmmax file!"); #undef SOME_LARGE_SHMAX fclose(f); return; } #else /* HAVE_PROC_SYS_KERNEL_SHMMAX */ void fb_set_shmmax(void) { return; } #endif /* HAVE_PROC_SYS_KERNEL_SHMMAX */ #ifdef HAVE_SETRLIMIT /* * Increase the limit of opened files. * * We first set the limit to the hardlimit reported by the kernel; this call * will always succeed. Then we try to set the limit to some large number of * files (unfortunately we can't set this ulimit to infinity), this will only * succeed if the process is ran by root. Therefore, we always set the maximum * possible value for the limit for this given process (well, only if hardlimit * is greater then the large number of files defined by us, it is not true). * * Increasing this limit is especially important when we use thread model, * because opened files are accounted per-process, not per-thread. */ void fb_set_rlimit(void) { struct rlimit rlp; (void)getrlimit(RLIMIT_NOFILE, &rlp); rlp.rlim_cur = rlp.rlim_max; (void)setrlimit(RLIMIT_NOFILE, &rlp); #define SOME_LARGE_NUMBER_OF_FILES 50000 rlp.rlim_cur = rlp.rlim_max = SOME_LARGE_NUMBER_OF_FILES; #undef SOME_LARGE_NUMBER_OF_FILES (void)setrlimit(RLIMIT_NOFILE, &rlp); return; } #else /* HAVE_SETRLIMIT */ void fb_set_rlimit(void) { return; } #endif /* HAVE_SETRLIMIT */
5,166
23.722488
80
c
filebench
filebench-master/utils.h
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _FB_UTILS_H #define _FB_UTILS_H #include "filebench.h" extern char *fb_stralloc(char *str); #ifdef HAVE_STRLCAT #define fb_strlcat strlcat #else extern size_t fb_strlcat(char *dst, const char *src, size_t dstsize); #endif /* HAVE_STRLCAT */ #ifdef HAVE_STRLCPY #define fb_strlcpy strlcpy #else extern size_t fb_strlcpy(char *dst, const char *src, size_t dstsize); #endif /* HAVE_STRLCPY */ extern void fb_set_shmmax(void); void fb_set_rlimit(void); #endif /* _FB_UTILS_H */
1,416
27.34
70
h
filebench
filebench-master/vars.c
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. * * Portions Copyright 2008 Denis Cheng */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <assert.h> #include "filebench.h" #include "vars.h" #include "misc.h" #include "utils.h" #include "stats.h" #include "eventgen.h" #include "fb_random.h" /* * The filebench variables system has attribute value descriptors (avd_t) where * an avd contains a boolean, integer, double, string, random distribution * object ptr, boolean ptr, integer ptr, double ptr, string ptr, or variable * ptr. The system also has the variables themselves, (var_t), which are named * and typed entities that can be allocated, selected and changed using the * "set" command and used in attribute assignments. The variables contain * either a boolean, an integer, a double, a string or pointer to an associated * random distribution object. Both avd_t and var_t entities are allocated from * interprocess shared memory space. * * The attribute descriptors implement delayed binding to variable values, * which is necessary because the values of variables may be changed between * the time the workload model is loaded and the time it actually runs by * further "set" commands. * * For static attributes, the value is just loaded in the descriptor directly, * avoiding the need to allocate a variable to hold the static value. * * For random variables, they actually point to the random distribution object, * allowing Filebench to invoke the appropriate random distribution function on * each access to the attribute. * * The routines in this module are used to allocate, locate, and manipulate the * attribute descriptors and vars. Routines are also included to convert * between the component strings, doubles and integers of vars, and said * components of avd_t. */ static char * avd_get_type_textified(avd_t avd) { switch (avd->avd_type) { case AVD_INVALID: return "uninitialized"; case AVD_VAL_BOOL: return "boolean"; case AVD_VARVAL_BOOL: return "pointer to a boolean in a variable"; case AVD_VAL_INT: return "integer"; case AVD_VARVAL_INT: return "pointer to an integer in a variable"; case AVD_VAL_DBL: return "double"; case AVD_VARVAL_DBL: return "pointer to a double in a variable"; case AVD_VAL_STR: return "string"; case AVD_VARVAL_STR: return "pointer to a string in a variable"; case AVD_VARVAL_RANDOM: return "pointer to a random variable"; case AVD_VARVAL_CUSTOM: return "pointer to a custom variable"; case AVD_VARVAL_UNKNOWN: return "pointer to variable of unknown type"; default: return "illegal avd type"; } } static void set_avd_type_by_var(avd_t avd, var_t *var, int error_on_unknown) { switch (var->var_type) { case VAR_BOOL: avd->avd_type = AVD_VARVAL_BOOL; avd->avd_val.boolptr = &var->var_val.boolean; break; case VAR_INT: avd->avd_type = AVD_VARVAL_INT; avd->avd_val.intptr = &var->var_val.integer; break; case VAR_DBL: avd->avd_type = AVD_VARVAL_DBL; avd->avd_val.dblptr = &var->var_val.dbl; break; case VAR_STR: avd->avd_type = AVD_VARVAL_STR; avd->avd_val.strptr = &var->var_val.string; break; case VAR_RANDOM: avd->avd_type = AVD_VARVAL_RANDOM; avd->avd_val.randptr = var->var_val.randptr; break; case VAR_CUSTOM: avd->avd_type = AVD_VARVAL_CUSTOM; avd->avd_val.cvarptr = var->var_val.cvarptr; break; case VAR_UNKNOWN: if (error_on_unknown) { filebench_log(LOG_ERROR, "Noninitialized variable %s", var->var_name); filebench_shutdown(1); } avd->avd_type = AVD_VARVAL_UNKNOWN; avd->avd_val.varptr = var; break; default: filebench_log(LOG_ERROR, "Invalid variable type (variable: %s)", var->var_name); filebench_shutdown(1); } } boolean_t avd_get_bool(avd_t avd) { var_t *var; assert(avd); switch (avd->avd_type) { case AVD_VAL_BOOL: return avd->avd_val.boolval; case AVD_VARVAL_BOOL: assert(avd->avd_val.boolptr); return *(avd->avd_val.boolptr); case AVD_VAL_INT: if (avd->avd_val.intval) return TRUE; return FALSE; case AVD_VARVAL_INT: assert(avd->avd_val.intptr); if (*(avd->avd_val.intptr)) return TRUE; return FALSE; case AVD_VAL_DBL: if (avd->avd_val.dblval) return TRUE; return FALSE; case AVD_VARVAL_DBL: assert(avd->avd_val.dblptr); if (*(avd->avd_val.dblptr)) return TRUE; return FALSE; case AVD_VARVAL_UNKNOWN: var = avd->avd_val.varptr; set_avd_type_by_var(avd, var, 1); return avd_get_bool(avd); default: filebench_log(LOG_ERROR, "Attempt to get boolean from %s avd", avd_get_type_textified(avd)); return FALSE; } } uint64_t avd_get_int(avd_t avd) { randdist_t *rndp; cvar_t *cvar; var_t *var; assert(avd); switch (avd->avd_type) { case AVD_VAL_INT: return avd->avd_val.intval; case AVD_VARVAL_INT: assert(avd->avd_val.intptr); return *(avd->avd_val.intptr); case AVD_VAL_DBL: return (uint64_t)avd->avd_val.dblval; case AVD_VARVAL_DBL: assert(avd->avd_val.dblptr); return (uint64_t)*(avd->avd_val.dblptr); case AVD_VARVAL_RANDOM: rndp = avd->avd_val.randptr; assert(rndp); return (uint64_t)rndp->rnd_get(rndp); case AVD_VARVAL_CUSTOM: cvar = avd->avd_val.cvarptr; assert(cvar); return (uint64_t)get_cvar_value(cvar); case AVD_VARVAL_UNKNOWN: var = avd->avd_val.varptr; set_avd_type_by_var(avd, var, 1); return avd_get_int(avd); default: filebench_log(LOG_ERROR, "Attempt to get integer from %s avd", avd_get_type_textified(avd)); return 0; } } double avd_get_dbl(avd_t avd) { randdist_t *rndp; cvar_t *cvar; var_t *var; assert(avd); switch (avd->avd_type) { case AVD_VAL_DBL: return avd->avd_val.dblval; case AVD_VARVAL_DBL: assert(avd->avd_val.dblptr); return *(avd->avd_val.dblptr); case AVD_VAL_INT: return (double)avd->avd_val.intval; case AVD_VARVAL_INT: assert(avd->avd_val.intptr); return (double)(*(avd->avd_val.intptr)); case AVD_VARVAL_RANDOM: rndp = avd->avd_val.randptr; assert(rndp); return rndp->rnd_get(rndp); case AVD_VARVAL_CUSTOM: cvar = avd->avd_val.cvarptr; assert(cvar); return get_cvar_value(cvar); case AVD_VARVAL_UNKNOWN: var = avd->avd_val.varptr; set_avd_type_by_var(avd, var, 1); return avd_get_dbl(avd); default: filebench_log(LOG_ERROR, "Attempt to get floating point from %s avd", avd_get_type_textified(avd)); return 0.0; } } char * avd_get_str(avd_t avd) { assert(avd); var_t *var; switch (avd->avd_type) { case AVD_VAL_STR: return avd->avd_val.strval; case AVD_VARVAL_STR: assert(avd->avd_val.strptr); return *avd->avd_val.strptr; case AVD_VARVAL_UNKNOWN: var = avd->avd_val.varptr; set_avd_type_by_var(avd, var, 1); return avd_get_str(avd); default: filebench_log(LOG_ERROR, "Attempt to get string from %s avd", avd_get_type_textified(avd)); return NULL; } } static avd_t avd_alloc_cmn(void) { avd_t avd; avd = (avd_t)ipc_malloc(FILEBENCH_AVD); if (!avd) filebench_log(LOG_ERROR, "AVD allocation failed"); return avd; } avd_t avd_bool_alloc(boolean_t val) { avd_t avd; avd = avd_alloc_cmn(); if (!avd) return NULL; avd->avd_type = AVD_VAL_BOOL; avd->avd_val.boolval = val; return avd; } avd_t avd_int_alloc(uint64_t val) { avd_t avd; avd = avd_alloc_cmn(); if (!avd) return NULL; avd->avd_type = AVD_VAL_INT; avd->avd_val.intval = val; return avd; } avd_t avd_dbl_alloc(double val) { avd_t avd; avd = avd_alloc_cmn(); if (!avd) return NULL; avd->avd_type = AVD_VAL_DBL; avd->avd_val.dblval = val; return avd; } avd_t avd_str_alloc(char *string) { avd_t avd; assert(string); avd = avd_alloc_cmn(); if (!avd) return NULL; avd->avd_type = AVD_VAL_STR; avd->avd_val.strval = ipc_stralloc(string); return avd; } static var_t * var_alloc(char *name) { var_t *var; var = (var_t *)ipc_malloc(FILEBENCH_VARIABLE); if (!var) { filebench_log(LOG_ERROR, "Out of memory for variables"); return NULL; } memset(var, 0, sizeof(*var)); VAR_SET_UNKNOWN(var); var->var_name = ipc_stralloc(name); if (!var->var_name) { filebench_log(LOG_ERROR, "Out of memory for strings"); return NULL; } var->var_next = filebench_shm->shm_var_list; filebench_shm->shm_var_list = var; return var; } static var_t * var_find(char *name) { var_t *var; for (var = filebench_shm->shm_var_list; var; var = var->var_next) if (!strcmp(var->var_name, name)) return var; return NULL; } static var_t * var_find_alloc(char *name) { var_t *var; var = var_find(name); if (!var) var = var_alloc(name); return var; } int var_assign_boolean(char *name, boolean_t bool) { var_t *var; var = var_find_alloc(name); if (!var) { filebench_log(LOG_ERROR, "Could not assign variable %s", name); return -1; } VAR_SET_BOOL(var, bool); return 0; } int var_assign_integer(char *name, uint64_t integer) { var_t *var; var = var_find_alloc(name); if (!var) { filebench_log(LOG_ERROR, "Could not assign variable %s", name); return -1; } VAR_SET_INT(var, integer); return 0; } int var_assign_double(char *name, double dbl) { var_t *var; var = var_find_alloc(name); if (!var) { filebench_log(LOG_ERROR, "Could not assign variable %s", name); return -1; } VAR_SET_DBL(var, dbl); return 0; } int var_assign_string(char *name, char *string) { var_t *var; char *strptr; var = var_find_alloc(name); if (!var) { filebench_log(LOG_ERROR, "Could not assign variable %s", name); return -1; } strptr = ipc_stralloc(string); if (!strptr) { filebench_log(LOG_ERROR, "Could not assign variable %s", name); return -1; } VAR_SET_STR(var, strptr); return 0; } int var_assign_random(char *name, randdist_t *rndp) { var_t *var; var = var_find_alloc(name); if (!var) { filebench_log(LOG_ERROR, "Could not assign variable %s", name); return -1; } VAR_SET_RANDOM(var, rndp); return 0; } int var_assign_custom(char *name, struct cvar *cvar) { var_t *var; var = var_find_alloc(name); if (!var) { filebench_log(LOG_ERROR, "Could not assign variable %s", name); return -1; } VAR_SET_CUSTOM(var, cvar); return 0; } /* * This function is called during the workload description parsing prior to the * execution phase. It is called when parser encounters a variable used as a * value (for attributes or command arguments, e.g., instances=$myinstances). * * At this point, the user might or might NOT have set the value (and consequently * its type is not known as well). */ avd_t avd_var_alloc(char *varname) { var_t *var; avd_t avd; var = var_find_alloc(varname); if (!var) { filebench_log(LOG_ERROR, "Could not access variable %s", varname); filebench_shutdown(1); } avd = avd_alloc_cmn(); if (!avd) return NULL; set_avd_type_by_var(avd, var, 0); return avd; } static char * __var_to_string(var_t *var) { char tmp[128]; if (VAR_HAS_RANDOM(var)) { switch (var->var_val.randptr->rnd_type & RAND_TYPE_MASK) { case RAND_TYPE_UNIFORM: return fb_stralloc("uniform random var"); case RAND_TYPE_GAMMA: return fb_stralloc("gamma random var"); case RAND_TYPE_TABLE: return fb_stralloc("tabular random var"); default: return fb_stralloc("unitialized random var"); } } if (VAR_HAS_CUSTOM(var)) return fb_stralloc("custom variable"); if (VAR_HAS_STRING(var) && var->var_val.string) return fb_stralloc(var->var_val.string); if (VAR_HAS_BOOLEAN(var)) { if (var->var_val.boolean) return fb_stralloc("true"); else return fb_stralloc("false"); } if (VAR_HAS_INTEGER(var)) { (void) snprintf(tmp, sizeof (tmp), "%llu", (u_longlong_t)var->var_val.integer); return fb_stralloc(tmp); } if (VAR_HAS_DOUBLE(var)) { (void) snprintf(tmp, sizeof (tmp), "%lf", var->var_val.dbl); return fb_stralloc(tmp); } return fb_stralloc("No default"); } char * var_to_string(char *name) { var_t *var; var = var_find(name); if (!var) return NULL; return __var_to_string(var); } char * var_randvar_to_string(char *name, int param_name) { var_t *var; uint64_t value; char tmp[128]; var = var_find(name); if (!var) return var_to_string(name); if (!VAR_HAS_RANDOM(var)) return var_to_string(name); switch (param_name) { case RAND_PARAM_TYPE: switch (var->var_val.randptr->rnd_type & RAND_TYPE_MASK) { case RAND_TYPE_UNIFORM: return fb_stralloc("uniform"); case RAND_TYPE_GAMMA: return fb_stralloc("gamma"); case RAND_TYPE_TABLE: return fb_stralloc("tabular"); default: return fb_stralloc("uninitialized"); } case RAND_PARAM_SRC: if (var->var_val.randptr->rnd_type & RAND_SRC_GENERATOR) return fb_stralloc("rand48"); else return fb_stralloc("urandom"); case RAND_PARAM_SEED: value = avd_get_int(var->var_val.randptr->rnd_seed); break; case RAND_PARAM_MIN: value = avd_get_int(var->var_val.randptr->rnd_min); break; case RAND_PARAM_MEAN: value = avd_get_int(var->var_val.randptr->rnd_mean); break; case RAND_PARAM_GAMMA: value = avd_get_int(var->var_val.randptr->rnd_gamma); break; case RAND_PARAM_ROUND: value = avd_get_int(var->var_val.randptr->rnd_round); break; default: return NULL; } /* just an integer value if we got here */ (void) snprintf(tmp, sizeof (tmp), "%llu", (u_longlong_t)value); return (fb_stralloc(tmp)); } /* XXX: Local variables related */ static var_t * var_find_list_only(char *name, var_t *var_list) { var_t *var; for (var = var_list; var; var = var->var_next) { if (!strcmp(var->var_name, name)) return var; } return NULL; } static var_t * var_find_local_normal(char *name) { var_t *var; var = var_find_list_only(name, filebench_shm->shm_var_loc_list); if (!var) var = var_find_list_only(name, filebench_shm->shm_var_list); return var; } /* * Copies the value stored in the source variable into the destination * variable. Returns -1 if any problems encountered, 0 otherwise. */ static int var_copy(var_t *dst_var, var_t *src_var) { char *strptr; if (VAR_HAS_BOOLEAN(src_var)) VAR_SET_BOOL(dst_var, src_var->var_val.boolean); if (VAR_HAS_INTEGER(src_var)) VAR_SET_INT(dst_var, src_var->var_val.integer); if (VAR_HAS_DOUBLE(src_var)) VAR_SET_DBL(dst_var, src_var->var_val.dbl); if (VAR_HAS_STRING(src_var)) { strptr = ipc_stralloc(src_var->var_val.string); if (!strptr) { filebench_log(LOG_ERROR, "Cannot assign string for variable %s", dst_var->var_name); return -1; } VAR_SET_STR(dst_var, strptr); } return 0; } /* * Allocates a local var (var_t) from interprocess shared memory after * first adjusting the name to elminate the leading $. */ var_t * var_lvar_alloc_local(char *name) { return var_alloc(name); } /* * Allocates a local var and then extracts the var_string from * the var named "string" and copies it into the var_string * of the var "name", after first allocating a piece of * interprocess shared string memory. Returns a pointer to the * newly allocated local var or NULL on error. */ var_t * var_lvar_assign_var(char *name, char *src_name) { var_t *dst_var, *src_var; char *strptr; src_name += 1; src_var = var_find_local_normal(src_name); if (!src_var) { filebench_log(LOG_ERROR, "Cannot find source variable %s", src_name); return NULL; } dst_var = var_lvar_alloc_local(name); if (!dst_var) { filebench_log(LOG_ERROR, "Cannot assign variable %s", name); return NULL; } if (VAR_HAS_BOOLEAN(src_var)) { VAR_SET_BOOL(dst_var, src_var->var_val.boolean); } else if (VAR_HAS_INTEGER(src_var)) { VAR_SET_INT(dst_var, src_var->var_val.integer); } else if (VAR_HAS_STRING(src_var)) { strptr = ipc_stralloc(src_var->var_val.string); if (!strptr) { filebench_log(LOG_ERROR, "Cannot assign variable %s", name); return NULL; } VAR_SET_STR(dst_var, strptr); } else if (VAR_HAS_DOUBLE(src_var)) { VAR_SET_INT(dst_var, src_var->var_val.dbl); } else if (VAR_HAS_RANDOM(src_var)) VAR_SET_RANDOM(dst_var, src_var->var_val.randptr); return dst_var; } var_t * var_lvar_assign_boolean(char *name, boolean_t bool) { var_t *var; var = var_lvar_alloc_local(name); if (!var) { filebench_log(LOG_ERROR, "Cannot assign variable %s", name); return NULL; } VAR_SET_BOOL(var, bool); return var; } var_t * var_lvar_assign_integer(char *name, uint64_t integer) { var_t *var; var = var_lvar_alloc_local(name); if (!var) { filebench_log(LOG_ERROR, "Cannot assign variable %s", name); return NULL; } VAR_SET_INT(var, integer); return var; } var_t * var_lvar_assign_double(char *name, double dbl) { var_t *var; var = var_lvar_alloc_local(name); if (!var) { filebench_log(LOG_ERROR, "Cannot assign variable %s", name); return NULL; } VAR_SET_DBL(var, dbl); return var; } var_t * var_lvar_assign_string(char *name, char *string) { var_t *var; char *strptr; var = var_lvar_alloc_local(name); if (!var) { filebench_log(LOG_ERROR, "Cannot assign variable %s", name); return NULL; } strptr = ipc_stralloc(string); if (!strptr) { filebench_log(LOG_ERROR, "Cannot assign variable %s", name); return NULL; } VAR_SET_STR(var, strptr); return var; } /* * replace the avd_t attribute value descriptor in the new FLOW_MASTER flowop * that points to a local variable with a new avd_t containing * the actual value from the local variable. */ void avd_update(avd_t *avdp, var_t *lvar_list) { /* Empty or not indirect, so no update needed */ return; } void var_update_comp_lvars(var_t *newlvar, var_t *proto_comp_vars, var_t *mstr_lvars) { var_t *proto_lvar; /* find the prototype lvar from the inherited list */ proto_lvar = var_find_list_only(newlvar->var_name, proto_comp_vars); if (!proto_lvar) return; /* * if the new local variable has not already been assigned * a value, try to copy a value from the prototype local variable */ if (VAR_HAS_UNKNOWN(newlvar)) { /* copy value from prototype lvar to new lvar */ (void) var_copy(newlvar, proto_lvar); } }
18,834
19.974388
82
c
filebench
filebench-master/vars.h
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2009 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _VARS_H #define _VARS_H #include "filebench.h" /* Attribute Value Descriptor (AVD) types */ typedef enum avd_type { AVD_INVALID = 0, /* avd is empty */ AVD_VAL_BOOL, /* avd contains a boolean_t */ AVD_VARVAL_BOOL, /* avd points to the boolean_t in a var_t */ AVD_VAL_INT, /* avd contains an uint64_t */ AVD_VARVAL_INT, /* avd points to the uint64_t in a var_t */ AVD_VAL_DBL, /* avd contains a double float */ AVD_VARVAL_DBL, /* avd points to the double in a var_t */ AVD_VAL_STR, /* avd contains a sting (*char) */ AVD_VARVAL_STR, /* avd points to a string in a var_t */ AVD_VARVAL_UNKNOWN, /* avd points to a variable whose type is not * known yet */ AVD_VARVAL_RANDOM, /* avd points to the randdist_t associated */ /* with a random variable type var_t */ AVD_VARVAL_CUSTOM /* avd points to the cvar_t associated */ /* with a custom variable type var_t */ } avd_type_t; /* Attribute Value Descriptor (AVD) */ typedef struct avd { avd_type_t avd_type; union { boolean_t boolval; boolean_t *boolptr; uint64_t intval; uint64_t *intptr; double dblval; double *dblptr; char *strval; char **strptr; struct var *varptr; /* * Used by AVDs that point to * uninitialized variables of * yet unknown type. */ struct randdist *randptr; struct cvar *cvarptr; } avd_val; } *avd_t; #define AVD_IS_RANDOM(vp) ((vp) && ((vp)->avd_type == AVD_VARVAL_RANDOM)) #define AVD_IS_STRING(vp) ((vp) && (((vp)->avd_type == AVD_VAL_STR) || \ ((vp)->avd_type == AVD_VARVAL_STR))) #define AVD_IS_BOOL(vp) ((vp) && (((vp)->avd_type == AVD_VAL_BOOL) || \ ((vp)->avd_type == AVD_VARVAL_BOOL))) #define AVD_IS_INT(vp) ((vp) && (((vp)->avd_type == AVD_VAL_INT) || \ ((vp)->avd_type == AVD_VARVAL_INT))) /* Variable Types */ typedef enum var_type { VAR_INVALID = 0, VAR_BOOL, VAR_INT, VAR_DBL, VAR_STR, VAR_RANDOM, VAR_CUSTOM, VAR_UNKNOWN, } var_type_t; typedef struct var { char *var_name; var_type_t var_type; struct var *var_next; union { boolean_t boolean; uint64_t integer; double dbl; char *string; struct randdist *randptr; struct cvar *cvarptr; } var_val; } var_t; #define VAR_HAS_BOOLEAN(vp) \ ((vp)->var_type == VAR_BOOL) #define VAR_HAS_INTEGER(vp) \ ((vp)->var_type == VAR_INT) #define VAR_HAS_DOUBLE(vp) \ ((vp)->var_type == VAR_DBL) #define VAR_HAS_STRING(vp) \ ((vp)->var_type == VAR_STR) #define VAR_HAS_RANDOM(vp) \ ((vp)->var_type == VAR_RANDOM) #define VAR_HAS_CUSTOM(vp) \ ((vp)->var_type == VAR_CUSTOM) #define VAR_HAS_UNKNOWN(vp) \ ((vp)->var_type == VAR_UNKNOWN) #define VAR_SET_BOOL(vp, val) \ { \ (vp)->var_val.boolean = (val); \ (vp)->var_type = VAR_BOOL;\ } #define VAR_SET_INT(vp, val) \ { \ (vp)->var_val.integer = (val); \ (vp)->var_type = VAR_INT; \ } #define VAR_SET_DBL(vp, val) \ { \ (vp)->var_val.dbl = (val); \ (vp)->var_type = VAR_DBL; \ } #define VAR_SET_STR(vp, val) \ { \ (vp)->var_val.string = (val); \ (vp)->var_type = VAR_STR; \ } #define VAR_SET_RANDOM(vp, val) \ { \ (vp)->var_val.randptr = (val); \ (vp)->var_type = VAR_RANDOM; \ } #define VAR_SET_CUSTOM(vp, val) \ { \ (vp)->var_val.cvarptr = (val); \ (vp)->var_type = VAR_CUSTOM; \ } #define VAR_SET_UNKNOWN(vp) \ { \ (vp)->var_type = VAR_UNKNOWN; \ } avd_t avd_bool_alloc(boolean_t bool); avd_t avd_int_alloc(uint64_t integer); avd_t avd_dbl_alloc(double integer); avd_t avd_str_alloc(char *string); avd_t avd_var_alloc(char *varname); int var_assign_boolean(char *name, boolean_t bool); int var_assign_integer(char *name, uint64_t integer); int var_assign_double(char *name, double dbl); int var_assign_string(char *name, char *string); int var_assign_random(char *name, struct randdist *rndp); int var_assign_custom(char *name, struct cvar *cvar); boolean_t avd_get_bool(avd_t); uint64_t avd_get_int(avd_t); double avd_get_dbl(avd_t); char *avd_get_str(avd_t); /* Local variables related */ void avd_update(avd_t *avdp, var_t *lvar_list); void var_update_comp_lvars(var_t *newlvar, var_t *proto_comp_vars, var_t *mstr_lvars); var_t *var_lvar_alloc_local(char *name); var_t *var_lvar_assign_boolean(char *name, boolean_t); var_t *var_lvar_assign_integer(char *name, uint64_t); var_t *var_lvar_assign_double(char *name, double); var_t *var_lvar_assign_string(char *name, char *string); var_t *var_lvar_assign_var(char *name, char *src_name); /* miscelaneous */ char *var_to_string(char *name); char *var_randvar_to_string(char *name, int param); #endif /* _VARS_H */
5,483
26.837563
73
h
filebench
filebench-master/cvars/cvar-erlang.c
/* * rand-erlang.c * * Custom variable that returns random numbers following the Erlang * distribution. * * Author: Santhosh Kumar Koundinya (santhosh@fsl.cs.sunysb.edu) */ #include <stdio.h> #include "mtwist/mtwist.h" #include "mtwist/randistrs.h" #include "cvar.h" #include "cvar_trace.h" #include "cvar_tokens.h" #include "cvar-erlang.h" void *cvar_alloc_handle(const char *cvar_parameters, void *(*cvar_malloc)(size_t size), void (*cvar_free)(void *cvar_ptr)) { cvar_token_t *list_head;; cvar_token_t *t; handle_t handle; handle_t *state = NULL; int ret = 0; cvar_trace("entry"); /* Tokenize parameters supplied by filebench. */ list_head = NULL; ret = tokenize(cvar_parameters, DEFAULT_PARAMETER_DELIMITER, DEFAULT_KEY_VALUE_DELIMITER, &list_head); if (ret) goto out; /* Get the value of shape and rate. */ t = find_token(list_head, RER_SHAPE); if (t && t->value) { t->used = 1; handle.shape = atoi(t->value); } else handle.shape = RER_SHAPE_DEFAULT; t = find_token(list_head, RER_RATE); if (t && t->value) { t->used = 1; handle.rate = atof(t->value); } else handle.rate = RER_RATE_DEFAULT; cvar_trace("shape = %d, rate = %lf", handle.shape, handle.rate); /* Validate parameters. */ if (handle.shape < 0) { cvar_log_error("Invalid parameter value: shape = %d. shape is a " "non-zero positive integer", handle.shape); goto out; } if (handle.rate < 0) { cvar_log_error("Invalid parameter value: rate = %lf. rate is a " "non-zero positive rational number", handle.rate); goto out; } t = unused_tokens(list_head); if (t) { cvar_log_error("Unsupported parameter %s", t->key); goto out; } /* Seed the state. */ mts_goodseed(&handle.state); /* All set. Now allocate space for the handle in the shared segment and * copy the state over. */ state = (handle_t *) cvar_malloc(sizeof(handle_t)); if (!state) { cvar_log_error("Out of memory"); goto out; } *state = handle; out: free_tokens(list_head); cvar_trace("exit"); return state; } int cvar_revalidate_handle(void *cvar_handle) { handle_t *h = (handle_t *) cvar_handle; mts_mark_initialized(&h->state); return 0; } int cvar_next_value(void *cvar_handle, double *value) { handle_t *h = (handle_t *) cvar_handle; if (!h) { cvar_trace("NULL cvar_handle"); return -1; } if (!value) { cvar_trace("NULL value"); return -1; } *value = rds_erlang(&h->state, h->shape, h->rate); return 0; } void cvar_free_handle(void *handle, void (*cvar_free)(void *ptr)) { cvar_free(handle); } const char *cvar_usage() { int offset; if (usage[0]) return usage; offset = 0; offset += snprintf(usage + offset, USAGE_LEN - offset, "\tparameter\tdefault\n"); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t---------\t-------\n"); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t%s\t\t%d\n", RER_SHAPE, RER_SHAPE_DEFAULT); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t%s\t\t%.1f\n", RER_RATE, RER_RATE_DEFAULT); offset += snprintf(usage + offset, USAGE_LEN - offset, "Use '%c' to delimit parameters and '%c' to delimit key-value " "pairs.\n", DEFAULT_PARAMETER_DELIMITER, DEFAULT_KEY_VALUE_DELIMITER); offset += snprintf(usage + offset, USAGE_LEN - offset, "Example: '%s%c%d%c%s%c%.1f'", RER_SHAPE, DEFAULT_KEY_VALUE_DELIMITER, RER_SHAPE_DEFAULT, DEFAULT_PARAMETER_DELIMITER, RER_RATE, DEFAULT_KEY_VALUE_DELIMITER, RER_RATE_DEFAULT); return usage; } const char *cvar_version() { return VERSION; }
3,537
20.839506
72
c
filebench
filebench-master/cvars/cvar-erlang.h
/* * rand-erlang.h * * Custom variable that returns random numbers following the Erlang * distribution. * * Author: Santhosh Kumar Koundinya (santhosh@fsl.cs.sunysb.edu) */ #ifndef _RAND_ERLANG_H #define _RAND_ERLANG_H #include "mtwist/mtwist.h" /* Parameters recognized by this variable. */ #define RER_SHAPE "shape" #define RER_RATE "rate" /* Parameter defaults. */ #define RER_SHAPE_DEFAULT 1 #define RER_RATE_DEFAULT 1.0 #define VERSION "0.1.1 (alpha)" /* The handle that will be returned to Filebench. */ typedef struct handle { mt_state state; int shape; double rate; } handle_t; /* Static buffer to hold the usage string */ #define USAGE_LEN 2048 char usage[USAGE_LEN + 1] = {0}; #endif /* _RAND_ERLANG_H */
734
18.342105
67
h
filebench
filebench-master/cvars/cvar-exponential.c
/* * rand-exponential.c * * Custom variable implementation that returns exponentially distributed random * numbers. * * Author: Santhosh Kumar Koundinya (santhosh@fsl.cs.sunysb.edu) */ #include <stdio.h> #include "mtwist/mtwist.h" #include "mtwist/randistrs.h" #include "cvar.h" #include "cvar_trace.h" #include "cvar_tokens.h" #include "cvar-exponential.h" void *cvar_alloc_handle(const char *cvar_parameters, void *(*cvar_malloc)(size_t size), void (*cvar_free)(void *cvar_ptr)) { cvar_token_t *list_head;; cvar_token_t *t; handle_t handle; handle_t *state = NULL; int ret = 0; cvar_trace("entry"); /* Tokenize parameters supplied by filebench. */ list_head = NULL; ret = tokenize(cvar_parameters, DEFAULT_PARAMETER_DELIMITER, DEFAULT_KEY_VALUE_DELIMITER, &list_head); if (ret) goto out; /* Get the value of mean. */ t = find_token(list_head, RE_MEAN); if (t && t->value) { t->used = 1; handle.mean = atof(t->value); } else handle.mean = RE_MEAN_DEFAULT; cvar_trace("mean = %lf", handle.mean); /* The Exponential PDF is defined to be 0 for mean < 0. */ if (handle.mean < 0) { cvar_trace("Setting mean to 0"); handle.mean = 0; } t = unused_tokens(list_head); if (t) { cvar_log_error("Unsupported parameter %s", t->key); goto out; } /* Seed the state. */ mts_goodseed(&handle.state); /* All set. Now allocate space for the handle in the shared segment and * copy the state over. */ state = (handle_t *) cvar_malloc(sizeof(handle_t)); if (!state) { cvar_log_error("Out of memory"); goto out; } *state = handle; out: free_tokens(list_head); cvar_trace("exit"); return state; } int cvar_revalidate_handle(void *cvar_handle) { handle_t *h = (handle_t *) cvar_handle; mts_mark_initialized(&h->state); return 0; } int cvar_next_value(void *cvar_handle, double *value) { handle_t *h = (handle_t *) cvar_handle; if (!h) { cvar_trace("NULL cvar_handle"); return -1; } if (!value) { cvar_trace("NULL value"); return -1; } *value = rds_exponential(&h->state, h->mean); return 0; } void cvar_free_handle(void *handle, void (*cvar_free)(void *ptr)) { cvar_free(handle); } const char *cvar_usage() { int offset; if (usage[0]) return usage; offset = 0; offset += snprintf(usage + offset, USAGE_LEN - offset, "\tparameter\tdefault\n"); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t---------\t-------\n"); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t%s\t\t%.1f\n", RE_MEAN, RE_MEAN_DEFAULT); offset += snprintf(usage + offset, USAGE_LEN - offset, "Use '%c' for assignment.\n", DEFAULT_KEY_VALUE_DELIMITER); offset += snprintf(usage + offset, USAGE_LEN - offset, "Example: '%s%c%.1f'", RE_MEAN, DEFAULT_KEY_VALUE_DELIMITER, RE_MEAN_DEFAULT); return usage; } const char *cvar_version() { return VERSION; }
2,859
19.140845
79
c
filebench
filebench-master/cvars/cvar-exponential.h
/* * rand-exponential.h * * Custom variable implementation that returns exponentially distributed random * numbers. * * Author: Santhosh Kumar Koundinya (santhosh@fsl.cs.sunysb.edu) */ #ifndef _RAND_EXPONENTIAL_H #define _RAND_EXPONENTIAL_H #include "mtwist/mtwist.h" /* Parameters recognized by this variable. */ #define RE_MEAN "mean" /* Parameter defaults. */ #define RE_MEAN_DEFAULT 1.0 #define VERSION "0.1.1 (alpha)" /* The handle that will be returned to Filebench. */ typedef struct handle { mt_state state; double mean; } handle_t; /* Static buffer to hold the usage string */ #define USAGE_LEN 2048 char usage[USAGE_LEN + 1] = {0}; #endif /* _RAND_EXPONENTIAL_H */
693
18.828571
79
h
filebench
filebench-master/cvars/cvar-gamma.c
/* * rand-gamma.c * * Custom variable implementation that returns gamma distributed random * numbers. * */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include "cvar.h" #include "cvar_trace.h" #include "cvar_tokens.h" #define VERSION "0.1.1 (alpha)" #define USAGE_LEN 2048 static char usage[USAGE_LEN + 1]; #define MEAN "mean" #define GAMMA "gamma" #define MEAN_DEFAULT 4096.0 #define GAMMA_DEFAULT 1.5 typedef struct handle { double mean; double scaledmean; double gamma; } handle_t; /******* Part from the original FB distribution ****************/ /* * This is valid for 0 < a <= 1 * * From Knuth Volume 2, 3rd edition, pages 586 - 587. */ static double gamma_dist_knuth_algG(double a, double (*src)(unsigned short *), unsigned short *xi) { double p, U, V, X, q; p = M_E/(a + M_E); G2: /* get a random number U */ U = (*src)(xi); do { /* get a random number V */ V = (*src)(xi); } while (V == 0); if (U < p) { X = pow(V, 1/a); /* q = e^(-X) */ q = exp(-X); } else { X = 1 - log(V); q = pow(X, a-1); } /* * X now has density g, and q = f(X)/cg(X) */ /* get a random number U */ U = (*src)(xi); if (U >= q) goto G2; return (X); } /* * This is valid for a > 1 * * From Knuth Volume 2, 3rd edition, page 134. */ static double gamma_dist_knuth_algA(double a, double (*src)(unsigned short *), unsigned short *xi) { double U, Y, X, V; A1: /* get a random number U */ U = (*src)(xi); Y = tan(M_PI*U); X = (sqrt((2*a) - 1) * Y) + a - 1; if (X <= 0) goto A1; /* get a random number V */ V = (*src)(xi); if (V > ((1 + (Y*Y)) * exp((a-1) * log(X/(a-1)) - sqrt(2*a -1) * Y))) goto A1; return (X); } /* * fetch a uniformly distributed random number using the drand48 generator */ /* ARGSUSED */ static double default_src(unsigned short *xi) { return (drand48()); } /* * Sample the gamma distributed random variable with gamma 'a' and * result mulitplier 'b', which is usually mean/gamma. Uses the default * drand48 random number generator as input */ static double gamma_dist_knuth(double a, double b) { if (a <= 1.0) return (b * gamma_dist_knuth_algG(a, default_src, NULL)); else return (b * gamma_dist_knuth_algA(a, default_src, NULL)); } /* * Sample the gamma distributed random variable with gamma 'a' and * multiplier 'b', which is mean / gamma adjusted for the specified * minimum value. The suppled random number source function is * used to optain the uniformly distributed random numbers. */ static double gamma_dist_knuth_src(double a, double b, double (*src)(unsigned short *), unsigned short *xi) { if (a <= 1.0) return (b * gamma_dist_knuth_algG(a, src, xi)); else return (b * gamma_dist_knuth_algA(a, src, xi)); } /*************************************************************/ void *cvar_alloc_handle(const char *cvar_parameters, void *(*cvar_malloc)(size_t size), void (*cvar_free)(void *cvar_ptr)) { cvar_token_t *list_head;; cvar_token_t *t; handle_t handle; handle_t *state = NULL; int ret = 0; cvar_trace("entry"); /* Tokenize parameters supplied by filebench. */ list_head = NULL; ret = tokenize(cvar_parameters, DEFAULT_PARAMETER_DELIMITER, DEFAULT_KEY_VALUE_DELIMITER, &list_head); if (ret) goto out; /* Get the values for mean and gamma. */ t = find_token(list_head, MEAN); if (t && t->value) { t->used = 1; handle.mean = atof(t->value); } else handle.mean = MEAN_DEFAULT; t = find_token(list_head, GAMMA); if (t && t->value) { t->used = 1; handle.gamma = atof(t->value); } else handle.gamma= GAMMA_DEFAULT; if (!handle.gamma) { cvar_log_error("Invalid parameter values: mean = %lf " "and gamma = %lf. gamma must be greater " "than 0", handle.mean, handle.gamma); goto out; } handle.scaledmean = handle.mean / handle.gamma; cvar_trace("mean = %lf, gamma = %lf", handle.mean, handle.gamma); t = unused_tokens(list_head); if (t) { cvar_log_error("Unsupported parameter %s", t->key); goto out; } /* All set. Now allocate space for the handle in the shared segment and * copy the state over. */ state = (handle_t *)cvar_malloc(sizeof(handle_t)); if (!state) { cvar_log_error("Out of memory"); goto out; } *state = handle; out: free_tokens(list_head); cvar_trace("exit"); return state; } int cvar_revalidate_handle(void *cvar_handle) { handle_t *h = (handle_t *) cvar_handle; return 0; } int cvar_next_value(void *cvar_handle, double *value) { handle_t *h = (handle_t *) cvar_handle; if (!h) { cvar_log_error("NULL cvar_handle"); return -1; } if (!value) { cvar_log_error("NULL value"); return -1; } *value = gamma_dist_knuth(h->gamma, h->scaledmean); return 0; } void cvar_free_handle(void *handle, void (*cvar_free)(void *ptr)) { cvar_free(handle); } const char *cvar_usage() { int offset; if (usage[0]) return usage; offset = 0; offset += snprintf(usage + offset, USAGE_LEN - offset, "\tparameter\tdefault\n"); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t---------\t-------\n"); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t%s\t\t%.1f\n", MEAN, MEAN_DEFAULT); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t%s\t\t%.1f\n", GAMMA, GAMMA_DEFAULT); offset += snprintf(usage + offset, USAGE_LEN - offset, "Use '%c' to delimit parameters and '%c' to delimit key-value " "pairs.\n", DEFAULT_PARAMETER_DELIMITER, DEFAULT_KEY_VALUE_DELIMITER); offset += snprintf(usage + offset, USAGE_LEN - offset, "Example: '%s%c%.1f%c%s%c%.1f'", MEAN, DEFAULT_KEY_VALUE_DELIMITER, MEAN_DEFAULT, DEFAULT_PARAMETER_DELIMITER, GAMMA, DEFAULT_KEY_VALUE_DELIMITER, GAMMA_DEFAULT); return usage; } const char *cvar_version() { return VERSION; }
5,771
19.323944
74
c
filebench
filebench-master/cvars/cvar-lognormal.c
/* * rand-lognormal.c * * Custom variable implementation that returns Log-Normally distributed random * numbers. * * Author: Santhosh Kumar Koundinya (santhosh@fsl.cs.sunysb.edu) */ #include <stdio.h> #include "mtwist/mtwist.h" #include "mtwist/randistrs.h" #include "cvar.h" #include "cvar_trace.h" #include "cvar_tokens.h" #include "cvar-lognormal.h" void *cvar_alloc_handle(const char *cvar_parameters, void *(*cvar_malloc)(size_t size), void (*cvar_free)(void *cvar_ptr)) { cvar_token_t *list_head;; cvar_token_t *t; handle_t handle; handle_t *state = NULL; int ret = 0; cvar_trace("entry"); /* Tokenize parameters supplied by filebench. */ list_head = NULL; ret = tokenize(cvar_parameters, DEFAULT_PARAMETER_DELIMITER, DEFAULT_KEY_VALUE_DELIMITER, &list_head); if (ret) goto out; /* Get the value of shape and scale. */ t = find_token(list_head, RLN_SHAPE); if (t && t->value) { t->used = 1; handle.shape = atof(t->value); } else handle.shape = RLN_SHAPE_DEFAULT; t = find_token(list_head, RLN_SCALE); if (t && t->value) { t->used = 1; handle.scale = atof(t->value); } else handle.scale = RLN_SCALE_DEFAULT; cvar_trace("shape = %lf, scale = %lf", handle.shape, handle.scale); if (handle.shape < 0) { cvar_log_error("Invalid parameter value: shape = %lf. shape is a " "non-zero, positive rational number", handle.shape); goto out; } if (handle.scale < 0) { cvar_log_error("Invalid parameter value: scale = %lf. scale is a " "non-zero, positive rational number", handle.scale); goto out; } t = unused_tokens(list_head); if (t) { cvar_log_error("Unsupported parameter %s", t->key); goto out; } /* Seed the state. */ mts_goodseed(&handle.state); /* All set. Now allocate space for the handle in the shared segment and * copy the state over. */ state = (handle_t *) cvar_malloc(sizeof(handle_t)); if (!state) { cvar_log_error("Out of memory"); goto out; } *state = handle; out: free_tokens(list_head); cvar_trace("exit"); return state; } int cvar_revalidate_handle(void *cvar_handle) { handle_t *h = (handle_t *) cvar_handle; mts_mark_initialized(&h->state); return 0; } int cvar_next_value(void *cvar_handle, double *value) { handle_t *h = (handle_t *) cvar_handle; if (!h) { cvar_trace("NULL cvar_handle"); return -1; } if (!value) { cvar_trace("NULL value"); return -1; } *value = rds_lognormal(&h->state, h->shape, h->scale); return 0; } void cvar_free_handle(void *handle, void (*cvar_free)(void *ptr)) { cvar_free(handle); } const char *cvar_usage() { int offset; if (usage[0]) return usage; offset = 0; offset += snprintf(usage + offset, USAGE_LEN - offset, "\tparameter\tdefault\n"); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t---------\t-------\n"); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t%s\t\t%.1f\n", RLN_SHAPE, RLN_SHAPE_DEFAULT); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t%s\t\t%.1f\n", RLN_SCALE, RLN_SCALE_DEFAULT); offset += snprintf(usage + offset, USAGE_LEN - offset, "Use '%c' to delimit parameters and '%c' to delimit key-value " "pairs.\n", DEFAULT_PARAMETER_DELIMITER, DEFAULT_KEY_VALUE_DELIMITER); offset += snprintf(usage + offset, USAGE_LEN - offset, "Example: '%s%c%.1f%c%s%c%.1f'", RLN_SHAPE, DEFAULT_KEY_VALUE_DELIMITER, RLN_SHAPE_DEFAULT, DEFAULT_PARAMETER_DELIMITER, RLN_SCALE, DEFAULT_KEY_VALUE_DELIMITER, RLN_SCALE_DEFAULT); return usage; } const char *cvar_version() { return VERSION; }
3,556
21.093168
78
c
filebench
filebench-master/cvars/cvar-lognormal.h
/* * rand-lognormal.h * * Custom variable implementation that returns Log-Normally distributed random * numbers. * * Author: Santhosh Kumar Koundinya (santhosh@fsl.cs.sunysb.edu) */ #ifndef _RAND_LOGNORMAL_H #define _RAND_LOGNORMAL_H #include "mtwist/mtwist.h" /* Parameters recognized by this variable. */ #define RLN_SHAPE "shape" #define RLN_SCALE "scale" /* Parameter defaults. */ #define RLN_SHAPE_DEFAULT 1.0 #define RLN_SCALE_DEFAULT 1.0 #define VERSION "0.1.1 (alpha)" /* The handle that will be returned to Filebench. */ typedef struct handle { mt_state state; double shape; double scale; } handle_t; /* Static buffer to hold the usage string */ #define USAGE_LEN 2048 char usage[USAGE_LEN + 1] = {0}; #endif /* _RAND_NORMAL_H */
758
18.973684
78
h
filebench
filebench-master/cvars/cvar-normal.c
/* * rand-normal.h * * Custom variable that returns random numbers following the Normal * distribution. * * Author: Santhosh Kumar Koundinya (santhosh@fsl.cs.sunysb.edu) */ #include <stdio.h> #include "mtwist/mtwist.h" #include "mtwist/randistrs.h" #include "cvar.h" #include "cvar_trace.h" #include "cvar_tokens.h" #include "cvar-normal.h" void *cvar_alloc_handle(const char *cvar_parameters, void *(*cvar_malloc)(size_t size), void (*cvar_free)(void *cvar_ptr)) { cvar_token_t *list_head;; cvar_token_t *t; handle_t handle; handle_t *state = NULL; int ret = 0; cvar_trace("entry"); /* Tokenize parameters supplied by filebench. */ list_head = NULL; ret = tokenize(cvar_parameters, DEFAULT_PARAMETER_DELIMITER, DEFAULT_KEY_VALUE_DELIMITER, &list_head); if (ret) goto out; /* Get the value of mean and sigma. */ t = find_token(list_head, RN_MEAN); if (t && t->value) { t->used = 1; handle.mean = atof(t->value); } else handle.mean = RN_MEAN_DEFAULT; t = find_token(list_head, RN_SIGMA); if (t && t->value) { t->used = 1; handle.sigma = atof(t->value); } else handle.sigma = RN_SIGMA_DEFAULT; cvar_trace("mean = %lf, sigma = %lf", handle.mean, handle.sigma); t = unused_tokens(list_head); if (t) { cvar_log_error("Unsupported parameter %s", t->key); goto out; } /* Seed the state. */ mts_goodseed(&handle.state); /* All set. Now allocate space for the handle in the shared segment and * copy the state over. */ state = (handle_t *) cvar_malloc(sizeof(handle_t)); if (!state) { cvar_log_error("Out of memory"); goto out; } *state = handle; out: free_tokens(list_head); cvar_trace("exit"); return state; } int cvar_revalidate_handle(void *cvar_handle) { handle_t *h = (handle_t *) cvar_handle; mts_mark_initialized(&h->state); return 0; } int cvar_next_value(void *cvar_handle, double *value) { handle_t *h = (handle_t *) cvar_handle; if (!h) { cvar_trace("NULL cvar_handle"); return -1; } if (!value) { cvar_trace("NULL value"); return -1; } *value = rds_normal(&h->state, h->mean, h->sigma); return 0; } void cvar_free_handle(void *handle, void (*cvar_free)(void *ptr)) { cvar_free(handle); } const char *cvar_usage() { int offset; if (usage[0]) return usage; offset = 0; offset += snprintf(usage + offset, USAGE_LEN - offset, "\tparameter\tdefault\n"); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t---------\t-------\n"); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t%s\t\t%.1f\n", RN_MEAN, RN_MEAN_DEFAULT); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t%s\t\t%.1f\n", RN_SIGMA, RN_SIGMA_DEFAULT); offset += snprintf(usage + offset, USAGE_LEN - offset, "Use '%c' to delimit parameters and '%c' to delimit key-value " "pairs.\n", DEFAULT_PARAMETER_DELIMITER, DEFAULT_KEY_VALUE_DELIMITER); offset += snprintf(usage + offset, USAGE_LEN - offset, "Example: '%s%c%.1f%c%s%c%.1f'", RN_MEAN, DEFAULT_KEY_VALUE_DELIMITER, RN_MEAN_DEFAULT, DEFAULT_PARAMETER_DELIMITER, RN_SIGMA, DEFAULT_KEY_VALUE_DELIMITER, RN_SIGMA_DEFAULT); return usage; } const char *cvar_version() { return VERSION; }
3,183
20.369128
72
c
filebench
filebench-master/cvars/cvar-normal.h
/* * rand-normal.h * * Custom variable that returns Normally distributed random numbers. * * Author: Santhosh Kumar Koundinya (santhosh@fsl.cs.sunysb.edu) */ #ifndef _RAND_NORMAL_H #define _RAND_NORMAL_H #include "mtwist/mtwist.h" /* Parameters recognized by this variable. */ #define RN_MEAN "mean" #define RN_SIGMA "sigma" /* Parameter defaults. */ #define RN_MEAN_DEFAULT 0.0 #define RN_SIGMA_DEFAULT 1.0 #define VERSION "0.1.1 (alpha)" /* The handle that will be returned to Filebench. */ typedef struct handle { mt_state state; double mean; double sigma; } handle_t; /* Static buffer to hold the usage string */ #define USAGE_LEN 2048 char usage[USAGE_LEN + 1] = {0}; #endif /* _RAND_NORMAL_H */
721
18.513514
68
h
filebench
filebench-master/cvars/cvar-triangular.c
/* * rand-triangular.c * * Custom variable implementation that returns random numbers following a * Triangular distribution. * * Author: Santhosh Kumar Koundinya (santhosh@fsl.cs.sunysb.edu) */ #include <stdio.h> #include "mtwist/mtwist.h" #include "mtwist/randistrs.h" #include "cvar.h" #include "cvar_trace.h" #include "cvar_tokens.h" #include "cvar-triangular.h" void *cvar_alloc_handle(const char *cvar_parameters, void *(*cvar_malloc)(size_t size), void (*cvar_free)(void *cvar_ptr)) { cvar_token_t *list_head;; cvar_token_t *t; handle_t handle; handle_t *state = NULL; int ret = 0; cvar_trace("entry"); /* Tokenize parameters supplied by filebench. */ list_head = NULL; ret = tokenize(cvar_parameters, DEFAULT_PARAMETER_DELIMITER, DEFAULT_KEY_VALUE_DELIMITER, &list_head); if (ret) goto out; /* Get the value of lower, upper and mode. */ t = find_token(list_head, RT_LOWER); if (t && t->value) { t->used = 1; handle.lower = atof(t->value); } else handle.lower = RT_LOWER_DEFAULT; t = find_token(list_head, RT_UPPER); if (t && t->value) { t->used = 1; handle.upper = atof(t->value); } else handle.upper = RT_UPPER_DEFAULT; t = find_token(list_head, RT_MODE); if (t && t->value) { t->used = 1; handle.mode = atof(t->value); } else handle.mode = RT_MODE_DEFAULT; cvar_trace("lower = %lf, upper = %lf, mode = %lf", handle.lower, handle.upper, handle.mode); /* Validate parameters. */ if (handle.upper < handle.lower) { cvar_log_error("Invalid parameter values: lower = %lf and upper = %lf. " "upper must be greater than lower", handle.lower, handle.upper); goto out; } if ((handle.mode > handle.upper) || (handle.mode < handle.lower)) { cvar_log_error("Invalid parameter values: lower = %lf, mode = %lf and " "upper = %lf. mode must be between lower and upper", handle.lower, handle.mode, handle.upper); goto out; } /* Check if there are unused tokens. */ t = unused_tokens(list_head); if (t) { cvar_log_error("Unsupported parameter %s", t->key); goto out; } /* Seed the state. */ mts_goodseed(&handle.state); /* All set. Now allocate space for the handle in the shared segment and * copy the state over. */ state = (handle_t *) cvar_malloc(sizeof(handle_t)); if (!state) { cvar_log_error("Out of memory"); goto out; } *state = handle; out: free_tokens(list_head); cvar_trace("exit"); return state; } int cvar_revalidate_handle(void *cvar_handle) { handle_t *h = (handle_t *) cvar_handle; mts_mark_initialized(&h->state); return 0; } int cvar_next_value(void *cvar_handle, double *value) { handle_t *h = (handle_t *) cvar_handle; if (!h) { cvar_log_error("NULL cvar_handle"); return -1; } if (!value) { cvar_log_error("NULL value"); return -1; } *value = rds_triangular(&h->state, h->lower, h->upper, h->mode); return 0; } void cvar_free_handle(void *handle, void (*cvar_free)(void *ptr)) { cvar_free(handle); } const char *cvar_usage() { int offset; if (usage[0]) return usage; offset = 0; offset += snprintf(usage + offset, USAGE_LEN - offset, "\tparameter\tdefault\n"); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t---------\t-------\n"); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t%s\t\t%.1f\n", RT_LOWER, RT_LOWER_DEFAULT); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t%s\t\t%.1f\n", RT_UPPER, RT_UPPER_DEFAULT); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t%s\t\t%.1f\n", RT_MODE, RT_MODE_DEFAULT); offset += snprintf(usage + offset, USAGE_LEN - offset, "Use '%c' to delimit parameters and '%c' to delimit key-value " "pairs.\n", DEFAULT_PARAMETER_DELIMITER, DEFAULT_KEY_VALUE_DELIMITER); offset += snprintf(usage + offset, USAGE_LEN - offset, "Example: '%s%c%.1f%c%s%c%.1f%c%s%c%.1f'", RT_LOWER, DEFAULT_KEY_VALUE_DELIMITER, RT_LOWER_DEFAULT, DEFAULT_PARAMETER_DELIMITER, RT_UPPER, DEFAULT_KEY_VALUE_DELIMITER, RT_UPPER_DEFAULT, DEFAULT_PARAMETER_DELIMITER, RT_MODE, DEFAULT_KEY_VALUE_DELIMITER, RT_MODE_DEFAULT); return usage; } const char *cvar_version() { return VERSION; }
4,154
22.607955
74
c
filebench
filebench-master/cvars/cvar-triangular.h
/* * rand-triangular.h * * Custom variable implementation that returns random numbers following a * Triangular distribution. * * Author: Santhosh Kumar Koundinya (santhosh@fsl.cs.sunysb.edu) */ #ifndef _RAND_TRIANGULAR_H #define _RAND_TRIANGULAR_H #include "mtwist/mtwist.h" /* Parameters recognized by this variable. */ #define RT_LOWER "lower" #define RT_UPPER "upper" #define RT_MODE "mode" /* Parameter defaults. */ #define RT_LOWER_DEFAULT 0.0 #define RT_UPPER_DEFAULT 1.0 #define RT_MODE_DEFAULT 0.5 #define VERSION "0.1.1 (alpha)" /* The handle that will be returned to Filebench. */ typedef struct handle { mt_state state; double lower; double upper; double mode; } handle_t; /* Static buffer to hold the usage string */ #define USAGE_LEN 2048 char usage[USAGE_LEN + 1] = {0}; #endif /* _RAND_TRIANGULAR_H */
839
19.487805
73
h
filebench
filebench-master/cvars/cvar-uniform.c
/* * rand-uniform.c * * Custom variable implementation that returns uniformly distributed random * numbers. * * Author: Santhosh Kumar Koundinya (santhosh@fsl.cs.sunysb.edu) */ #include <stdio.h> #include "mtwist/mtwist.h" #include "mtwist/randistrs.h" #include "cvar.h" #include "cvar_trace.h" #include "cvar_tokens.h" #include "cvar-uniform.h" void *cvar_alloc_handle(const char *cvar_parameters, void *(*cvar_malloc)(size_t size), void (*cvar_free)(void *cvar_ptr)) { cvar_token_t *list_head;; cvar_token_t *t; handle_t handle; handle_t *state = NULL; int ret = 0; cvar_trace("entry"); /* Tokenize parameters supplied by filebench. */ list_head = NULL; ret = tokenize(cvar_parameters, DEFAULT_PARAMETER_DELIMITER, DEFAULT_KEY_VALUE_DELIMITER, &list_head); if (ret) goto out; /* Get the values for lower and upper. */ t = find_token(list_head, RU_LOWER); if (t && t->value) { t->used = 1; handle.lower = atof(t->value); } else handle.lower = RU_LOWER_DEFAULT; t = find_token(list_head, RU_UPPER); if (t && t->value) { t->used = 1; handle.upper = atof(t->value); } else handle.upper = RU_UPPER_DEFAULT; cvar_trace("lower = %lf, upper = %lf", handle.lower, handle.upper); /* Validate parameters. */ if (handle.lower > handle.upper) { cvar_log_error("Invalid parameter values: lower = %lf and upper = %lf. " "upper must be greater than lower", handle.lower, handle.upper); } t = unused_tokens(list_head); if (t) { cvar_log_error("Unsupported parameter %s", t->key); goto out; } /* Seed the state. */ mts_goodseed(&handle.state); /* All set. Now allocate space for the handle in the shared segment and * copy the state over. */ state = (handle_t *) cvar_malloc(sizeof(handle_t)); if (!state) { cvar_log_error("Out of memory"); goto out; } *state = handle; out: free_tokens(list_head); cvar_trace("exit"); return state; } int cvar_revalidate_handle(void *cvar_handle) { handle_t *h = (handle_t *) cvar_handle; mts_mark_initialized(&h->state); return 0; } int cvar_next_value(void *cvar_handle, double *value) { handle_t *h = (handle_t *) cvar_handle; if (!h) { cvar_log_error("NULL cvar_handle"); return -1; } if (!value) { cvar_log_error("NULL value"); return -1; } *value = rds_uniform(&h->state, h->lower, h->upper); return 0; } void cvar_free_handle(void *handle, void (*cvar_free)(void *ptr)) { cvar_free(handle); } const char *cvar_usage() { int offset; if (usage[0]) return usage; offset = 0; offset += snprintf(usage + offset, USAGE_LEN - offset, "\tparameter\tdefault\n"); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t---------\t-------\n"); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t%s\t\t%.1f\n", RU_LOWER, RU_LOWER_DEFAULT); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t%s\t\t%.1f\n", RU_UPPER, RU_UPPER_DEFAULT); offset += snprintf(usage + offset, USAGE_LEN - offset, "Use '%c' to delimit parameters and '%c' to delimit key-value " "pairs.\n", DEFAULT_PARAMETER_DELIMITER, DEFAULT_KEY_VALUE_DELIMITER); offset += snprintf(usage + offset, USAGE_LEN - offset, "Example: '%s%c%.1f%c%s%c%.1f'", RU_LOWER, DEFAULT_KEY_VALUE_DELIMITER, RU_LOWER_DEFAULT, DEFAULT_PARAMETER_DELIMITER, RU_UPPER, DEFAULT_KEY_VALUE_DELIMITER, RU_UPPER_DEFAULT); return usage; } const char *cvar_version() { return VERSION; }
3,422
21.227273
75
c
filebench
filebench-master/cvars/cvar-uniform.h
/* * rand-uniform.h * * Custom variable implementation that generates uniformly distributed random * numbers. * * Author: Santhosh Kumar Koundinya (santhosh@fsl.cs.sunysb.edu) */ #ifndef _RAND_UNIFORM_H #define _RAND_UNIFORM_H #include "mtwist/mtwist.h" /* Parameters recognized by this variable. */ #define RU_LOWER "lower" #define RU_UPPER "upper" /* Parameter defaults. */ #define RU_LOWER_DEFAULT 0.0 #define RU_UPPER_DEFAULT 1.0 #define VERSION "0.1.1 (alpha)" /* The handle that will be returned to Filebench. */ typedef struct handle { mt_state state; double lower; double upper; } handle_t; /* Static buffer to hold the usage string */ #define USAGE_LEN 2048 char usage[USAGE_LEN + 1] = {0}; #endif /* _RAND_UNIFORM_H */
748
18.710526
77
h
filebench
filebench-master/cvars/cvar-weibull.c
/* * rand-weibull.c * * Custom variable implementation that returns random numbers following the * Weibull distribution. * * Author: Santhosh Kumar Koundinya (santhosh@fsl.cs.sunysb.edu) */ #include <stdio.h> #include "mtwist/mtwist.h" #include "mtwist/randistrs.h" #include "cvar.h" #include "cvar_trace.h" #include "cvar_tokens.h" #include "cvar-weibull.h" void *cvar_alloc_handle(const char *cvar_parameters, void *(*cvar_malloc)(size_t size), void (*cvar_free)(void *cvar_ptr)) { cvar_token_t *list_head;; cvar_token_t *t; handle_t handle; handle_t *state = NULL; int ret = 0; cvar_trace("entry"); /* Tokenize parameters supplied by filebench. */ list_head = NULL; ret = tokenize(cvar_parameters, DEFAULT_PARAMETER_DELIMITER, DEFAULT_KEY_VALUE_DELIMITER, &list_head); if (ret) goto out; /* Get the value of shape and scale. */ t = find_token(list_head, RW_SHAPE); if (t && t->value) { t->used = 1; handle.shape = atof(t->value); } else handle.shape = RW_SHAPE_DEFAULT; t = find_token(list_head, RW_SCALE); if (t && t->value) { t->used = 1; handle.scale = atof(t->value); } else handle.scale = RW_SCALE_DEFAULT; cvar_trace("shape = %lf, scale = %lf", handle.shape, handle.scale); /* Validate parameters. */ if (handle.shape < 0) { cvar_log_error("Invalid parameter value: shape = %lf. shape is a " "non-zero, positive integer", handle.shape); goto out; } if (handle.scale < 0) { cvar_log_error("Invalid parameter value: scale = %lf. scale is a " "non-zero, positive rational number", handle.scale); goto out; } t = unused_tokens(list_head); if (t) { cvar_log_error("Unsupported parameter %s", t->key); goto out; } /* Seed the state. */ mts_goodseed(&handle.state); /* All set. Now allocate space for the handle in the shared segment and * copy the state over. */ state = (handle_t *) cvar_malloc(sizeof(handle_t)); if (!state) { cvar_log_error("Out of memory"); goto out; } *state = handle; out: free_tokens(list_head); cvar_trace("exit"); return state; } int cvar_revalidate_handle(void *cvar_handle) { handle_t *h = (handle_t *) cvar_handle; mts_mark_initialized(&h->state); return 0; } int cvar_next_value(void *cvar_handle, double *value) { handle_t *h = (handle_t *) cvar_handle; if (!h) { cvar_trace("NULL cvar_handle"); return -1; } if (!value) { cvar_trace("NULL value"); return -1; } *value = rds_weibull(&h->state, h->shape, h->scale); return 0; } void cvar_free_handle(void *handle, void (*cvar_free)(void *ptr)) { cvar_free(handle); } const char *cvar_usage() { int offset; if (usage[0]) return usage; offset = 0; offset += snprintf(usage + offset, USAGE_LEN - offset, "\tparameter\tdefault\n"); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t---------\t-------\n"); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t%s\t\t%.1f\n", RW_SHAPE, RW_SHAPE_DEFAULT); offset += snprintf(usage + offset, USAGE_LEN - offset, "\t%s\t\t%.1f\n", RW_SCALE, RW_SCALE_DEFAULT); offset += snprintf(usage + offset, USAGE_LEN - offset, "Use '%c' to delimit parameters and '%c' to delimit key-value " "pairs.\n", DEFAULT_PARAMETER_DELIMITER, DEFAULT_KEY_VALUE_DELIMITER); offset += snprintf(usage + offset, USAGE_LEN - offset, "Example: '%s%c%.1f%c%s%c%.1f'", RW_SHAPE, DEFAULT_KEY_VALUE_DELIMITER, RW_SHAPE_DEFAULT, DEFAULT_PARAMETER_DELIMITER, RW_SCALE, DEFAULT_KEY_VALUE_DELIMITER, RW_SCALE_DEFAULT); return usage; } const char *cvar_version() { return VERSION; }
3,568
21.030864
75
c
filebench
filebench-master/cvars/cvar-weibull.h
/* * rand-weibull.h * * Custom variable implementation that returns random numbers following the * Weibull distribution. * * Author: Santhosh Kumar Koundinya (santhosh@fsl.cs.sunysb.edu) */ #ifndef _RAND_WEIBULL_H #define _RAND_WEIBULL_H #include "mtwist/mtwist.h" /* Parameters recognized by this variable. */ #define RW_SHAPE "shape" #define RW_SCALE "scale" /* Parameter defaults. */ #define RW_SHAPE_DEFAULT 1.0 #define RW_SCALE_DEFAULT 1.0 #define VERSION "0.1.1 (alpha)" /* The handle that will be returned to Filebench. */ typedef struct handle { mt_state state; double shape; double scale; } handle_t; /* Static buffer to hold the usage string */ #define USAGE_LEN 2048 char usage[USAGE_LEN + 1] = {0}; #endif /* _RAND_WEIBULL_H */
759
19
75
h
filebench
filebench-master/cvars/cvar.h
/* * cvar.h * * Include file for code implementing custom variables. * * @Author Santhosh Kumar Koundinya (santhosh@fsl.cs.sunysb.edu) */ #ifndef _CVAR_H #define _CVAR_H /* * Initialize the state of the library supporting the custom variable. * cvar_module_init is the first function to be invoked when a custom variable * module is loaded. * * Implementation: Optional. * * Return 0 on success and a non-zero error code on failure. */ int cvar_module_init(); /* * Allocate a new custom variable handle. A handle is subsequently used to * generate values. Memory required for initializing the handle must be * allocated using argument cvar_malloc only. Libraries can use cvar_free to * clean up memory allocated by cvar_malloc in case construction of the handle * fails. Libraries must not store references to cvar_malloc and cvar_free for * later use. * * Implementation: Mandatory. * * Return a non NULL handle on success and a NULL handle on error. */ void *cvar_alloc_handle(const char *cvar_parameters, void *(*cvar_malloc)(size_t size), void (*cvar_free)(void *ptr)); /* * Re-validate a previously allocated handle. Filebench will always * re-validate handles that were not allocated in the current process before * use in the current process. * * Implementation: Optional. * * Return 0 on success and a non-zero error code on failure to re-validate * existing handle. */ int cvar_revalidate_handle(void *cvar_handle); /* * Called every time a new value of the custom variable is required. * * Implementation: Mandatory. * * Return 0 on success and non zero on error. On success, argument value is * initialized to the next value of the variable whose state is in handle. */ int cvar_next_value(void *cvar_handle, double *value); /* * Called when an existing custom variable has to be destroyed. Use function * cvar_free to free up memory allocated for cvar_handle. * * Implementation: Mandatory. * * Note: cvar_free_handle may not be called at all, i.e., Filebench may choose * to quit without invoking free_handle. */ void cvar_free_handle(void *cvar_handle, void (*cvar_free)(void *ptr)); /* * Invoked before unloading the module. * * Implementation: Optional. * * Note: * 1. cvar_module_exit will never be invoked if cvar_module_init failed. * 2. cvar_module_exit may not be called at all, i.e., Filebench may choose * to quit without invoking cvar_module_exit. */ void cvar_module_exit(); /* * Show usage, including information on the list of parameters supported and the * format of the parameter string. * * Implementation: Optional. * * Return a non-null, formatted string to be displayed on screen. */ const char *cvar_usage(); /* * Show version. * * Implementation: Optional. * * Return a non-null version string. */ const char *cvar_version(); #endif /* _CVAR_H */
2,873
24.891892
80
h
filebench
filebench-master/cvars/cvar_tokens.c
/* * cvar_tokens.c * * Simple utilities to manipulate tokens. * * Author: Santhosh Kumar Koundinya (santhosh@fsl.cs.sunysb.edu) */ #include <stdio.h> #include <string.h> #include "cvar_trace.h" #include "cvar_tokens.h" /* * Return 0 if tokenization was successful, non-zero otherwise. This function * does not use strtok (or strtok_r) as we need to point out empty keys. */ int tokenize(const char *parameters, const char parameter_delimiter, const char key_value_delimiter, cvar_token_t **list_head) { char *param; char *param_start, *param_end; char *key_start, *key_end; cvar_token_t *lhead, *prev, *curr; int more_params; int no_value; int ret = 0; if (!parameters) goto out; ret = -1; lhead = prev = NULL; param = strdup(parameters); if (!param) { cvar_log_error("Out of memory"); goto cleanup; } param_start = param; more_params = 1; while (more_params) { param_end = strchr(param_start, parameter_delimiter); if (param_end) *param_end = '\0'; else { param_end = param_start + strlen(param_start); more_params = 0; } if (param_start != param_end) { key_start = param_start; key_end = strchr(param_start, key_value_delimiter); if (key_end) { *key_end = '\0'; no_value = 0; } else { key_end = param_end; no_value = 1; } if (key_start == key_end) { cvar_log_error("Empty key at position %lu in parameter string " "\"%s\"", (key_start - param)/sizeof(char) + 1, parameters); goto cleanup; } curr = (cvar_token_t *) malloc(sizeof(cvar_token_t)); if (!curr) { cvar_log_error("Out of memory"); goto cleanup; } memset(curr, 0x00, sizeof(cvar_token_t)); curr->key = strdup(key_start); if (!curr->key) { cvar_log_error("Out of memory"); goto cleanup; } if (!no_value) { curr->value = strdup(key_end+1); if (!curr->value) { cvar_log_error("Out of memory"); goto cleanup; } } if (!prev) lhead = prev = curr; else { prev->next = curr; prev = curr; } } if (more_params) param_start = param_end + 1; } *list_head = lhead; ret = 0; out: return ret; cleanup: free_tokens(lhead); lhead = NULL; goto out; } /* * Finds a token with a given key. Returns NULL if the token is not found or if * list_head or key is NULL. */ cvar_token_t *find_token(cvar_token_t *list_head, const char *key) { cvar_token_t *t; if (!list_head || !key) return NULL; for (t = list_head; t != NULL; t = t->next) { if (t->key && !strcmp(t->key, key)) return t; } return NULL; } /* * Returns a pointer to the first unused token or NULL if no unused tokens * exist. */ cvar_token_t *unused_tokens(cvar_token_t *list_head) { cvar_token_t *t; for (t = list_head; t != NULL; t = t->next) { if (!t->used) break; } return t; } static void free_token(cvar_token_t *token) { if (!token) return; if (token->key) free(token->key); if (token->value) free(token->value); free(token); return; } /* * Free up a list of tokens. */ void free_tokens(cvar_token_t *list_head) { cvar_token_t *curr; if (!list_head) return; while ((curr = list_head->next) != NULL) { list_head->next = curr->next; free_token(curr); } free_token(list_head); return; }
3,291
16.145833
79
c
filebench
filebench-master/cvars/cvar_tokens.h
/* * cvar_tokens.h * * Simple utilities to manipulate tokens. * * Author: Santhosh Kumar Koundinya (santhosh@fsl.cs.sunysb.edu) */ #ifndef _CVAR_TOKENS_H #define _CVAR_TOKENS_H #define DEFAULT_PARAMETER_DELIMITER ';' #define DEFAULT_KEY_VALUE_DELIMITER ':' /* A token holds a key-value pair. */ typedef struct cvar_token { char *key; char *value; int used; /* Non-zero if the token is used */ struct cvar_token *next; } cvar_token_t; /* * Return 0 if tokenization was successful, non-zero otherwise. This function * does not use strtok (or strtok_r) as we need to point out empty keys. */ int tokenize(const char *parameters, const char parameter_delimiter, const char key_value_delimiter, cvar_token_t **list_head); /* * Finds a token with a given key. Returns NULL if the token is not found or if * list_head or key is NULL. */ cvar_token_t *find_token(cvar_token_t *list_head, const char *key); /* * Returns a pointer to the first unused token or NULL if no unused tokens * exist. */ cvar_token_t *unused_tokens(cvar_token_t *list_head); /* * Free up a list of tokens. */ void free_tokens(cvar_token_t *list_head); #endif /* _CVAR_TOKENS_H */
1,178
23.061224
79
h
filebench
filebench-master/cvars/cvar_trace.h
/* * cvar_trace.h * * Tracing and logging utilities. * * Author: Santhosh Kumar Koundinya (santhosh@fsl.cs.sunysb.edu) */ #ifndef _CVAR_TRACE_H #define _CVAR_TRACE_H #include <stdio.h> #include <stdlib.h> #define cvar_log_error(fmt, ...) fprintf(stderr, fmt ".\n", ##__VA_ARGS__) #ifdef DEBUG #define cvar_trace(fmt, ...) fprintf(stdout, "%s: %d: %s: " fmt ".\n",\ __FILE__, __LINE__, __func__, ##__VA_ARGS__) /* Tracing functions */ static inline void cvar_tracebuf(const void *buff, unsigned int len) { char *buf = (char *)buff; unsigned int i; char *sbuf = NULL; if (len == 0) return; sbuf = (char *)malloc(2 + 2*len + 1); if (sbuf == NULL) { fprintf(stdout, "out of memory. unable to print " "buffer in hex."); return; } sbuf[2*len + 2] = '\0'; sprintf(sbuf, "%s", "0x"); for (i = 0; i < len; i++) { if (((buf[i] & 0xF0) >> 4) < 0x0A) sprintf(sbuf + 2 + 2*i, "%c", '0' + (int)((buf[i] & 0xF0) >> 4)); else sprintf(sbuf + 2 + 2*i, "%c", 'a' + (char) (((buf[i] & 0xF0) >> 4) - 0x0A)); if ((buf[i] & 0x0F) < 0x0A) sprintf(sbuf + 2 + 2*i + 1, "%c", '0' + (int)(buf[i] & 0x0F)); else sprintf(sbuf + 2 + 2*i + 1, "%c", 'a' + (char) ((buf[i] & 0x0F) - 0x0A)); } fprintf(stdout, "%s.\n", sbuf); free(sbuf); return; } #else #define cvar_trace(fmt, ...) static inline void cvar_tracebuf(const void *buff, unsigned int len) { return; } #endif /* DEBUG */ #endif /* _CVAR_TRACE_H */
1,467
18.064935
74
h