Saturday 11 November 2017

Moving Gjennomsnittet Køen


2.4 Prioritetskøer Mange applikasjoner krever at vi behandler elementer som har nøkler i orden, men ikke nødvendigvis i full sortert rekkefølge og ikke nødvendigvis alle samtidig. Ofte samler vi et sett med elementer, og prosesserer den med den største nøkkelen, så samler kanskje flere elementer, og prosesserer den med den nåværende største nøkkelen og så videre. En passende datatype i et slikt miljø støtter to operasjoner: Fjern maksimum og sett inn. En slik datatype kalles en prioritetskø. Prioritetskøer kjennetegnes ved å fjerne maksimal - og innsatsoperasjonen. Ved konvensjon vil vi bare sammenligne nøkler med en mindre () metode, som vi har gjort for sortering. Dermed, hvis poster kan ha dupliserte nøkler, betyr maksimum som enhver plate med den største nøkkelverdien. For å fullføre API-en, må vi også legge til konstruktører og en test hvis den er tom. For fleksibilitet bruker vi en generell implementering med en generisk type Nøkkel som implementerer Comparable. Program TopM. java er en prioritetskøsklient som tar et kommandolinjemargument M. leser transaksjoner fra standardinngang, og skriver ut de største transaksjonene M. Elementære implementeringer. De grunnleggende datastrukturene som vi diskuterte i avsnitt 1.3 gir oss fire umiddelbare utgangspunkt for å implementere prioritetskøer. Array representasjon (uordnet). Kanskje den enkleste prioritetskøen implementeringen er basert på vår kode for pushdown stabler. Koden for innsetting i prioritetskøen er den samme som for å trykke på stakken. For å implementere, fjern maksimalt. Vi kan legge til kode som den indre sløyfen for utvalg, sortere for å utveksle det maksimale elementet med elementet på slutten, og deretter slette det som vi gjorde med pop () for stabler. Program UnorderedArrayMaxPQ. java implementerer en prioritetskø med denne tilnærmingen. Array representasjon (bestilt). En annen tilnærming er å legge til kode for innsetting for å flytte større oppføringer en posisjon til høyre, og dermed holde oppføringene i arrayet i rekkefølge (som i innsettingssort). Dermed er det største elementet alltid på slutten, og koden for å fjerne maksimumet i prioritetskøen er det samme som for pop i stakken. Program OrderedArrayMaxPQ. java implementerer en prioritetskø med denne tilnærmingen. Tilknyttede representasjoner (uordnet og omvendt bestilt). På samme måte kan vi starte med vår koblede liste kode for pushdown-stabler, enten ved å endre koden for pop () for å finne og returnere maksimum eller koden for push () for å beholde elementer i omvendt rekkefølge og koden for pop () til Fjern koblingen og returner den første (maksimale) elementet på listen. Alle elementære implementeringer som nettopp er diskutert, har egenskapen om at enten innsatsen eller fjerningen av maksimal operasjon tar lineær tid i verste fall. Å finne en implementering der begge operasjonene er garantert å være raske, er en mer interessant oppgave, og det er hovedfeltet i denne delen. Hoppdefinisjoner. Den binære bunken er en datastruktur som effektivt kan støtte de grunnleggende prioritetskøoperasjoner. I en binær haug lagres elementene i en matrise slik at hver nøkkel er garantert å være større enn (eller lik) nøklene ved to andre spesifikke posisjoner. I sin tur må hver av disse nøklene være større enn to nøkler og så videre. Denne bestillingen er lett å se om vi ser nøklene som i en binær trestruktur med kanter fra hver tast til de to tastene som er kjent for å være mindre. Definisjon. Et binært tre er heap-bestilt hvis nøkkelen i hver node er større enn (eller lik) nøklene i det noder to barn (hvis noen). Forslag. Den største nøkkelen i et bunkebestilt binært tre er funnet på roten. Vi kan pålegge bunkebestillingsbegrensningen på et binært tre. Det er imidlertid spesielt praktisk å bruke et komplett binært tre som det nedenfor. Vi representerer komplette binære trær i rekkefølge innenfor en matrise ved å sette knutepunktene med nivåordre. med roten i stilling 1, sine barn i stillinger 2 og 3, deres barn i stillinger 4, 5, 6 og 7, og så videre. Definisjon. En binær haug er et sett med noder med nøkler som er arrangert i et komplett heapordret binærtre, representert i nivåordre i en matrise (ikke ved bruk av første oppføring). I en haug er forelderen til noden i posisjon k i posisjon k2 og omvendt er de to barnene til node i posisjon k i stillingene 2k og 2k 1. Vi kan reise opp og ned ved å gjøre enkle aritmetiske på matriseindekser : å flytte opp treet fra ak settes k til k2 for å flytte ned treet vi stiller k til 2k eller 2k1. Algoritmer på hauger. Vi representerer en bunke av størrelse N i private array pq av lengde N1, med pq0 ubrukt og bunken i pq1 til pqN. Vi får tilgang til nøkler bare gjennom private hjelpefunksjoner mindre () og exch (). Høveloperasjonene som vi vurderer å arbeide ved først å lage en enkel modifikasjon som kan bryte haugens tilstand, og deretter reise gjennom bunken og modifisere bunken som nødvendig for å sikre at bunkebetingelsen er fornøyd overalt. Vi refererer til denne prosessen som reorifisering. eller gjenopprette bunkeordre. Bottom-up reheapify (svømme). Hvis bunkeordren brytes, fordi en nodernøkkel blir større enn det nodernes foreldre nøkkel, kan vi gjøre fremskritt mot å fikse bruddet ved å bytte knutepunktet med foreldrene. Etter utvekslingen er noden større enn begge sine barn (den ene er den gamle forelder, den andre er mindre enn den gamle forelder fordi det var et barn av den node), men noden kan fortsatt være større enn foreldrene. Vi kan fikse dette bruddet på samme måte, og så videre, flytte opp bunken til vi kommer til en knutepunkt med en større nøkkel eller roten. Top-down heapify (vask). Hvis bunkeordren brytes fordi en knutepunkt blir mindre enn en eller begge knutepunktene barnesnøkler, kan vi gjøre fremskritt mot å fikse bruddet ved å bytte knutepunktet med den største av sine to barn. Denne bryteren kan føre til brudd på barnet vi løser dette bruddet på samme måte, og så videre, beveger oss ned i bunken til vi når en knutepunkt med både barn mindre eller bunn. Heap-basert prioritetskø. Disse sink () og swim () operasjonene danner grunnlaget for effektiv implementering av API for prioritetskøen, som vist nedenfor og implementert i MaxPQ. java og MinPQ. java. Sett inn. Vi legger til det nye elementet på slutten av matrisen, øker størrelsen på bunken og svømmer opp gjennom bunken med det aktuelle elementet for å gjenopprette bunkebetingelsen. Fjern maksimalt. Vi tar det største elementet fra toppen, legger varen fra enden av bunken på toppen, senker størrelsen på bunken, og senker den ned gjennom bunken med det aktuelle elementet for å gjenopprette bunkebetingelsen. Forslag. I en N-punkts prioritetskø, krever heapalgoritmene ikke mer enn 1 lg sammenlignet for innsetting og ikke mer enn 2 lg N sammenlikner for å fjerne maksimumet. Praktiske hensyn. Vi konkluderer med studien av API-høyprioriteringskøen med noen få praktiske hensyn. Multiway heaps. Det er ikke vanskelig å endre koden vår for å bygge hauger basert på en array-representasjon av komplette heapbestilt ternære eller darytende trær. Det er en bytte mellom lavere kostnader fra redusert trehøyde og høyere kostnad for å finne den største av de tre eller d-barna på hver knute. Array resizing. Vi kan legge til en ikke-argumentkonstruktor, kode for array-fordobling i insert (). og kode for array halving i delMax (). akkurat som vi gjorde for stabler i avsnitt 1.3. Logaritmiske tidsgrenser blir amortisert når størrelsen på prioritetskøen er vilkårlig, og arrayene blir endret. Immutability av nøkler. Prioritetskøen inneholder objekter som er opprettet av klienter, men forutsetter at klientkoden ikke endrer nøklene (som kan ugyldiggjøre bunkeinvarianter). Indeks prioritetskø. I mange applikasjoner er det fornuftig å tillate kundene å referere til elementer som allerede er på prioritetskøen. En enkel måte å gjøre det på er å knytte en unik helhetsindeks med hvert element. IndexMinPQ. java er en haugbasert implementering av denne API IndexMaxPQ. java er lik, men for maksimalorienterte prioritetskøer. Multiway. java er en klient som sammenføyer flere sorterte inngangsstrømmer til en sortert utgangsstrøm. Vi kan bruke en hvilken som helst prioritetskø for å utvikle en sorteringsmetode. Vi setter inn alle tastene som skal sorteres i en minimumsrettet prioritets kø, og bruk gjentatte ganger for å fjerne dem alt i orden. Når du bruker en haug for prioritetskøen, får vi heapsort. Med fokus på oppgaven med sortering, forlater vi tanken om å gjemme høydenes representasjon av prioritetskøen og bruk svømme () og sink () direkte. Hvis du gjør det, kan vi sortere en matrise uten å trenge ekstra plass ved å opprettholde bunken i arrayet som skal sorteres. Heapsort går i to faser: heap konstruksjon. hvor vi reorganiserer den opprinnelige gruppen i en bunke og sorteringen. hvor vi trekker varene ut av bunken i avtagende rekkefølge for å bygge det sorterte resultatet. Heap konstruksjon. Vi kan utføre denne oppgaven i tide proporsjonal med N lg N, ved å gå fra venstre til høyre gjennom matrisen, ved å bruke svømmer () for å sikre at oppføringene til venstre for skanningspekeren utgjør et heapbestilt fullstendig tre, som etterfølgende prioritetskøinnlegginger. En smart metode som er mye mer effektiv, er å fortsette fra høyre til venstre, ved hjelp av vask () for å lage underlag som vi går. Hver posisjon i gruppen er roten til en liten subheap sink () - verk eller lignende underlag. Hvis de to barna i en knute er hauger, så kalles vasken () på den knutepunktet, som gjør subtreet rotet der en bunke. Sortdown. Det meste av arbeidet under heapsort er gjort i den andre fasen, hvor vi fjerner de største gjenværende gjenstandene fra bunken og legger den inn i stillingsposisjonen som er forlatt når bunken krymper. Heap. java er en full implementering av heapsort. Nedenfor er et spor av innholdet i matrisen etter hver vask. Forslag. Vaskbasert haugekonstruksjon er lineær tid. Forslag. Heapsort brukere mindre enn 2n lg n sammenligne og utveksle for å sortere n elementer. De fleste gjenstander som er satt inn i bunken under sortering, går helt til bunnen. Vi kan dermed spare tid ved å unngå kontrollen for om varen har nådd sin posisjon, bare fremme den største av de to barna til bunnen er nådd, og deretter flytte opp bakken til riktig posisjon. Denne ideen reduserer antall sammenligninger med en faktor 2 på bekostning av ekstra bokføring. Anta at sekvensen (der et brev betyr å sette inn og en stjerne betyr å fjerne maksimumet) blir brukt til en først og fremst tom prioritetskø. Gi sekvensen av verdier returnert ved å fjerne de maksimale operasjonene. Løsning. R R P O T Y I I U Q E U (E igjen på PQ) Kritisér følgende ide: For å finne maksimalt i konstant tid, hvorfor ikke holde oversikt over maksimalverdien som er satt inn så langt, og returner den verdien for å finne maksimum. Løsning. Vil nødvendigvis oppdatere maksimumsverdien fra bunnen av etter en maksimal drift. Gi prioritetskø implementeringer som støtter innsatsen og fjern maksimalt. en for hver av følgende underliggende datastrukturer: uordnet array, bestilt array, uordnet koblet liste og bestilt koblet liste. Gi en tabell med worst case-grensene for hver operasjon for hver av dine fire implementeringer fra forrige øvelse. Delvis løsning. OrderedArrayMaxPQ. java og UnorderedArrayMaxPQ. java Er en matrise som er sortert i synkende rekkefølge en maksimal orientering. Svar. Ja. Anta at søknaden din vil ha et stort antall innsatsoperasjoner, men bare få fjerner de maksimale operasjonene. Hvilken implementering av prioritetskøen tror du vil være mest effektiv: heap, uordnet array, bestilt array Svar. Uordnet array. Sett inn er konstant tid. Anta at søknaden din vil ha et stort antall finne de maksimale operasjonene, men et relativt lite antall innsatser og fjerne maksimal drift. Hvilken prioritetskøimplementasjon tror du vil være mest effektiv: heap, uordnet array, bestilt array Svar. Ordnet array. Finn maksimum er konstant tid. Hva er minimum antall elementer som må byttes under en fjern maksimal drift i en haug av størrelse N uten dupliserte nøkler Gi en haug med størrelse 15 som minimumet oppnås. Svar på det samme spørsmålet for to og tre påfølgende, fjern de maksimale operasjonene. Delvis svar. (a) 2. Utform en algoritme for lineær tidssertifisering for å kontrollere om et array pq er en minorientert bunke. Løsning. Se metoden isMinHeap () i MinPQ. java. Bevis at sinkbasert haugekonstruksjon bruker maksimalt 2 n sammenlignet og maksimalt n utveksling. Løsning. Det er nok å bevise at sinkbasert haugekonstruksjon bruker færre enn n utveksling fordi antall sammenligninger er høyst dobbelt så mange utvekslinger. For å forenkle, anta at binærhøyden er perfekt (dvs. et binært tre hvor hvert nivå er ferdig fylt) og har høyde h. Vi definerer høyden på en node i et tre for å være subtreetes høyde rotfestet på den noden. En nøkkel i høyden k kan byttes med maksimalt k-taster under den når den senkes ned. Siden det er 2 timer minus k noder i høyden k. Det totale antall utvekslinger er høyst: Den første likestilling er for en ikke-standard sum, men det er greit å verifisere at formelen holder seg gjennom matematisk induksjon. Den andre likestilling holder fordi et perfekt binært tre med høyde h har 2 h 1 minus 1 noder. Å bevise at resultatet holder når det binære treet ikke er perfekt krever litt mer omsorg. Du kan gjøre det ved å bruke det faktum at antall noder i høyden k i en binær bunke på n noder er høyst nivå (n 2 k 1). Alternativ løsning. Igjen, for enkelhet, anta at binærhøyden er perfekt (dvs. et binært tre hvor hvert nivå er fullført). Vi definerer høyden på en node i et tre for å være subtreetes høyde rotfestet på den noden. Først observere at en binær haug på n noder har n minus 1 koblinger (fordi hver lenke er forelder til en node og hver node har en foreldre lenke bortsett fra roten). Å senke en node med høyde k krever mest k utvekslinger. Vi vil lade k-koblinger til hver knute i høyden k. men ikke nødvendigvis koblingene på banen som er tatt når du synker noden. I stedet belaster vi noden k-koden langs stien fra noden som går til venstre-høyre-høyre-høyre-. For eksempel, i diagrammet under, er rotnoden ladet de 4 røde koblingene den blå noden er ladet de 3 blå koblingene og så videre. Merk at ingen kobling er belastet mer enn ett node. (Faktisk er det to koblinger som ikke er belastet noen knutepunkt: den riktige lenken fra rot - og stamkoblingen fra nederste høyre knutepunkt.) Det totale antall utvekslinger er dermed nesten ikke n. Siden det maksimalt er 2 sammenligninger per utveksling, er antall sammenligninger maksimalt 2 n. Kreative problemer Beregningsnummerteori. Skriv et program CubeSum. java som skriver ut alle heltallene av skjemaet en 3 b 3 hvor a og b er heltall mellom 0 og N i rekkefølge, uten å bruke for mye plass. Det er, i stedet for å beregne en rekke N2-summene og sortere dem, bygge en minimumsrettet prioritetskø, som først inneholder (0 3 0, 0), (1 3 1, 0), (2 3 2 , 0). (N3N, 0). Deretter, mens prioritetskøen ikke er tillatt, fjern det minste elementet (i 3 j 3. i, j), skriv det ut, og så, hvis j 3 (j1) 3. i, j1). Bruk dette programmet til å finne alle de forskjellige heltallene a, b, c og d mellom 0 og 106 slik at en 3 b 3 c 3 d 3. f. eks. 1729 93 103 13 123. Finn minimum. Legg til en min () metode til MaxPQ. java. Din implementering skal bruke konstant tid og konstant ekstra plass. Løsning . Legg til en ekstra instansvariabel som peker på det minste elementet. Oppdater det etter hvert anrop for å sette inn (). Tilbakestill den til null hvis prioritetskøen blir tom. Dynamisk-median funnet. Lag en datatype som støtter innsats i logaritmisk tid, finn medianen i konstant tid, og fjern medianen i logaritmisk tid. Løsning . Hold mediannøkkelen inn v bruk en maksimalorientert haug for nøkler mindre enn nøkkelen til v bruk en minorientert haug for nøkler som er større enn nøkkelen til v. For å sette inn, legg til den nye nøkkelen i riktig haug, erstatt v med nøkkelen hentet fra den bunken. Nedre grense. Bevis at det er umulig å utvikle en implementering av MinPQ API slik at både sette inn og slette minimumsgarantien for å bruke N logglogg N, sammenlignes. Løsning. Dette ville gi en N-logg N-sammenligningsbasert sorteringsalgoritme (sett inn N-elementene, fjern gjentatte ganger gjentatte ganger), og bryter med forslaget til Seksjon 2.3. Indeks prioritering-kø implementering. Implementer IndexMaxPQ. java ved å endre MaxPQ. java som følger: Endre pq for å holde indekser, legge til en array nøkler for å holde nøkkelverdiene, og legg til en array qp som er den inverse av pq mdash qpi gir posisjonen til i i pq indeks j slik at pqj er i). Endre koden for å opprettholde disse datastrukturene. Bruk konvensjonen som qpi er -1 hvis jeg ikke er i køen, og inkludere en metode som inneholder () som tester denne tilstanden. Du må endre hjelpemetoder exch () og mindre (), men ikke synke () eller svømme (). Nettøvelser Beste, gjennomsnittlige og verste fall av heapsort. Hva er det beste tilfellet, gjennomsnittlig tilfelle, og verste fall antall sammenligner for heapsorting en rekke lengde N Solution. Hvis vi tillater duplikater, er det beste tilfellet lineær tid (N like nøkler) hvis vi forkaster duplikater, det beste tilfellet er N lg N sammenligner (men det beste tilfelleinngangen er ubehagelig). Det gjennomsnittlige og verste tilfelle antall sammenligninger er 2 N lg N sammenlikninger. Se analysen av Heapsort for detaljer. Beste og verste tilfelle av heapify. Hva er det færre og mest antall sammenligningseksempler som trengs for å heapify en rekke N-produkter Løsning. Hoving av en rekke N-elementer i synkende rekkefølge krever 0-utvekslinger og N-1 sammenligner. Å heapere en rekke N-elementer i stigende rekkefølge krever N-utvekslinger og 2N sammenligner. Taxicab nummer. Finn de minste heltalene som kan uttrykkes som summen av heltalene på to forskjellige måter (1.729), tre forskjellige måter (87.539.319), fire forskjellige måter (6,963,472,309,248), fem forskjellige måter (48.988.659.276.962.496) og seks forskjellige måter (24.153.319.581.254.312.065.344 ). Slike heltall heter Taxicab-tall etter den berømte Ramanujan-historien. De minste heltallene som kan uttrykkes som summen av kubene av heltall på syv forskjellige måter er foreløpig ukjent. Skriv et program Taxicab. java som leser i en kommandolinjeparameter N og skriver ut alle nontrivielle løsninger med en 3 b 3 c 3 d 3. slik at a, b, c og d er mindre enn eller lik N. Beregn tallteori. Finn alle løsninger til ligningen a 2b 2 3c 3 4d 4 for hvilke a, b, c og d er mindre enn 100.000. Hint. bruk en minhurt og en maxhøyde. Avbruddshåndtering. Når du programmerer et sanntidssystem som kan avbrytes (for eksempel med et museklikk eller en trådløs forbindelse), er det nødvendig å følge avbruddene umiddelbart, før du fortsetter med gjeldende aktivitet. Hvis avbruddene skal håndteres i samme rekkefølge de kommer, er en FIFO-kø den riktige datastrukturen. Men hvis forskjellige forstyrrelser har forskjellige prioriteringer (f. eks.), Trenger vi en prioritetskø. Simulering av køenettverk. MM1 kø for dobbel parallell køer, etc. Vanskelig å analysere komplekse køenettverk matematisk. I stedet bruk simulering for å plotte distribusjon av ventetider, etc. Trenger prioritetskø for å avgjøre hvilken hendelse som skal behandles neste. Zipf distribusjon. Bruk resultatet av den forrige øvelsen (e) til å prøve fra Zipfian-fordelingen med parameter s og N. Fordelingen kan ta på heltallverdier fra 1 til N, og tar på verdien k med sannsynlighet 1ks sum (i 1 til N) 1is . Eksempel: Ord i Shakespeare spiller Hamlet med s omtrentlig lik 1. Tilfeldig prosess. Begynn med N-skuffer, hver bestående av en ball. Velg tilfeldig en av N-ballene og flytte ballen til en kasse tilfeldig slik at sannsynligheten for at en ball plasseres i en kasse med m baller er mN. Hva er fordelingen av baller som resulterer etter mange iterasjoner Bruk den tilfeldige prøvetakingsmetoden beskrevet ovenfor for å gjøre simuleringen effektiv. Nærmeste naboer. Gitt N vektorer x 1. x 2. x N med lengde M og en annen vektor x av samme lengde, finn de 20 vektorene som er nærmest x. Sirkel tegnet på et stykke grafpapir. Skriv et program for å finne radius av en sirkel, sentrert på opprinnelsen, som berører 32 poeng med heltall x - og y-koordinater. Hint: se etter et tall enn det kan uttrykkes som summen av to firkanter på flere forskjellige måter. Svar: Det er to pythagoranske tripler med hypotenuse 25: 152 202 252, 72 242 252, og gir 20 slike gitterpunkter. Det er 22 forskjellige Pythagorean-tripper med hypotenuse 5.525, dette fører til 180 gitterpunkter. 27.625 er minste radius som berører mer enn 64. 154.136.450 har 35 Pythagorean tripler. Perfekte krefter. Skriv et program PerfectPower. java for å skrive ut alle perfekte krefter som kan representeres som 64-biters lange heltall: 4, 8, 9, 16, 25, 27. En perfekt kraft er et tall som kan skrives som ab for heltall a og b ge 2. Flytende punkt tillegg. Legg opp N flytpunktsnumre, unngå rundefeil. Slett minst to: Legg til to hverandre, og sett inn igjen. Første passform for binpakking. 1710 OPT 2, 119 OPT 4 (avtagende). Bruk maks turneringstreet hvor spillere er N-bokser og verdien tilgjengelig kapasitet. Stack med minmax. Design en datatype som støtter push, pop, størrelse, min og max (hvor min og max er minimum og maksimale elementer på stakken). Alle operasjoner bør ta konstant tid i verste fall. Hint: Tilknytt hver enkelt stakkoppføring med minimum og maksimalt antall elementer som står på stakken. Kø med minmax. Design en datatype som støtter enqueue, dequeue, size, min og max (hvor min og max er minimum og maksimale elementer i køen). Alle operasjoner bør ta konstant avkortet tid. Tips: Gjør den forrige øvelsen og simuler en kø med to stabler. 2i 5j. Skriv ut tallene på skjemaet 2i 5j i stigende rekkefølge. Min-max bunke. Design en datastruktur som støtter min og max i konstant tid, sett inn, slett min og slett maks i logaritmisk tid ved å sette elementene i et enkelt utvalg av størrelse N med følgende egenskaper: Strukturen representerer et komplett binært tre. Nøkkelen i en node på et jevnt nivå er mindre enn (eller liknende) nøklene i dens undertreet nøkkelen i en node på et ulikt nivå er større enn (eller liknende) nøklene i dens undertreet. Vær oppmerksom på at maksimumverdien er lagret ved roten og minimumsverdien er lagret på en av røttene children. Solution. Min-Max Hopper og Generalized Priority Queues Range minimum spørring. Gitt en sekvens av N-elementer, er en rekkeminimumsforespørsel fra indeksen i til j indeksen for det minste elementet mellom i og j. Utform en datastruktur som preprocesserer sekvensen av N-elementer i lineær tid for å støtte minimumsintervall i logaritmisk tid. Bevis at et komplett binært tre med N noder har nøyaktig tak (N2) blad noder (noder uten barn). Maksimalorientert prioritetskø med min. Hva er rekkefølgen av veksten av kjøretiden for å finne en minimumsnøkkel i en maksimal-orientert binær haug. Løsning . linearmdashthe minimum nøkkelen kan være i noen av taket (N2) blad noder. Maksimalorientert prioritetskø med min. Design en datatype som støtter innstikk og fjern-maksimum i logaritmisk tid sammen med både maks en min i konstant tid. Løsning. Opprett en maksimal orientert binær bunke og lagre også minsteknappen så langt (som aldri vil øke med mindre denne bunken blir tom). kth største objektet større enn x. Gitt en maksimal orientert binær haug, utform en algoritme for å avgjøre om kth største objektet er større enn eller lik x. Din algoritme skal løpe i tid proporsjonal med k. Løsning . Hvis nøkkelen i noden er større enn eller lik x, søker du rekursivt både til venstre undertreet og høyre undertreet. Stopp når antall noder utforsket er lik k (svaret er ja) eller det er ikke flere noder å utforske (nei). kth minste gjenstand i en minorientert binær haug. Opprett en k log k algoritme for å finne det kth minste elementet i en min-orientert binærhakke H som inneholder N elementer. Løsning. Bygg en ny minorientert bunke H. Vi vil ikke modifisere H. Sett inn roten til H i ​​H sammen med bunkeindeksen 1. Gjenta gjentatte ganger det minste elementet x i H og sett inn i H de to barna x fra H . Kth-elementet slettet fra H er kth minste punkt i H. Randomized kø. Implementer en RandomQueue slik at hver operasjon er garantert å ta mest logaritmisk tid. Hint. kan ikke råd til array dobling. Ingen enkel måte med koblede lister for å finne et tilfeldig element i O (1) tid. I stedet bruker du et komplett binært tre med eksplisitte lenker. FIFO-kø med tilfeldig sletting. Implementere en datatype som støtter følgende operasjoner: sett inn et element. slette elementet som sist ble lagt til og slett et tilfeldig element. Hver operasjon bør i det minste ta (høyst) logaritmisk tid. Løsning . Bruk et komplett binært tre med eksplisitte koblinger tilordne den lange heltalsprioriteten jeg til den i posten lagt til datastrukturen. Topp k summer av to sorterte arrays. Gitt to sorterte arrays a og b, finner hver lengde N de største k-summene av skjemaet ai bj. Hint. Ved å bruke en prioritetskø (tilsvarende taxicabproblemet), kan du oppnå en O (k log N) algoritme. Overraskende er det mulig å gjøre det i O (k) tid, men algoritmen er komplisert. Empirisk analyse av haugkonstruksjon. Sammenligne empirisk line-time bottom-up heap konstruksjon versus den naive linearithmic-time topp-down heap konstruksjon. Vær sikker på å kompradere den over en rekke verdier av N. LaMarca og Ladner rapporterer at på grunn av cache-lokalitet kan naivalgoritmen utføre bedre i praksis enn den mer klare tilnærmingen til store verdier av N (når bunken ikke lenger passer i cache) selv om sistnevnte utfører mange færre sammenligninger og utvekslinger. Empirisk analyse av flerveishunder. Empirisk sammenligne ytelsen på 2- 4- og 8-veis hauger. LaMarca og Ladner foreslår flere optimaliseringer, med tanke på caching-effekter. Empirisk analyse av heapsort. Empirisk sammenligne ytelsen til 2- 4- og 8-veis heapsort. LaMarca og Ladner foreslår flere optimaliseringer, med tanke på caching-effekter. Deres data indikerer at en optimalisert (og minneinnstilt) 8-veis heapsort kan være dobbelt så rask som klassisk heapsort. Heapify ved innsetting. Anta at du bulider en binær haug på N-tastene ved å gjenta den neste nøkkelen i binærhugen. Vis at totalt antall sammenlikninger er høyst svar. Antall sammenligninger er høyst lg 1 lg 2. Lg N lg (N) N lg N. Forhøy nedre bundet. (Gonnet og Munro) Vis at en sammenligningsbasert algoritme for å bygge en binær haug på N-tastene tar minst 1,3644 N i verste fall. Svar . bruk et informasjonsteoretisk argument, ala sortering nedre bundet. Det er N mulige hauger (permutasjon av N-tallene) på N forskjellige taster, men det er mange hauger som tilsvarer samme bestilling. For eksempel er det to dynger (cab og cba) som samsvarer med de tre elementene aCisco IOS Kvalitet for service løsninger Konfigurasjonsveiledning, Utgivelse 12.2 Overstyring Undersøkelse Overvåkningsteknikker overvåker nettverkstrafikkbelastninger i et forsøk på å forutse og unngå overbelastning på felles nettverk flaskehalser. Congestion unngåelse oppnås gjennom pakke slippe. Blant de mer vanlige overbelastningsmekanismene er tilfeldig tidlig deteksjon (RED), som er optimal for høyhastighets transittnett. Cisco IOS QoS inkluderer en implementering av RED som, når den er konfigurert, styrer når ruteren slipper pakker. Hvis du ikke konfigurerer Veidet Tilfeldig Tidlig Deteksjon (WRED), bruker ruteren den vanlige standardpakke-dråpemekanismen kalt halefeil. For en forklaring på nettverksbelastning, se kapitlet Kvartalsoversikt for Serviceoversikt. quot Dette kapittelet gir en kort beskrivelse av hvilke typer mekanismer for overbelastning som leveres av Cisco IOS QoS-funksjonene. Det diskuterer følgende funksjoner: Halefalle. Dette er standard overbelastningsadferd når WRED ikke er konfigurert. WRED. WRED og distribuert WRED (DWRED), begge er Cisco implementeringer av REDcombine funksjonene til den Røde algoritmen med IP Precedence-funksjonen. I avsnittet om WRED diskuteres følgende relaterte funksjoner: Flow-basert WRED. Flytbasert WRED utvider WRED for å gi større rettferdighet til alle strømmer på et grensesnitt med hensyn til hvordan pakker blir tapt. DiffServ-kompatibel WRED. DiffServ-kompatibel WRED utvider WRED for å støtte Differentiated Services (DiffServ) og Assured Forwarding (AF) Per Hop Behavior (PHB). Denne funksjonen gjør det mulig for kunder å implementere AF PHB ved å fargepakke i henhold til DSCP-verdier for differensierte tjenester, og deretter tilordne fortrinnsrettesannsynligheter til disse pakkene. For informasjon om hvordan du konfigurerer WRED, DWRED, flowbasert WRED og DiffServ Compliant WRED, se kapitteletConfiguring Weighted Random Early Detectionquot i denne boken. Tail drop behandler all trafikk likt og skiller ikke mellom tjenesteklasser. Køer fyller i perioder med overbelastning. Når utgangskøen er full og halen slipp er i kraft, blir pakker droppet til overbelastningen er eliminert og køen er ikke lenger full. Veidet tilfeldig tidlig oppdagelse Denne delen gir en kort introduksjon til Røde konsepter og adresser WRED, Cisco implementering av RED for standard Cisco IOS-plattformer. WRED unngår globaliseringsproblemer som oppstår når halefallet brukes som overbelastningsemekanisme på ruteren. Global synkronisering oppstår som bølger av overbelastningskamp bare for å bli fulgt av troughs der transmisjonskoblingen ikke er fullt utnyttet. Global synkronisering av TCP-verter kan for eksempel oppstå fordi pakkene blir tapt alt på en gang. Globale synkroniserings manifesterer når flere TCP-verter reduserer overføringshastighetene som svar på pakkefeil, og deretter øker overføringshastigheten igjen når overbelastningen reduseres. Om tilfeldig tidlig oppdagelse Den Røde mekanismen ble foreslått av Sally Floyd og Van Jacobson tidlig på 1990-tallet for å takle nettverksbelastning på en responsiv snarere enn reaktiv måte. Underliggende RØDMekanismen er premisset om at trafikken kjører på data transport implementeringer som er følsomme for tap og vil midlertidig bremse når noen av trafikken er tapt. TCP, som reagerer hensiktsmessig og robust til trafikkfall ved å redusere trafikkoverføringen, gjør det mulig å redusere trafikkfallet til RED som en signaleringsmekanisme for overbelastning. TCP er den mest brukte nettverkstransporten. Gitt den allestedsnærværende tilstedeværelsen av TCP, tilbyr RED en utbredt, effektiv overbelastnings-mekanisme. Når man vurderer nytten av RED når robuste transporter som TCP er gjennomgripende, er det viktig å også vurdere de alvorlig negative implikasjonene ved å bruke RED når en betydelig prosentandel av trafikken ikke er robust som følge av pakktap. Verken Novell NetWare eller AppleTalk er hensiktsmessig robust som følge av pakketap, derfor bør du ikke bruke RED for dem. How It Works RED aims to control the average queue size by indicating to the end hosts when they should temporarily slow down transmission of packets. RED takes advantage of the congestion control mechanism of TCP. By randomly dropping packets prior to periods of high congestion, RED tells the packet source to decrease its transmission rate. Assuming the packet source is using TCP, it will decrease its transmission rate until all the packets reach their destination, indicating that the congestion is cleared. You can use RED as a way to cause TCP to slow down transmission of packets. TCP not only pauses, but it also restarts quickly and adapts its transmission rate to the rate that the network can support. RED distributes losses in time and maintains normally low queue depth while absorbing spikes. When enabled on an interface, RED begins dropping packets when congestion occurs at a rate you select during configuration. For an explanation of how the Cisco WRED implementation determines parameters to use in the WRED queue size calculations and how to determine optimum values to use for the weight factor, see the section quotAverage Queue Sizequot later in this chapter. Packet Drop Probability The packet drop probability is based on the minimum threshold, maximum threshold, and mark probability denominator. When the average queue depth is above the minimum threshold, RED starts dropping packets. The rate of packet drop increases linearly as the average queue size increases until the average queue size reaches the maximum threshold. The mark probability denominator is the fraction of packets dropped when the average queue depth is at the maximum threshold. For example, if the denominator is 512, one out of every 512 packets is dropped when the average queue is at the maximum threshold. When the average queue size is above the maximum threshold, all packets are dropped. Figure 9 summarizes the packet drop probability. Figure 9 RED Packet Drop Probability The minimum threshold value should be set high enough to maximize the link utilization. If the minimum threshold is too low, packets may be dropped unnecessarily, and the transmission link will not be fully used. The difference between the maximum threshold and the minimum threshold should be large enough to avoid global synchronization of TCP hosts (global synchronization of TCP hosts can occur as multiple TCP hosts reduce their transmission rates). If the difference between the maximum and minimum thresholds is too small, many packets may be dropped at once, resulting in global synchronization. How TCP Handles Traffic Loss Note The sections quotHow TCP Handles Traffic Lossquot and quotHow the Router Interacts with TCPquot contain detailed information that you need not read in order to use WRED or to have a general sense of the capabilities of RED. If you want to understand why problems of global synchronization occur in response to congestion when tail drop is used by default and how RED addresses them, read these sections. When the recipient of TCP trafficcalled the receiverreceives a data segment, it checks the four octet (32-bit) sequence number of that segment against the number the receiver expected, which would indicate that the data segment was received in order. If the numbers match, the receiver delivers all of the data that it holds to the target application, then it updates the sequence number to reflect the next number in order, and finally it either immediately sends an acknowledgment (ACK) packet to the sender or it schedules an ACK to be sent to the sender after a short delay. The ACK notifies the sender that the receiver received all data segments up to but not including the one marked with the new sequence number. Receivers usually try to send an ACK in response to alternating data segments they receive they send the ACK because for many applications, if the receiver waits out a small delay, it can efficiently include its reply acknowledgment on a normal response to the sender. However, when the receiver receives a data segment out of order, it immediately responds with an ACK to direct the sender to resend the lost data segment. When the sender receives an ACK, it makes this determination: It determines if any data is outstanding. If no data is outstanding, the sender determines that the ACK is a keepalive, meant to keep the line active, and it does nothing. If data is outstanding, the sender determines whether the ACK indicates that the receiver has received some or none of the data. If the ACK indicates receipt of some data sent, the sender determines if new credit has been granted to allow it to send more data. When the ACK indicates receipt of none of the data sent and there is outstanding data, the sender interprets the ACK to be a repeatedly sent ACK. This condition indicates that some data was received out of order, forcing the receiver to remit the first ACK, and that a second data segment was received out of order, forcing the receiver to remit the second ACK. In most cases, the receiver would receive two segments out of order because one of the data segments had been dropped. When a TCP sender detects a dropped data segment, it resends the segment. Then it adjusts its transmission rate to half of what is was before the drop was detected. This is the TCP back-off or slow-down behavior. Although this behavior is appropriately responsive to congestion, problems can arise when multiple TCP sessions are carried on concurrently with the same router and all TCP senders slow down transmission of packets at the same time. How the Router Interacts with TCP Note The sections quotHow TCP Handles Traffic Lossquot and quotHow the Router Interacts with TCPquot contain detailed information that you need not read in order to use WRED or to have a general sense of the capabilities of RED. If you want to understand why problems of global synchronization occur in response to congestion when tail drop is used by default and how RED addresses them, read these sections. To see how the router interacts with TCP, we will look at an example. In this example, on average, the router receives traffic from one particular TCP stream every other, every 10th, and every 100th or 200th message in the interface in MAE-EAST or FIX-WEST. A router can handle multiple concurrent TCP sessions. Because network flows are additive, there is a high probability that when traffic exceeds the Transmit Queue Limit (TQL) at all, it will vastly exceed the limit. However, there is also a high probability that the excessive traffic depth is temporary and that traffic will not stay excessively deep except at points where traffic flows merge or at edge routers. If the router drops all traffic that exceeds the TQL, as is done when tail drop is used by default, many TCP sessions will simultaneously go into slow start. Consequently, traffic temporarily slows down to the extreme and then all flows slow-start again this activity creates a condition of global synchronization. However, if the router drops no traffic, as is the case when queueing features such as fair queueing or custom queueing (CQ) are used, then the data is likely to be stored in main memory, drastically degrading router performance. By directing one TCP session at a time to slow down, RED solves the problems described, allowing for full utilization of the bandwidth rather than utilization manifesting as crests and troughs of traffic. About WRED WRED combines the capabilities of the RED algorithm with the IP Precedence feature to provide for preferential traffic handling of higher priority packets. WRED can selectively discard lower priority traffic when the interface begins to get congested and provide differentiated performance characteristics for different classes of service. You can configure WRED to ignore IP precedence when making drop decisions so that nonweighted RED behavior is achieved. For interfaces configured to use the Resource Reservation Protocol (RSVP) feature, WRED chooses packets from other flows to drop rather than the RSVP flows. Also, IP Precedence governs which packets are droppedtraffic that is at a lower precedence has a higher drop rate and therefore is more likely to be throttled back. WRED differs from other congestion avoidance techniques such as queueing strategies because it attempts to anticipate and avoid congestion rather than control congestion once it occurs. Why Use WRED WRED makes early detection of congestion possible and provides for multiple classes of traffic. It also protects against global synchronization. For these reasons, WRED is useful on any output interface where you expect congestion to occur. However, WRED is usually used in the core routers of a network, rather than at the edge of the network. Edge routers assign IP precedences to packets as they enter the network. WRED uses these precedences to determine how to treat different types of traffic. WRED provides separate thresholds and weights for different IP precedences, allowing you to provide different qualities of service in regard to packet dropping for different traffic types. Standard traffic may be dropped more frequently than premium traffic during periods of congestion. WRED is also RSVP-aware, and it can provide the controlled-load QoS service of integrated service. How It Works By randomly dropping packets prior to periods of high congestion, WRED tells the packet source to decrease its transmission rate. If the packet source is using TCP, it will decrease its transmission rate until all the packets reach their destination, which indicates that the congestion is cleared. WRED generally drops packets selectively based on IP precedence. Packets with a higher IP precedence are less likely to be dropped than packets with a lower precedence. Thus, the higher the priority of a packet, the higher the probability that the packet will be delivered. WRED reduces the chances of tail drop by selectively dropping packets when the output interface begins to show signs of congestion. By dropping some packets early rather than waiting until the queue is full, WRED avoids dropping large numbers of packets at once and minimizes the chances of global synchronization. Thus, WRED allows the transmission line to be used fully at all times. In addition, WRED statistically drops more packets from large users than small. Therefore, traffic sources that generate the most traffic are more likely to be slowed down than traffic sources that generate little traffic. WRED avoids the globalization problems that occur when tail drop is used as the congestion avoidance mechanism. Global synchronization manifests when multiple TCP hosts reduce their transmission rates in response to packet dropping, then increase their transmission rates once again when the congestion is reduced. WRED is only useful when the bulk of the traffic is TCPIP traffic. With TCP, dropped packets indicate congestion, so the packet source will reduce its transmission rate. With other protocols, packet sources may not respond or may resend dropped packets at the same rate. Thus, dropping packets does not decrease congestion. WRED treats non-IP traffic as precedence 0, the lowest precedence. Therefore, non-IP traffic, in general, is more likely to be dropped than IP traffic. Figure 10 illustrates how WRED works. Figure 10 Weighted Random Early Detection Average Queue Size The router automatically determines parameters to use in the WRED calculations. The average queue size is based on the previous average and the current size of the queue. The formula is: where n is the exponential weight factor, a user-configurable value. For high values of n . the previous average becomes more important. A large factor smooths out the peaks and lows in queue length. The average queue size is unlikely to change very quickly, avoiding drastic swings in size. The WRED process will be slow to start dropping packets, but it may continue dropping packets for a time after the actual queue size has fallen below the minimum threshold. The slow-moving average will accommodate temporary bursts in traffic. Note If the value of n gets too high, WRED will not react to congestion. Packets will be sent or dropped as if WRED were not in effect. For low values of n . the average queue size closely tracks the current queue size. The resulting average may fluctuate with changes in the traffic levels. In this case, the WRED process responds quickly to long queues. Once the queue falls below the minimum threshold, the process will stop dropping packets. If the value of n gets too low, WRED will overreact to temporary traffic bursts and drop traffic unnecessarily. Restrictions You cannot configure WRED on the same interface as Route Switch Processor (RSP)-based CQ, priority queueing (PQ), or weighted fair queueing (WFQ). Distributed Weighted Random Early Detection Distributed WRED (DWRED) is an implementation of WRED for the Versatile Interface Processor (VIP). DWRED provides the complete set of functions for the VIP that WRED provides on standard Cisco IOS platforms. The DWRED feature is only supported on Cisco 7000 series routers with an RSP-based RSP7000 interface processor and Cisco 7500 series routers with a VIP-based VIP2-40 or greater interface processor. A VIP2-50 interface processor is strongly recommended when the aggregate line rate of the port adapters on the VIP is greater than DS3. A VIP2-50 interface processor is required for OC-3 rates. DWRED is configured the same way as WRED. If you enable WRED on a suitable VIP interface, such as a VIP2-40 or greater with at least 2 MB of SRAM, DWRED will be enabled instead. In order to use DWRED, distributed Cisco Express Forwarding (dCEF) switching must be enabled on the interface. For information about dCEF, refer to the Cisco IOS Switching Services Configuration Guide and the Cisco IOS Switching Services Command Reference. You can configure both DWRED and distributed weighted fair queueing (DWFQ) on the same interface, but you cannot configure distributed WRED on an interface for which RSP-based CQ, PQ, or WFQ is configured. You can enable DWRED using the Modular Quality of Service Command-Line Interface (Modular QoS CLI) feature. For complete conceptual and configuration information on the Modular QoS CLI feature, see the chapter quotModular Quality of Service Command-Line Interface Overviewquot of this book. How It Works When a packet arrives and DWRED is enabled, the following events occur: The average queue size is calculated. See the quotAverage Queue Sizequot section for details. If the average is less than the minimum queue threshold, the arriving packet is queued. If the average is between the minimum queue threshold and the maximum queue threshold, the packet is either dropped or queued, depending on the packet drop probability. See the quotPacket-Drop Probabilityquot section for details. If the average queue size is greater than the maximum queue threshold, the packet is automatically dropped. Average Queue Size The average queue size is based on the previous average and the current size of the queue. The formula is: where n is the exponential weight factor, a user-configurable value. For high values of n. the previous average queue size becomes more important. A large factor smooths out the peaks and lows in queue length. The average queue size is unlikely to change very quickly, avoiding drastic swings in size. The WRED process will be slow to start dropping packets, but it may continue dropping packets for a time after the actual queue size has fallen below the minimum threshold. The slow-moving average will accommodate temporary bursts in traffic. Note If the value of n gets too high, WRED will not react to congestion. Packets will be sent or dropped as if WRED were not in effect. For low values of n. the average queue size closely tracks the current queue size. The resulting average may fluctuate with changes in the traffic levels. In this case, the WRED process responds quickly to long queues. Once the queue falls below the minimum threshold, the process stops dropping packets. If the value of n gets too low, WRED will overreact to temporary traffic bursts and drop traffic unnecessarily. Packet-Drop Probability The probability that a packet will be dropped is based on the minimum threshold, maximum threshold, and mark probability denominator. When the average queue size is above the minimum threshold, RED starts dropping packets. The rate of packet drop increases linearly as the average queue size increases, until the average queue size reaches the maximum threshold. The mark probability denominator is the fraction of packets dropped when the average queue size is at the maximum threshold. For example, if the denominator is 512, one out of every 512 packets is dropped when the average queue is at the maximum threshold. When the average queue size is above the maximum threshold, all packets are dropped. Figure 11 summarizes the packet drop probability. Figure 11 Packet Drop Probability The minimum threshold value should be set high enough to maximize the link utilization. If the minimum threshold is too low, packets may be dropped unnecessarily, and the transmission link will not be fully used. The difference between the maximum threshold and the minimum threshold should be large enough to avoid global synchronization of TCP hosts (global synchronization of TCP hosts can occur as multiple TCP hosts reduce their transmission rates). If the difference between the maximum and minimum thresholds is too small, many packets may be dropped at once, resulting in global synchronization. Why Use DWRED DWRED provides faster performance than does RSP-based WRED. You should run DWRED on the VIP if you want to achieve very high speed on the Cisco 7500 series platformfor example, you can achieve speed at the OC-3 rates by running WRED on a VIP2-50 interface processor. Additionally, the same reasons you would use WRED on standard Cisco IOS platforms apply to using DWRED. (See the section quotWhy Use WREDquot earlier in this chapter.) For instance, when WRED or DWRED is not configured, tail drop is enacted during periods of congestion. Enabling DWRED obviates the global synchronization problems that result when tail drop is used to avoid congestion. The DWRED feature provides the benefit of consistent traffic flows. When RED is not configured, output buffers fill during periods of congestion. When the buffers are full, tail drop occurs all additional packets are dropped. Because the packets are dropped all at once, global synchronization of TCP hosts can occur as multiple TCP hosts reduce their transmission rates. The congestion clears, and the TCP hosts increase their transmission rates, resulting in waves of congestion followed by periods when the transmission link is not fully used. RED reduces the chances of tail drop by selectively dropping packets when the output interface begins to show signs of congestion. By dropping some packets early rather than waiting until the buffer is full, RED avoids dropping large numbers of packets at once and minimizes the chances of global synchronization. Thus, RED allows the transmission line to be used fully at all times. In addition, RED statistically drops more packets from large users than small. Therefore, traffic sources that generate the most traffic are more likely to be slowed down than traffic sources that generate little traffic. DWRED provides separate thresholds and weights for different IP precedences, allowing you to provide different qualities of service for different traffic. Standard traffic may be dropped more frequently than premium traffic during periods of congestion. Restrictions The following restrictions apply to the DWRED feature: Interface-based DWRED cannot be configured on a subinterface. (A subinterface is one of a number of virtual interfaces on a single physical interface.) DWRED is not supported on Fast EtherChannel and tunnel interfaces. RSVP is not supported on DWRED. DWRED is useful only when the bulk of the traffic is TCPIP traffic. With TCP, dropped packets indicate congestion, so the packet source reduces its transmission rate. With other protocols, packet sources may not respond or may resend dropped packets at the same rate. Thus, dropping packets does not necessarily decrease congestion. DWRED treats non-IP traffic as precedence 0, the lowest precedence. Therefore, non-IP traffic is usually more likely to be dropped than IP traffic. DWRED cannot be configured on the same interface as RSP-based CQ, PQ, or WFQ. However, both DWRED and DWFQ can be configured on the same interface. Note Do not use the match protocol command to create a traffic class with a non-IP protocol as a match criterion. The VIP does not support matching of non-IP protocols. Prerequisites This section provides the prerequisites that must be met before you configure the DWRED feature. Weighted Fair Queueing Attaching a service policy to an interface disables WFQ on that interface if WFQ is configured for the interface. For this reason, you should ensure that WFQ is not enabled on such an interface before configuring DWRED. Attaching a service policy configured to use WRED to an interface disables WRED on that interface. If any of the traffic classes that you configure in a policy map use WRED for packet drop instead of tail drop, you must ensure that WRED is not configured on the interface to which you intend to attach that service policy. Access Control Lists You can specify a numbered access list as the match criterion for any traffic class that you create. For this reason, before configuring DWRED you should know how to configure access lists. Cisco Express Forwarding In order to use DWRED, dCEF switching must be enabled on the interface. For information on dCEF, refer to the Cisco IOS Switching Services Configuration Guide . Flow-Based WRED Flow-based WRED is a feature that forces WRED to afford greater fairness to all flows on an interface in regard to how packets are dropped. Why Use Flow-Based WRED Before you consider the advantages that use of flow-based WRED offers, it helps to think about how WRED (without flow-based WRED configured) affects different kinds of packet flows. Even before flow-based WRED classifies packet flows, flows can be thought of as belonging to one of the following categories: Nonadaptive flows, which are flows that do not respond to congestion. Robust flows, which on average have a uniform data rate and slow down in response to congestion. Fragile flows, which, though congestion-aware, have fewer packets buffered at a gateway than do robust flows. WRED tends toward bias against fragile flows because all flows, even those with relatively fewer packets in the output queue, are susceptible to packet drop during periods of congestion. Though fragile flows have fewer buffered packets, they are dropped at the same rate as packets of other flows. To provide fairness to all flows, flow-based WRED has the following features: It ensures that flows that respond to WRED packet drops (by backing off packet transmission) are protected from flows that do not respond to WRED packet drops. It prohibits a single flow from monopolizing the buffer resources at an interface. How It Works Flow-based WRED relies on the following two main approaches to remedy the problem of unfair packet drop: It classifies incoming traffic into flows based on parameters such as destination and source addresses and ports. It maintains state about active flows, which are flows that have packets in the output queues. Flow-based WRED uses this classification and state information to ensure that each flow does not consume more than its permitted share of the output buffer resources. Flow-based WRED determines which flows monopolize resources and it more heavily penalizes these flows. To ensure fairness among flows, flow-based WRED maintains a count of the number of active flows that exist through an output interface. Given the number of active flows and the output queue size, flow-based WRED determines the number of buffers available per flow. To allow for some burstiness, flow-based WRED scales the number of buffers available per flow by a configured factor and allows each active flow to have a certain number of packets in the output queue. This scaling factor is common to all flows. The outcome of the scaled number of buffers becomes the per-flow limit. When a flow exceeds the per-flow limit, the probability that a packet from that flow will be dropped increases. DiffServ Compliant WRED DiffServ Compliant WRED extends the functionality of WRED to enable support for DiffServ and AF Per Hop Behavior PHB. This feature enables customers to implement AF PHB by coloring packets according to DSCP values and then assigning preferential drop probabilities to those packets. Note This feature can be used with IP packets only. It is not intended for use with Multiprotocol Label Switching (MPLS)-encapsulated packets. The Class-Based Quality of Service MIB supports this feature. This MIB is actually the following two MIBs: The DiffServ Compliant WRED feature supports the following RFCs: RFC 2474, Definition of the Differentiated Services Field (DS Field) in the IPv4 and IPv6 Headers RFC 2475, An Architecture for Differentiated Services Framework RFC 2597, Assured Forwarding PHB RFC 2598, An Expedited Forwarding PHB How It Works The DiffServ Compliant WRED feature enables WRED to use the DSCP value when it calculates the drop probability for a packet. The DSCP value is the first six bits of the IP type of service (ToS) byte. This feature adds two new commands, random-detect dscp and dscp . It also adds two new arguments, dscp-based and prec-based . to two existing WRED-related commandsthe random-detect (interface) command and the random-detect-group command. The dscp-based argument enables WRED to use the DSCP value of a packet when it calculates the drop probability for the packet. The prec-based argument enables WRED to use the IP Precedence value of a packet when it calculates the drop probability for the packet. These arguments are optional (you need not use any of them to use the commands) but they are also mutually exclusive. That is, if you use the dscp-based argument, you cannot use the prec-based argument with the same command. After enabling WRED to use the DSCP value, you can then use the new random-detect dscp command to change the minimum and maximum packet thresholds for that DSCP value. Three scenarios for using these arguments are provided. Usage Scenarios The new dscp-based and prec-based arguments can be used whether you are using WRED at the interface level, at the per-virtual circuit (VC) level, or at the class level (as part of class-based WFQ (CBWFQ) with policy maps). WRED at the Interface Level At the interface level, if you want to have WRED use the DSCP value when it calculates the drop probability, you can use the dscp-based argument with the random-detect (interface) command to specify the DSCP value. Then use the random-detect dscp command to specify the minimum and maximum thresholds for the DSCP value. WRED at the per-VC Level At the per-VC level, if you want to have WRED use the DSCP value when it calculates the drop probability, you can use the dscp-based argument with the random-detect-group command. Then use the dscp command to specify the minimum and maximum thresholds for the DSCP value or the mark-probability denominator. This configuration can then be applied to each VC in the network. WRED at the Class Level If you are using WRED at the class level (with CBWFQ), the dscp-based and prec-based arguments can be used within the policy map. First, specify the policy map, the class, and the bandwidth. Then, if you want WRED to use the DSCP value when it calculates the drop probability, use the dscp-based argument with the random-detect (interface) command to specify the DSCP value. Then use the random-detect dscp command to modify the default minimum and maximum thresholds for the DSCP value. This configuration can then be applied wherever policy maps are attached (for example, at the interface level, the per-VC level, or the shaper level). Usage Points to Note Remember the following points when using the new commands and the new arguments included with this feature: If you use the dscp-based argument, WRED will use the DSCP value to calculate the drop probability. If you use the prec-based argument, WRED will use the IP Precedence value to calculate the drop probability. The dscp-based and prec-based arguments are mutually exclusive. If you do not specify either argument, WRED will use the IP Precedence value to calculate the drop probability (the default method). The random-detect dscp command must be used in conjunction with the random-detect (interface) command. The random-detect dscp command can only be used if you use the dscp-based argument with the random-detect (interface) command. The dscp command must be used in conjunction with the random-detect-group command. The dscp command can only be used if you use the dscp-based argument with the random-detect-group command. For more information about using these commands, refer to the Cisco IOS Quality of Service Command Reference. The purpose of this document is to describe how IOs are queued the disk device driver and the adapter device driver, SDD, and SDDPCM and to explain how these can be tuned to increase performance. And this also includes the use of VIO. This information is also useful for AIX LPARs using other multi-path code as well. Where this stuff fits in the IO stack Following is the IO stack from the application to the disk: Application File system (optional) LVM device driver (optional) SDD or SDDPCM or other multi-path driver (if used) hdisk device driver adapter device driver interconnect to the disk Disk subsystem Disk Note that even though the disk is attached to the adapter, the hdisk driver code is utilized before the adapter driver code. So this stack represents the order software comes into play over time as the IO traverses the stack. Why do we need to simultaneously submit more than one IO to a disk This improves performance. And this would be performance from an applications point of view. This is especially important with disk subsystems where a virtual disk (or LUN) is backed by multiple physical disks. In such a situation, if we only could submit a single IO at a time, wed find we get good IO service times, but very poor thruput. Submitting multiple IOs to a physical disk allows the disk to minimize actuator movement (using an elevator algorithm) and get more IOPS than is possible by submitting one IO at a time. The elevator analogy is appropriate. How long would people be waiting to use an elevator if only one person at a time could get on it In such a situation, wed expect that people would wait quite a while to use the elevator (queueing time), but once they got on it, theyd get to their destination quickly (service time). So submitting multiple in-flight IOs to a disk subsystem allows it to figure out how to get the most thruput and fastest overall IO service time. Theoretically, the IOPS for a disk is limited by queuedepth(average IO service time). Assuming a queuedepth of 3, and an average IO service time of 10 ms, this yields a maximum thruput of 300 IOPS for the hdisk. And for many applications this may not be enough thruput. Where are IOs queued As IOs traverse the IO stack, AIX needs to keep track of them at each layer. So IOs are essentially queued at each layer. Generally, some number of in flight IOs may be issued at each layer and if the number of IO requests exceeds that number, they reside in a wait queue until the required resource becomes available. So there is essentially an in process queue and a wait queue at each layer (SDD and SDDPCM are a little more complicated). At the file system layer, file system buffers limit the maximum number of in flight IOs for each file system. At the LVM device driver layer, hdisk buffers limit the number of in flight IOs. At the SDD layer, IOs are queued if the dpo devices attribute, qdepthenable, is set to yes (which it is by default). Some releases of SDD do not queue IOs so it depends on the release of SDD. SDDPCM on the other hand does not queue IOs before sending them to the disk device driver. The hdisks have a maximum number of in flight IOs thats specified by its queuedepth attribute. And FC adapters also have a maximum number of in flight IOs specified by numcmdelems. The disk subsystems themselves queue IOs and individual physical disks can accept multiple IO requests but only service one at a time. Here are an ESS hdisks attributes: lsattr - El hdisk33 PRkeyvalue none Reserve Key True location Location Label True lunid 0x5515000000000000 Logical Unit Number ID True lunresetspt yes Support SCSI LUN reset True maxtransfer 0x40000 NA True nodename 0x5005076300c096ab FC Node Name False pvid none Physical volume identifier False qtype simple Queuing TYPE True qfulldly 20 delay in seconds for SCSI TASK SET FULL True queuedepth 20 Queue DEPTH True reservepolicy singlepath Reserve Policy True rwtimeout 60 READWRITE time out value True scbsydly 20 delay in seconds for SCSI BUSY True scsiid 0x620713 SCSI ID True starttimeout 180 START unit time out value True wwname 0x5005076300cd96ab FC World Wide Name False The default queuedepth is 20, but can be changed to as high as 256 for ESS, DS6000 and DS8000. One can display allowable values with: lsattr - Rl hdisk33 - a queuedepth 1. 256 (1) indicating the value can be anywhere from 1 to 256 in increments of 1. One can use this command to see any allowable value for attributes which can be changed (showing a value of True in the last field of lsattr - El ltdevicegt for the device using: lsattr - Rl ltdevicegt - a ltattributegt Heres a FC adapters attributes: lsattr - El fcs0 busintrlvl 65703 Bus interrupt level False busioaddr 0xdec00 Bus IO address False busmemaddr 0xe8040000 Bus memory address False initlink al INIT Link flags True intrpriority 3 Interrupt priority False lgtermdma 0x800000 Long term DMA True maxxfersize 0x100000 Maximum Transfer Size True numcmdelems 200 Maximum number of COMMANDS to queue to the adapter True prefalpa 0x1 Preferred ALPA True swfcclass 2 FC Class for Fabric True The default queue depth (numcmdelems) for FC adapters is 200 but can be increased up to 2048 for most adapters. Heres the dpo devices attributes for one release of SDD: lsattr - El dpo Enterprmaxlun 600 Maximum LUNS allowed for Enterprise Products True Virtualmaxlun 512 Maximum LUNS allowed for Virtualization Products False persistentresv yes Subsystem Supports Persistent Reserve Command False qdepthenable yes Queue Depth Control True When qdepthenableyes, SDD will only submit queuedepth IOs to any underlying hdisk (where queuedepth here is the value for the underlying hdisks queuedepth attribute). When qdepthenableno, SDD just passes on the IOs directly to the hdisk driver. So the difference is, if qdepthenableyes (the default), IOs exceeding the queuedepth will queue at SDD, and if qdepthenableno, then IOs exceed the queuedepth will queue in the hdisks wait queue. In other words, SDD with qdepthenableno and SDDPCM do not queue IOs and instead just pass them to the hdisk drivers. Note that at SDD 1.6, its preferable to use the datapath command to change qdepthenable, rather than using chdev, as then its a dynamic change, e. g. datapath set qdepth disable will set it to no. Some releases of SDD dont include SDD queueing, and some do, and some releases dont show the qdepthenable attribute. Either check the manual for your version of SDD or try the datapath command to see if it supports turning this feature off. If youve used both SDD and SDDPCM, youll remember that with SDD, each LUN has a corresponding vpath and an hdisk for each path to the vpath or LUN. And with SDDPCM, you just have one hdisk per LUN. Thus, with SDD one can submit queuedepth x paths to a LUN, while with SDDPCM, one can only submit queuedepth IOs to the LUN. If you switch from SDD using 4 paths to SDDPCM, then youd want to set the SDDPCM hdisks to 4x that of SDD hdisks for an equivalent effective queue depth. And migrating to SDDPCM is recommended as its more strategic than SDD. Both the hdisk and adapter drivers have an in process and wait queues. Once the queue limit is reached, the IOs wait until an IO completes, freeing up a slot in the service queue. The in process queue is also sometimes referred to as the service queue Its worth mentioning, that many applications will not generate many in flight IOs, especially single threaded applications that dont use asynchronous IO. Applications that use asynchronous IO are likely to generate more in flight IOs. What tools are available to monitor the queues For AIX, one can use iostat (at AIX 5.3 or later) and sar (5.1 or later) to monitor the hdisk driver queues. The iostat - D command generates output such as: hdisk6 xfer: tmact bps tps bread bwrtn 4.7 2.2M 19.0 0.0 2.2M read: rps avgserv minserv maxserv timeouts fails 0.0 0.0 0.0 0.0 0 0 write: wps avgserv minserv maxserv timeouts fails 19.0 38.9 1.1 190.2 0 0 queue: avgtime mintime maxtime avgwqsz avgsqsz sqfull 15.0 0.0 83.7 0.0 0.0 136 Here, the avgwqsz is the average wait queue size, and avgsqsz is the average service queue size. The average time spent in the wait queue is avgtime. The sqfull value has changed from initially being a count of the times weve submitted an IO to a full queue, to now where its the rate of IOs per second submitted to a full queue. The example report shows the prior case (a count of IOs submitted to a full queue), while newer releases typically show decimal fractions indicating a rate. Its nice that iostat - D separates reads and writes, as we would expect the IO service times to be different when we have a disk subsystem with cache. The most useful report for tuning is just running iostat - D which shows statistics since system boot, assuming the system is configured to continuously maintain disk IO history (run lsattr - El sys0. or smitty chgsys to see if the iostat attribute is set to true). And the authors favorite iostat command flags are iostat - RDTl ltintervalgt ltintervalsgt. From the applications point of view, the length of time to do an IO is its service time plus the time it waits in the hdisk wait queue. The sar - d command changed at AIX 5.3, and generates output such as: 16:50:59 device busy avque rws Kbss avwait avserv 16:51:00 hdisk1 0 0.0 0 0 0.0 0.0 hdisk0 0 0.0 0 0 0.0 0.0 The avwait and avserv are the average times spent in the wait queue and service queue respectively. And avserv here would correspond to avgserv in the iostat output. The avque value changed at AIX 5.3, it represents the average number of IOs in the wait queue, and prior to 5.3, it represents the average number of IOs in the service queue. SDDPCM provides the pcmpath query devstats and pcmpath query adaptstats commands to show hdisk and adapter queue statistics. SDD similarly has datapath query devstats and datapath query adaptstats. You can refer to the SDDSDDPCM manual for syntax, options and explanations of all the fields. Heres some devstats output for a single LUN: Device : 0 Total Read Total Write Active Read Active Write Maximum IO: 29007501 3037679 1 0 40 SECTOR: 696124015 110460560 8 0 20480 Transfer Size: lt 512 lt 4k lt 16K lt 64K gt 64K 21499 10987037 18892010 1335598 809036 and heres some adaptstats output: Adapter : 0 Total Read Total Write Active Read Active Write Maximum IO: 439690333 24726251 7 0 258 SECTOR: 109851534 960137182 608 0 108625 Here, were mainly interested in the Maximum field which indicates the maximum number of IOs submitted to the device since system boot. For SDD, the Maximum for devstats will not exceed queuedepth x paths when qdepthenableyes. But Maximum for adaptstats can exceed numcmdelems as it represents the maximum number of IOs submitted to the adapter driver and includes IOs for both the service and wait queues. If, in this case, we have 2 paths and are using the default queuedepth of 20, then the 40 indicates weve filled the queue at least once and increasing queuedepth can help performance. For SDDPCM, if the Maximum value equals the hdisks queuedepth, then the hdisk driver queue was filled during the interval, and increasing queuedepth is usually appropriate. One can similarly monitor adapter IOPS with iostat - at ltintervalgt lt of intervalsgt and for adapter queue information, run iostat - aD. optionally with an interval and number of intervals. For FC adapters, the fcstat command provides information on the adapter queue and resource use, and can tell us if we need to increase its queue sizes. For adapter queues, the fcstat command is used and is discussed below. First, one should not indiscriminately just increase these values. Its possible to overload the disk subsystem or cause problems with device configuration at boot. So the approach of adding up the hdisks queuedepths and using that to determine the numcmdelems isnt necessarily the best approach. Instead, its better to use the maximum number of submitted IOs to each device for tuning. When you increase the queuedepths and number of in flight IOs that are sent to the disk subsystem, the IO service times are likely to increase, but throughput will also increase. If IO service times start approaching the disk timeout value, then youre submitting more IOs than the disk subsystem can handle. If you start seeing IO timeouts and errors in the error log indicating problems completing IOs, then this is the time to look for hardware problems or to make the pipe smaller. A good general rule for tuning queuedepths, is that one can increase queuedepths until IO service times start exceeding 15 ms for small random reads or writes or one isnt filling the queues. Once IO service times start increasing, weve pushed the bottleneck from the AIX disk and adapter queues to the disk subsystem. Two approaches to tuning queue depth are 1) base the queue depths on actual IO requests your application generate or 2) use a test tool to see what the disk subsystem can handle and tune the queues based on what the disk subsystem can handle. The ndisk tool (part of the nstress package available on the internet at www-941.ibmcollaborationwikidisplayWikiPtypenstress ) can be used to stress the disk subsystem to see what it can handle. The authors preference is to tune based on your application IO requirements, especially when the disk is shared with other servers. For tuning, we can categorize the situation into four categories: Were filling up the queues and IOs are waiting in the hdisk or adapter drivers Were not filling up the queues, and IO service times are good Were not filling up the queues, and IO service times are poor Were not filling up the queues, and were sending IOs to the storage faster than it can handle and it loses the IOs We want to tune the queues to be in either situation 2 or 3. If were in situation 3, that indicates a bottleneck beyond the hdisk driver which will typically be in the disk subsystem itself, but could also be in the adapter driver or SAN fabric. Situation 4 is something we do want to avoid. All disks and disk subsystem have limits regarding the number of in-flight IOs they can handle, mainly due to memory limitations to hold the IO request and data. When the storage loses IOs, the IO will eventually time out at the host, recovery code will be used and resubmit the IO, but in the meantime transactions waiting on that IO will be stalled. This isnt a desirable situation, as the CPU ends up doing more work to handle IOs than necessary. If the IO eventually fails, then this can lead to an application crash or worse. So be sure to check your storage documentation to understand its limits. Then after running your application during peak IO periods look at the statistics and tune again. Regarding the qdepthenable parameter for SDD, the default is yes which essentially has SDD handling the IOs beyond queuedepth for the underlying hdisks. Setting it to no results in the hdisk device driver handling them in its wait queue. In other words, with qdepthenableyes, SDD handles the wait queue, otherwise the hdisk device driver handles the wait queue. There are error handling benefits to allowing SDD to handle these IOs, e. g. if using LVM mirroring across two ESSs. With heavy IO loads and a lot of queueing in SDD (when qdepthenableyes) its more efficient to allow the hdisk device drivers to handle relatively shorter wait queues rather than SDD handling a very long wait queue by setting qdepthenableno. In other words, SDDs queue handling is single threaded where each hdisk driver has its own thread. So if error handling is of primary importance (e. g. when LVM mirroring across disk subsystems) then leave qdepthenableyes. Otherwise, setting qdepthenableno more efficiently handles the wait queues when they are long. Note that one should set the qdepthenable parameter via the datapath command as its a dynamic change that way (using chdev is not dynamic for this parameter). If error handling is of concern, then its also advisable, assuming the disk is SAN switch attached, to set the fscsi device attribute fcerrrecov to fastfail rather than the default of delayedfail, and also change the fscsi device dyntrk attribute to yes rather than the default of no. These attributes assume a SAN switch that supports this feature. What are reasonable average IO service times What is good or reasonable is somewhat a factor of the technology of the storage and the storage cache sizes. Assuming no IOs are queued to a disk, a typical read will take somewhere from 0 to 15 ms, or so, depending on how far the actuator has to travel (seek time), how long it takes the disk to rotate to the right sector (rotation time), and how long it takes to read the data (transfer time). Then the data must move from the storage to the host. Typically the time is dominated by seek time rotation time, though for large IOs transfer time also can be significant. Sometimes the data will be in disk subsystem read cache, in which case the IO service time is around 1 ms. Typically for large disk subsystems that arent overloaded, IO service times will average around 5-10 ms. When small random reads start averaging greater than 15 ms, this indicates the storage is getting busy. Writes typically go to write cache (assuming it exists) and then these average typically less than about 2.5 ms. But there are exceptions. If the storage is synchronously mirroring the data to a remote site, writes can take much longer. And if the IO is large (say 64 KB or larger) then the transfer time becomes more significant and the average time is slightly worse. If theres no cache, then writes take about the same as reads. If the IO is large block sequential, then besides the increased transfer time, we expect IOs to queue at the physical disk, and IO service times to be much longer on average. E. G. if an application submits 50 IOs (say 50 64 KB IOs reading a file sequentially) then the first few IOs will have reasonably good IO service times, while the last IO will have had to wait for the other 49 to finish first, and will have a very long IO service time. IOs to SSDs are typically less than 1 ms, and for SSDs in disk subsystems, typically less than 2 ms, and on occasion higher. Tuning the FC adapter numcmdelems The fcstat command is perhaps the easiest tool to look for blocked IOs in the adapters queues, e. g. FIBRE CHANNEL STATISTICS REPORT: fcs0 . FC SCSI Adapter Driver Information No DMA Resource Count: 0 No Adapter Elements Count: 104848 No Command Resource Count: 13915968 . The values for No Adapter Elements Count and No Command Resource Count are the number of times since boot that an IO was temporarily blocked due to an inadequate numcmdelems attribute value. Non-zero values indicate that increasing numcmdelems may help improve IO service times. Of course if the value increments slowly, then the improvement may be very small, while quickly incrementing values means tuning is more likely to have a measurable improvement in performance. Like the hdisk queuedepth attribute, changing the numcmdelems value requires stopping use of the resources or a reboot. Queue depths with VSCSI VIO When using VIO, one configures VSCSI adapters (for each virtual adapter in a VIOS, known as a vhost device, there will be a matching VSCSI adapter in a VIOC). These adapters have a fixed queue depth that varies depending on how many VSCSI LUNs are configured for the adapter. There are 512 command elements of which 2 are used by the adapter, 3 are reserved for each VSCSI LUN for error recovery and the rest are used for IO requests. Thus, with the default queuedepth of 3 for VSCSI LUNs, that allows for up to 85 LUNs to use an adapter: (512 - 2) (3 3) 85 rounding down. So if we need higher queue depths for the devices, then the number of LUNs per adapter is reduced. E. G. if we want to use a queuedepth of 25, that allows 51028 18 LUNs. We can configure multiple VSCSI adapters to handle many LUNs with high queue depths. each requiring additional memory. One may have more than one VSCSI adapter on a VIOC connected to the same VIOS if you need more bandwidth. Also, one should set the queuedepth attribute on the VIOCs hdisk to match that of the mapped hdisks queuedepth on the VIOS. For a formula, the maximum number of LUNs per virtual SCSI adapter (vhost on the VIOS or vscsi on the VIOC) is INT(510(Q3)) where Q is the queuedepth of all the LUNs (assuming they are all the same). Note that to change the queuedepth on an hdisk at the VIOS requires that we unmap the disk from the VIOC and remap it back, or a simpler approach is to change the values in the ODM (e. g. chdev - l hdisk30 - a queuedepth20 - P) then reboot the VIOS. For LV VSCSI hdisks, where multiple VIOC hdisks are created from a single VIOS hdisk, then one may take a dedicated resource, shared resource or an in between approach to the VIOS hdisk queue slots. See the section below entitled Further theoretical thoughts on shared vs. dedicated resources . Queue depths with NPIV VIO When using NPIV, we have virtual FC adapters (vFC) and real FC adapters, and often have multiple vFCs tied to a single real FC adapter. If you increase numcmdelems on the virtual FC (vFC) adapter, then you should also increase the setting on the real FC adapter. You can use the fcstat command for both the virtual adapter as well as the real adapter for tuning purposes. A special note on the FC adapter maxxfersize attribute This attribute for the fscsi device, which controls the maximum IO size the adapter device driver will handle, also controls a memory area used by the adapter for data transfers. When the default value is used (maxxfersize0x100000) the memory area is 16 MB in size. When setting this attribute to any other allowable value (say 0x200000) then the memory area is 128 MB in size. At AIX 6.1 TL2 or later a change was made for virtual FC adapters so the DMA memory area is always 128 MB even with the default maxxfersize. This memory area is a DMA memory area, but it is different than the DMA memory area controlled by the lgtermdma attribute (which is used for IO control). The default value for lgtermdma of 0x800000 is usually adequate. So for heavy IO and especially for large IOs (such as for backups) its recommended to set maxxfersize0x200000. The fcstat command can also be used to examine whether or not increasing numcmdelems or maxxfersize could increase performance fcstat fcs0 . FC SCSI Adapter Driver Information No DMA Resource Count: 0 No Adapter Elements Count: 0 No Command Resource Count: 0 This shows an example of an adapter that has sufficient values for numcmdelems and maxxfersize. Non zero value would indicate a situation in which IOs queued at the adapter due to lack of resources, and increasing numcmdelems and maxxfersize would be appropriate. Note that changing maxxfersize uses memory in the PCI Host Bridge chips attached to the PCI slots. The salesmanual, regarding the dual port 4 Gbps PCI-X FC adapter states that If placed in a PCI-X slot rated as SDR compatible andor has the slot speed of 133 MHz, the AIX value of the maxxfersize must be kept at the default setting of 0x100000 (1 megabyte) when both ports are in use. The architecture of the DMA buffer for these slots does not accommodate larger maxxfersize settings If there are too many FC adapters and too many LUNs attached to the adapter, this will lead to issues configuring the LUNs. Errors will look like: LABEL: DMAERR IDENTIFIER: 00530EA6 DateTime: Mon Mar 3 10:48:09 EST 2008 Sequence Number: 863 Machine Id: 00C3BCB04C00 Node Id: p595back Class: H Type: UNKN Resource Name: PCIDMA Resource Class: NONE Resource Type: NONE Location: Description UNDETERMINED ERROR Probable Causes SYSTEM IO BUS SOFTWARE PROGRAM ADAPTER DEVICE Recommended Actions PERFORM PROBLEM DETERMINATION PROCEDURES Detail Data BUS NUMBER FFFF FFFF 9000 00E4 CHANNEL UNIT ADDRESS 0000 0000 0000 018B ERROR CODE 0000 0000 1000 0003 So if you get these errors, youll need to change the maxxfersize back to the default value. Also note that if you are booting from SAN, if you encounter this error, you wont be able to boot, so be sure to have a back out plan if you plan to change this and are booting from SAN. Further theoretical thoughts on shared vs. dedicated resources The astute reader will have considered the fact that typically we have many hdisk drivers sharing multiple adapters and adapter drivers, thus, the FC queue slots are a shared resource for the hdisk drivers: Thus, its possible to ensure that we never fill the adapter queues, by making SUM(hdisk0 queuedepth, hdisk1 queuedepth. hdiskM queuedepth) lt SUM (fcs0 numcmdelems, fcs1 numcmdelems. fcsN numcmdelems). This assumes that IO are evenly spread across the adapters. And most multi-path code does balance IOs across the adapters (or at least can). Though often, environments have many more hdisks than FC ports, and ensuring we wont fill the adapter drivers can lead to small values for queuedepth, and full queues on the hdisk drivers. So there is the dedicated resource approach, the shared resource approach, and in between dedicated and shared. Taking this simple example where Q represents the queue depth for the device driver: This would be considered a dedicated resource approach, where 10 of the adapter driver queue slots are dedicated to each hdisk driver. Here we know well never submit an IO to a full queue on the adapter driver. This would be considered a shared resource approach where the 10 adapter queue slots could be filled up from a single hdisk driver. And heres an example of something in between: Here, there will always be at least 5 queue slots available in the adapter driver for either hdisk driver. There are pros and cons to each approach. The benefit of the dedicated resource approach is that the resources allocated will always be available but typically there will be fewer resources available to each user of the resource (here the resource were considering is the adapter queue slots, and the users of the resource are the hdisk drivers). The benefit of the shared resource approach is that well have more resources for an individual user of the resource when it needs it and it will be able to get greater thruput than in the dedicated resource approach. The author generally prefers a shared resource approach, as generally provides the best thruput and price performance. Note that this situation of shared resources occurs in several possible ways beyond hdisk drivers using adapter drivers. It is also involved when: Several LV VSCSI hdisks for a single hdisk on a VIOS Several vFC adapters using a single real FC adapter Several LPARs using the same disk subsystem

No comments:

Post a Comment