Wednesday 5 July 2017

Moving Average Queue


2.4 Antrian Prioritas Banyak aplikasi mengharuskan kami memproses item yang memiliki kunci secara berurutan, namun tidak harus dalam urutan penuh dan tidak harus sekaligus sekaligus. Seringkali, kita mengumpulkan satu set item, lalu mengolah yang satu dengan kunci terbesar, lalu mungkin mengumpulkan lebih banyak barang, lalu mengolah yang satu dengan kunci terbesar saat ini, dan sebagainya. Tipe data yang tepat di lingkungan seperti itu mendukung dua operasi: keluarkan maksimum dan sisipkan. Tipe data semacam itu disebut priority queue. Antrian prioritas dicirikan dengan menghapus operasi maksimum dan penyisipan. Dengan konvensi, kita akan membandingkan kunci hanya dengan metode yang kurang (), seperti yang telah kita lakukan untuk menyortir. Jadi, jika catatan bisa memiliki kunci duplikat, maksimal berarti ada catatan dengan nilai kunci terbesar. Untuk melengkapi API, kita juga perlu menambahkan konstruktor dan tes jika operasi kosong. Untuk fleksibilitas, kami menggunakan implementasi generik dengan tipe generik Key yang mengimplementasikan Comparable. Program TopM. java adalah client antrian prioritas yang mengambil argumen command-line M. Membaca transaksi dari input standar, dan mencetak transaksi M terbesar. Implementasi dasar. Struktur data dasar yang kami bahas di Bagian 1.3 memberi kami empat titik awal untuk menerapkan antrian prioritas. Array representasi (unordered). Mungkin implementasi antrian prioritas paling sederhana didasarkan pada kode kita untuk tumpukan pushdown. Kode untuk memasukkan dalam antrian prioritas sama dengan push di stack. Untuk menerapkan menghapus maksimal. Kita dapat menambahkan kode seperti lingkaran dalam dari jenis pilihan untuk menukar item maksimum dengan item di bagian akhir dan kemudian menghapus yang itu, seperti yang kita lakukan dengan pop () untuk tumpukan. Program UnorderedArrayMaxPQ. java menerapkan antrian prioritas dengan menggunakan pendekatan ini. Array representasi (dipesan). Pendekatan lain adalah menambahkan kode untuk insert untuk memindahkan entri yang lebih besar satu posisi ke kanan, sehingga menjaga entri dalam array secara berurutan (seperti pada sort penyisipan). Dengan demikian item terbesar selalu di akhir, dan kode untuk menghapus maksimal dalam antrian prioritas sama dengan pop di stack. Program OrderedArrayMaxPQ. java menerapkan antrian prioritas menggunakan pendekatan ini. Linked-list representations (unordered dan reverse-ordered). Demikian pula, kita bisa mulai dengan kode daftar-linked untuk tumpukan pushdown, baik memodifikasi kode pop () untuk menemukan dan mengembalikan maksimum atau kode untuk push () untuk menyimpan item dalam urutan terbalik dan kode pop () ke Batalkan tautan dan kembalikan item (maksimum) pertama pada daftar. Semua implementasi elementer yang baru saja dibahas memiliki properti baik insert atau remove operasi maksimum mengambil waktu linier dalam kasus terburuk. Menemukan sebuah implementasi di mana kedua operasi dijamin cepat adalah tugas yang lebih menarik, dan ini adalah subjek utama dari bagian ini. Heap definisi. Tumpukan biner adalah struktur data yang secara efisien dapat mendukung operasi antrian prioritas dasar. Dalam tumpukan biner, item disimpan dalam array sehingga setiap tombol dijamin lebih besar dari (atau sama dengan) tombol pada dua posisi spesifik lainnya. Pada gilirannya, masing-masing kunci itu harus lebih besar dari dua kunci lagi, dan sebagainya. Pemesanan ini mudah untuk melihat apakah kita melihat tombol sebagai berada dalam struktur pohon biner dengan tepi dari setiap tombol ke dua kunci yang diketahui lebih kecil. Definisi. Sebuah pohon biner ditumpuk-tumpukan jika kunci di setiap simpul lebih besar dari (atau sama dengan) kunci di simpul dua anak (jika ada). Dalil. Kunci terbesar dalam tumpukan pohon biner yang ditumpuk ditemukan di root. Kita bisa memaksakan pembatasan pemesanan tumpukan pada pohon biner manapun. Akan sangat nyaman jika menggunakan pohon biner lengkap seperti di bawah ini. Kami mewakili pohon biner lengkap secara berurutan dalam sebuah array dengan meletakkan node dengan tingkat ketertiban. Dengan akar pada posisi 1, anak-anaknya di posisi 2 dan 3, anak-anak mereka di posisi 4, 5, 6 dan 7, dan seterusnya. Definisi. Tumpukan biner adalah sekumpulan simpul dengan kunci yang disusun dalam susunan biner biner lengkap, yang terwakili dalam urutan tingkat dalam sebuah array (tidak menggunakan entri pertama). Dalam tumpukan, induk dari node pada posisi k berada pada posisi k2 dan, sebaliknya, kedua anak simpul pada posisi k berada pada posisi 2k dan 2k 1. Kita dapat melakukan perjalanan naik turun dengan melakukan aritmatika sederhana pada indeks array. : Untuk naik pohon dari ak kita set k ke k2 untuk turun pohon kita set k ke 2k atau 2k1. Algoritma pada tumpukan. Kami mewakili tumpukan ukuran N dalam array pribadi dengan panjang pq N1, dengan pq0 tidak digunakan dan tumpukan di pq1 sampai pqN. Kami mengakses kunci hanya melalui fungsi pembantu pribadi kurang () dan exch (). Operasi timbunan yang kami anggap bekerja dengan terlebih dahulu membuat modifikasi sederhana yang bisa melanggar kondisi heap, lalu berjalan melalui heap, memodifikasi timbunan seperti yang dipersyaratkan untuk memastikan bahwa kondisi heap sudah memuaskan dimana-mana. Kami mengacu pada proses ini sebagai reheapifikasi. Atau mengembalikan heap order. Rebung kembali ke bawah (berenang). Jika urutan tumpukan dilanggar karena kunci nodus menjadi lebih besar dari pada kunci induk orang tua, maka kita dapat membuat kemajuan dalam memperbaiki pelanggaran dengan menukar simpul dengan orang tuanya. Setelah pertukaran, simpul lebih besar dari kedua anaknya (satu adalah induk tua, dan yang lainnya lebih kecil dari orang tua karena anak adalah anak dari simpul itu) namun simpulnya masih lebih besar dari induknya. Kita bisa memperbaiki pelanggaran itu dengan cara yang sama, dan seterusnya, menaikkan tumpukan sampai kita mencapai simpul dengan kunci lebih besar, atau akarnya. Top-down heapify (wastafel). Jika urutan tumpukan dilanggar karena kunci nodus menjadi lebih kecil dari satu atau kedua kunci anak-anak itu, maka kita dapat membuat kemajuan dalam memperbaiki pelanggaran dengan menukar nodus dengan yang lebih besar dari kedua anaknya. Peralihan ini dapat menyebabkan pelanggaran pada anak kami memperbaiki pelanggaran tersebut dengan cara yang sama, dan seterusnya, bergerak menuruni tumpukan sampai kami mencapai simpul dengan kedua anak lebih kecil, atau bagian bawahnya. Heap berbasis priority queue. Operasi wastafel () dan berenang () ini memberikan dasar untuk penerapan API antrian prioritas secara efisien, seperti yang ditunjukkan di bawah dan diimplementasikan di MaxPQ. java dan MinPQ. java. Memasukkan. Kami menambahkan item baru di akhir array, menambah ukuran timbunan, lalu berenang naik melalui tumpukan dengan item itu untuk mengembalikan kondisi tumpukan. Hapus maksimal. Kami mengambil barang terbesar dari atas, meletakkan barang dari ujung tumpukan di bagian atas, mengurangi ukuran timbunan, dan kemudian menenggelamkan diri melalui tumpukan dengan barang itu untuk mengembalikan kondisi tumpukan. Dalil. Dalam antrian prioritas item N, algoritma tumpukan tidak memerlukan lebih dari 1 lg N untuk menyisipkan dan tidak lebih dari 2 lg N untuk menghapus maksimum. Pertimbangan praktis. Kami menyimpulkan penelitian kami tentang antrian prioritas API dengan beberapa pertimbangan praktis. Tumpukan multiway Tidaklah sulit untuk mengubah kode kita untuk membangun tumpukan berdasarkan representasi array dari pohon terner atau rerata yang terapung. Ada tradeoff antara biaya yang lebih rendah dari penurunan ketinggian pohon dan biaya yang lebih tinggi untuk menemukan anak-anak tiga atau d terbesar di setiap simpul. Array mengubah ukuran Kita bisa menambahkan konstruktor tanpa argumen, kode untuk penggandaan array di insert (). Dan kode untuk membuat potongan separuh dalam delMax (). Seperti yang kita lakukan untuk tumpukan di Bagian 1.3. Batas waktu logaritmik diamortisasi bila ukuran antrian prioritas sewenang-wenang dan susunannya diubah ukurannya. Ketidakmampuan tombol. Antrian prioritas berisi objek yang dibuat oleh klien namun mengasumsikan bahwa kode klien tidak mengubah kunci (yang mungkin membuat inversi tumpukan). Indeks prioritas antrian Dalam banyak aplikasi, masuk akal jika mengizinkan klien merujuk ke item yang sudah ada dalam antrian prioritas. Salah satu cara mudah untuk melakukannya adalah mengaitkan indeks bilangan bulat unik dengan setiap item. IndexMinPQ. java adalah implementasi berbasis tumpukan API IndexMaxPQ. java ini serupa namun untuk antrian prioritas dengan orientasi maksimal. Multiway. java adalah klien yang menggabungkan beberapa input input menjadi satu output stream yang diurutkan. Kita bisa menggunakan antrian prioritas untuk mengembangkan metode sorting. Kami memasukkan semua kunci yang akan diurutkan ke dalam antrian prioritas berorientasi minimum, kemudian berulang kali menggunakan menghapus minimum untuk menghapus semuanya secara berurutan. Saat menggunakan timbunan untuk antrian prioritas, kita mendapatkan heapsort. Berfokus pada tugas menyortir, kita meninggalkan gagasan untuk menyembunyikan representasi tumpukan antrian prioritas dan menggunakan swim () dan sink () secara langsung. Dengan melakukan hal tersebut, kita bisa mengurutkan sebuah array tanpa memerlukan ruang ekstra, dengan mempertahankan tumpukan dalam susunan yang akan diurutkan. Heapsort terbagi menjadi dua tahap: konstruksi tumpukan. Dimana kita mengatur ulang susunan aslinya menjadi tumpukan, dan pengaturannya. Di mana kita menarik barang keluar dari tumpukan dalam penurunan untuk membangun hasil yang diurutkan. Konstruksi tumpukan. Kita dapat menyelesaikan tugas ini dalam waktu yang sebanding dengan N lg N, dengan melanjutkan dari kiri ke kanan melalui array, menggunakan berenang () untuk memastikan bahwa entri di sebelah kiri penunjuk pemindai membentuk pohon lengkap yang direkomendasikan tumpukan, seperti berturut-turut Sisipan antrian prioritas Metode cerdas yang jauh lebih efisien adalah melanjutkan dari kanan ke kiri, menggunakan wastafel () untuk membuat keropos saat kita pergi. Setiap posisi dalam array adalah akar dari wastafel subheap kecil () bekerja atau semacam itu, juga. Jika dua anak dari sebuah simpul bertumpuk, maka memanggil wastafel () pada simpul tersebut membuat subtree berakar di sana sebuah tumpukan. Sortdown. Sebagian besar pekerjaan selama heapsort dilakukan selama fase kedua, di mana kita menghapus barang-barang tersisa terbesar dari tumpukan dan memasukkannya ke dalam posisi array dikosongkan saat timbunan menyusut. Heap. java adalah implementasi penuh heapsort. Berikut adalah jejak isi array setelah masing-masing wastafel. Dalil. Konstruksi timbunan wastafel adalah waktu linier. Dalil. Heapsort users kurang dari 2n lg n bandingkan dan tukar untuk mengurutkan n item. Sebagian besar barang dimasukkan kembali ke tumpukan saat pengekangan pergi sampai ke bawah. Dengan demikian kita dapat menghemat waktu dengan menghindari pemeriksaan apakah item tersebut telah mencapai posisinya, hanya dengan mempromosikan yang lebih besar dari kedua anak tersebut sampai bagian bawahnya tercapai, kemudian mengembalikan tumpukan ke posisi yang tepat. Ide ini mengurangi jumlah perbandingan dengan faktor 2 dengan mengorbankan pembukuan tambahan. Misalkan urutan (di mana huruf berarti insert dan tanda asterisk menghapus maksimum) diterapkan pada antrian prioritas yang awalnya kosong. Berikan urutan nilai yang dikembalikan dengan menghapus operasi maksimum. Larutan. R R P O T Y I I U Q E U (E tertinggal di PQ) Mengkritik gagasan berikut: untuk menerapkan menemukan yang terbaik dalam waktu konstan, mengapa tidak mencatat nilai maksimum yang dimasukkan sejauh ini, kemudian mengembalikan nilai tersebut untuk menemukan yang maksimal. Larutan. Perlu mengupdate nilai maksimal dari awal setelah operasi remove-the-maximum. Berikan prioritas implementasi antrian yang mendukung insert dan remove secara maksimal. Satu untuk masing-masing struktur data dasar berikut: array tak berurutan, susunan pesanan, daftar tertaut yang tidak berurutan, dan daftar tertaut yang dipesan. Berikan tabel batas terburuk untuk setiap operasi untuk masing-masing dari keempat implementasi Anda dari latihan sebelumnya. Solusi parsial OrderedArrayMaxPQ. java dan UnorderedArrayMaxPQ. java Merupakan array yang diurutkan dalam urutan menurun sebagai timbunan berorientasi maks. Menjawab. Iya nih. Misalkan aplikasi Anda akan memiliki sejumlah besar operasi insert, namun hanya sedikit yang menghapus operasi maksimum. Implementasi antrean prioritas mana yang menurut Anda paling efektif: tumpukan, array tidak berurutan, deretan perintah Jawaban. Array tak berurutan Sisipkan adalah waktu konstan. Misalkan aplikasi Anda akan memiliki sejumlah besar pencarian operasi maksimum, namun sejumlah kecil memasukkan dan menghapus operasi maksimum. Implementasi antrian prioritas yang menurut Anda paling efektif: tumpukan, array tidak berurutan, deretan perintah Jawaban. Array yang dipesan Temukan maksimum adalah waktu konstan. Berapakah jumlah minimum barang yang harus dipertukarkan saat mengeluarkan operasi maksimum dalam tumpukan ukuran N tanpa tombol duplikat Beri tumpukan ukuran 15 yang minimumnya tercapai. Jawab pertanyaan yang sama untuk dua dan tiga kali berturut-turut menghapus operasi maksimum. Jawaban parsial (A) 2. Rancang algoritma sertifikasi linier untuk memeriksa apakah sebuah array pq adalah timah min-oriented. Larutan. Lihat metode isMinHeap () di MinPQ. java. Buktikan bahwa konstruksi tumpukan berbasis wastafel menggunakan paling banyak 2 n membandingkan dan paling banyak pertukaran n. Larutan. Sudah cukup untuk membuktikan bahwa konstruksi tumpukan berbasis wastafel menggunakan lebih sedikit daripada n pertukaran karena jumlah perbandingan paling banyak dua kali jumlah pertukaran. Untuk kesederhanaan, asumsikan bahwa tumpukan biner itu sempurna (yaitu pohon biner di mana setiap tingkat selesai diisi) dan memiliki tinggi h. Kami mendefinisikan tinggi simpul di pohon menjadi puncak subtree yang berakar pada simpul itu. Kunci pada ketinggian k dapat ditukar dengan paling banyak k kuncinya di bawahnya saat tenggelam. Karena ada 2 h minus k node pada ketinggian k. Jumlah total pertukaran paling banyak: Kesetaraan pertama adalah untuk jumlah yang tidak standar, namun sangat mudah untuk memverifikasi bahwa formula tersebut bertahan melalui induksi matematis. Persamaan kedua berlaku karena pohon biner yang sempurna dengan tinggi h memiliki 2 h 1 minus 1 node. Membuktikan bahwa hasilnya berlaku saat pohon biner tidak sempurna membutuhkan perawatan yang sedikit lebih. Anda dapat melakukannya dengan menggunakan fakta bahwa jumlah nodus pada tinggi k pada tumpukan biner pada n node paling banyak terjadi (n 2 k 1). Solusi alternatif Sekali lagi, untuk kesederhanaan, asumsikan bahwa tumpukan biner itu sempurna (yaitu pohon biner di mana setiap tingkat selesai diisi). Kami mendefinisikan tinggi simpul di pohon menjadi puncak subtree yang berakar pada simpul itu. Pertama, amati bahwa tumpukan biner pada n node memiliki n minus 1 link (karena setiap link adalah induk dari satu node dan setiap node memiliki parent link kecuali root). Menenggelamkan simpul dengan tinggi k membutuhkan paling banyak pertukaran k. Kami akan menagih k link ke setiap node pada ketinggian k. Tapi belum tentu link di jalan yang ditempuh saat menenggelamkan simpul. Sebagai gantinya, kita mengisi node k link di sepanjang jalan dari simpul yang menuju ke kiri kanan-kanan-kanan-. Sebagai contoh, pada diagram di bawah, root node diisi dengan 4 link merah node biru tersebut diisi dengan 3 link biru dan sebagainya. Perhatikan bahwa tidak ada link yang dibebankan ke lebih dari satu node. (Sebenarnya, ada dua tautan yang tidak dibebankan ke simpul manapun: tautan kanan dari akar dan tautan induk dari simpul kanan paling bawah). Jadi, jumlah total pertukaran paling banyak n. Karena paling banyak 2 membandingkan per pertukaran, jumlah perbandingan paling banyak 2 n. Masalah Kreatif Teori bilangan komputasional. Tulis sebuah program CubeSum. java yang mencetak semua bilangan bulat dari bentuk 3 b 3 dimana a dan b adalah bilangan bulat antara 0 dan N dalam urutan yang diurutkan, tanpa menggunakan ruang yang berlebihan. Artinya, alih-alih menghitung array dari jumlah N 2 dan memilahnya, buatlah antrian prioritas berorientasi minimum, yang pada awalnya mengandung (0 3. 0, 0), (1 3. 1, 0), (2 3. 2 , 0). (N 3. N, 0). Kemudian, sementara antrian prioritas tidak kosong, hapus item terkecil (i 3 j 3. i, j), cetaklah, dan kemudian, jika j 3 (j1) 3. i, j1). Gunakan program ini untuk menemukan semua bilangan bulat yang berbeda a, b, c, dan d antara 0 dan 106 sedemikian rupa sehingga a 3 b 3 c 3 d 3. mis. 1729 93 103 13 123. Temukan minimum. Tambahkan metode min () ke MaxPQ. java. Implementasi Anda harus menggunakan waktu konstan dan ruang ekstra konstan. Solusi. Tambahkan variabel contoh tambahan yang menunjuk ke item minimum. Perbarui setelah setiap panggilan masuk (). Reset ke null jika antrian prioritas menjadi kosong. Pencarian rata-rata. Rancang tipe data yang mendukung sisipan dalam waktu logaritmik, cari median dalam waktu konstan, dan lepaskan median dalam waktu logaritmik. Solusi. Jaga kunci median di v gunakan tumpukan kunci yang berorientasi maksimal untuk kunci kurang dari tombol v gunakan tumpukan berorientasi min untuk tombol yang lebih besar dari tombol v. Untuk memasukkan, tambahkan kunci baru ke tumpukan yang sesuai, ganti v dengan Kunci yang diambil dari tumpukan itu Batas bawah. Buktikan bahwa tidak mungkin untuk mengembangkan implementasi API MinPQ sehingga keduanya memasukkan dan menghapus jaminan minimum untuk menggunakan N log log N compare. Larutan. Ini akan menghasilkan algoritma penyortiran N log-based N log (masukkan item N, kemudian berulang kali menghapus minimum), yang melanggar proposisi Section 2.3. Prioritas indeks antrian implementasi. Terapkan IndexMaxPQ. java dengan memodifikasi MaxPQ. java sebagai berikut: Ubah pq untuk menyimpan indeks, tambahkan tombol array untuk menahan nilai kunci, dan tambahkan qp array yang merupakan kebalikan dari pq mdash qpi memberi posisi i pada pq ( Indeks j sehingga pqj adalah i). Kemudian ubah kode untuk mempertahankan struktur data ini. Gunakan konvensi bahwa qpi adalah -1 jika saya tidak berada dalam antrian, dan sertakan sebuah metode yang berisi () yang menguji kondisi ini. Anda perlu memodifikasi metode penolong exch () dan kurang () tapi tidak sink () atau berenang (). Latihan Web Kasus terbaik, rata-rata, dan terburuk heapsort. Apa kasus terbaik, kasus rata-rata, dan jumlah kasus terburuk untuk membandingkan serangkaian solusi N panjang. Jika kita mengizinkan duplikat, kasus terbaik adalah waktu linier (kunci sama N) jika kita melarang duplikat, kasus terbaiknya adalah N lg N dibandingkan (tapi masukan kasus terbaik tidak penting). Rata-rata dan jumlah kasus terburuk dari perbandingan adalah 2 N lg N dibandingkan. Lihat Analisis Heapsort untuk rinciannya. Kasus terbaik dan terburuk heapify. Berapa jumlah paling sedikit dan paling banyak perbandingan yang dibutuhkan untuk mengumpulkan serangkaian N item Solution. Heapifying array item N dalam urutan menurun memerlukan 0 pertukaran dan membandingkan N - 1. Heapating array item N dalam urutan menaik membutuhkan pertukaran N dan membandingkan 2N. Nomor taksi Tentukan bilangan bulat terkecil yang dapat dinyatakan sebagai jumlah batu bulat dalam dua cara yang berbeda (1,729), tiga cara yang berbeda (87,539,319), empat cara berbeda (6,963, 472,309,248), lima cara berbeda (48,988,659,276,962,496), dan enam cara yang berbeda (24.153.319.581.254.312.065.344 ). Bilangan bulat tersebut diberi nomor Taxicab setelah cerita Ramanujan yang terkenal. Bilangan bulat terkecil yang dapat dinyatakan sebagai jumlah kubus bilangan bulat dalam tujuh cara yang berbeda saat ini tidak diketahui. Tuliskan sebuah program Taxicab. java yang berbunyi dalam parameter baris perintah N dan mencetak semua solusi trivial dari 3 b 3 c 3 d 3. sedemikian rupa sehingga a, b, c, dan d, kurang dari atau sama dengan N. Komputasi Nomor teori Temukan semua solusi untuk persamaan 2b 2 3c3 4d 4 dimana a, b, c, dan d kurang dari 100.000. Petunjuk Gunakan satu tumpukan min dan satu tumpukan maks. Penanganan interupsi Saat memprogram sistem real-time yang dapat terganggu (mis. Dengan klik mouse atau koneksi nirkabel), Anda perlu segera segera menyela, sebelum melanjutkan aktivitas saat ini. Jika interupsi harus ditangani dengan urutan yang sama, antrian FIFO adalah struktur data yang sesuai. Namun, jika berbeda interrupts memiliki prioritas yang berbeda (misalnya), maka kita perlu antrian prioritas. Simulasi jaringan antrian. Antrian MM1 untuk antrian paralel ganda, dll. Sulit untuk menganalisis jaringan antrian yang kompleks secara matematis. Sebaiknya gunakan simulasi untuk merencanakan distribusi waktu tunggu, dll. Perlu antrian prioritas untuk menentukan event mana yang akan di proses selanjutnya. Distribusi Zipf Gunakan hasil latihan sebelumnya untuk sampel dari distribusi Zipfian dengan parameter s dan N. Distribusi dapat mengambil nilai integer dari 1 sampai N, dan mengambil nilai k dengan probabilitas 1ks sum (i 1 sampai N) 1is . Contoh: kata dalam Shakespeares bermain Hamlet dengan s kira-kira sama dengan 1. Random process. Mulailah dengan N sampah, masing-masing terdiri satu bola. Pilih salah satu bola N secara acak dan pindahkan bola ke tempat sampah secara acak sehingga probabilitas bola diletakkan di tempat sampah dengan bola m adalah mN. Apa distribusi bola yang dihasilkan setelah banyak iterasi Gunakan metode sampling acak yang dijelaskan di atas untuk membuat simulasi menjadi efisien. Tetangga terdekat Mengingat vektor N x 1. X 2. X N dari panjang M dan vektor x lainnya dengan panjang yang sama, temukan 20 vektor yang paling dekat dengan x. Lingkaran digambar pada selembar kertas grafik. Tulis sebuah program untuk menemukan radius lingkaran, berpusat pada titik asal, yang menyentuh 32 titik dengan koordinat x dan y bilangan bulat. Petunjuk: cari angka daripada yang bisa dinyatakan sebagai jumlah dua kotak dengan beberapa cara berbeda. Jawaban: ada dua Pythagoras tiga kali lipat dengan hipotensi 25: 152 202 252, 72 242 252 yang menghasilkan 20 titik kisi tersebut di sana 22 buah Pythagoras berbeda tiga kali lipat dengan hipotetis 5,525 sehingga menghasilkan 180 titik kisi. 27.625 adalah radius terkecil yang menyentuh lebih dari 64. 154.136.450 memiliki 35 Pythagoras tiga kali lipat. Kekuatan sempurna Tuliskan program PerfectPower. java untuk mencetak semua kekuatan sempurna yang dapat direpresentasikan sebagai bilangan bulat panjang 64 bit: 4, 8, 9, 16, 25, 27. Kekuatan yang sempurna adalah angka yang dapat ditulis sebagai bilangan bulat untuk bilangan bulat Dan b ge 2. Penambahan floating point. Tambahkan nomor floating point N, hindari kesalahan roundoff. Hapus yang terkecil dua: tambahkan dua satu sama lain, dan masukkan kembali. Pertama-cocok untuk kemasan sampah. 1710 OPT 2, 119 OPT 4 (menurun). Gunakan pohon turnamen max dimana pemain adalah N bins dan nilai kapasitas yang tersedia. Tumpuk dengan minmax. Rancang tipe data yang mendukung push, pop, size, min, dan max (di mana min dan max adalah item minimum dan maksimum pada stack). Semua operasi harus mengambil waktu konstan dalam kasus terburuk. Petunjuk: Mengaitkan dengan setiap tumpukan entri item minimum dan maksimum saat ini di stack. Antrian dengan minmax Rancang tipe data yang mendukung enqueue, dequeue, ukuran, min, dan max (di mana min dan max adalah item minimum dan maksimum pada antrian). Semua operasi harus mengambil waktu diamortisasi konstan. Petunjuk: lakukan latihan sebelumnya dan simulasikan antrian dengan dua tumpukan. 2i 5j. Cetak nomor dari bentuk 2i 5j dalam rangka meningkatkan pesanan. Tumpahan min-max. Rancang struktur data yang mendukung min dan max dalam waktu konstan, masukkan, hapus min, dan hapus max dalam waktu logaritmik dengan meletakkan item dalam satu array ukuran N dengan properti berikut: Array mewakili pohon biner yang lengkap. Kunci pada sebuah simpul pada tingkat genap kurang dari (atau sama dengan) tombol pada subtreenya kunci pada sebuah simpul pada tingkat ganjil lebih besar dari (atau sama dengan) tombol pada subpohonnya. Perhatikan bahwa nilai maksimal disimpan di root dan nilai minimum disimpan di salah satu akar anak. Min-Max Heaps dan Generalized Priority Queues Rentang kueri minimum. Dengan urutan item N, kueri minimum dari indeks i sampai j adalah indeks dari item minimum antara i dan j. Rancang struktur data yang menyusun urutan item N dalam waktu linier untuk mendukung kueri minimum dalam waktu logaritmik. Buktikan bahwa pohon biner lengkap dengan nodus N memiliki simpul daun langit-langit (N2) yang benar (nodus tanpa anak-anak). Antrian prioritas berorientasi Max dengan min. Berapakah tatanan waktu berjalan untuk menemukan kunci minimum dalam tumpukan biner berorientasikan maksimal. Solusi. Linearmdash kunci minimum bisa berada di salah satu nodus daun langit-langit (N2). Antrian prioritas berorientasi Max dengan min. Rancang tipe data yang mendukung insert dan remove-the-maximum pada waktu logaritmik bersamaan dengan kedua max min dalam waktu konstan. Larutan. Buat tumpukan biner berorientasi-maks dan juga simpan kunci minimum yang dimasukkan sejauh ini (yang tidak akan pernah meningkat kecuali tumpukan ini menjadi kosong). Kth item terbesar lebih besar dari x. Dengan tumpukan biner berorientasi maksimum, rancang algoritma untuk menentukan apakah item terbesar kth lebih besar dari atau sama dengan x. Algoritma Anda harus berjalan dalam waktu yang sebanding dengan k. Solusi. Jika kunci di simpul lebih besar dari atau sama dengan x, rekursif cari subtree kiri dan subtree kanan. Berhenti bila jumlah simpul yang dieksplorasi sama dengan k (jawabannya adalah iya) atau tidak ada lagi simpul untuk dijelajahi (tidak). Kth item terkecil di tumpukan biner min-oriented. Rancang algoritma k log k untuk menemukan item kth terkecil dalam tumpukan biner min-oriented yang berisi item N. Larutan. Bangun timbunan min-oriented baru H. Kami tidak akan memodifikasi H. Masukkan akar H ke H bersamaan dengan indeks heapnya 1. Sekarang, berulang kali hapus item minimum x di H dan masukkan ke H kedua anak x dari H Item kth yang dihapus dari H adalah item terkecil kth di H. Randomized queue. Terapkan RandomQueue sehingga setiap operasi dijamin paling banyak mencatat waktu logaritmik. Petunjuk Tidak bisa membeli array dua kali lipat. Tidak ada cara mudah dengan linked list untuk mencari elemen acak dalam O (1) waktu. Sebagai gantinya, gunakan pohon biner lengkap dengan tautan eksplisit. Antrian FIFO dengan random deletion. Menerapkan tipe data yang mendukung operasi berikut: masukkan item. Hapus item yang baru saja ditambahkan. Dan hapus item acak. Setiap operasi harus mengambil (paling banyak) waktu logaritmik dalam kasus terburuk. Solusi. Gunakan pohon biner lengkap dengan link eksplisit menetapkan prioritas integer panjang i ke item ke-i ditambahkan ke struktur data. Top k jumlah dari dua array diurutkan. Dengan dua array berurutan a dan b, masing-masing panjang N, temukan jumlah k terbesar dari bentuk ai bj. Petunjuk Dengan menggunakan antrian prioritas (mirip dengan masalah pajak), Anda dapat mencapai algoritma O (k log N). Anehnya, dimungkinkan untuk melakukannya dalam waktu O (k) tapi algoritmanya rumit. Analisis empiris konstruksi tumpukan. Secara empiris membandingkan konstruksi tumpukan bottom-up linier versus konstruksi tumpukan top-down nano linear. Pastikan untuk membandingkannya dengan sejumlah nilai N. LaMarca dan Ladner melaporkan bahwa karena lokasi cache, algoritma naif dapat berjalan lebih baik dalam praktik daripada pendekatan yang lebih cerdas untuk nilai N yang besar (bila tumpukan tidak sesuai lagi dengan Cache) meskipun yang terakhir melakukan perbandingan dan pertukaran yang jauh lebih sedikit. Analisis empiris tumpukan multi jalan. Secara empiris membandingkan kinerja tumpukan 2 - 4- dan 8-way. LaMarca dan Ladner menyarankan beberapa pengoptimalan, dengan mempertimbangkan efek caching. Analisis empiris heapsort. Secara empiris membandingkan kinerja hembusan 2 - 4 dan 8-way. LaMarca dan Ladner menyarankan beberapa pengoptimalan, dengan mempertimbangkan efek caching. Data mereka menunjukkan bahwa timbin 8-bit yang dioptimalkan (dan memori-disetel) bisa dua kali lebih cepat dari heapsort klasik. Heapify dengan insersi. Misalkan Anda menggembung tumpukan biner pada kunci N dengan berulang kali memasukkan kunci berikutnya ke tumpukan biner. Tunjukkan bahwa jumlah total perbandingan paling banyak adalah Jawaban. Jumlah perbandingan paling banyak lg 1 lg 2. Lg N lg (N) N lg N. Heapify lower bound. (Gonnet and Munro) Tunjukkan bahwa setiap algoritma berbasis perbandingan untuk membangun tumpukan biner pada kunci N memerlukan setidaknya 1.3644 N dalam kasus terburuk. Jawaban. Gunakan argumen teoritis informasi, ala sorting lower bound. Ada N kemungkinan tumpukan (permutasi bilangan bulat N) pada tombol N yang berbeda, namun ada banyak tumpukan yang sesuai dengan urutan yang sama. Sebagai contoh, ada dua tumpukan (taksi dan cba) yang sesuai dengan 3 elemen aCisco IOS Quality of Service Solutions Configuration Guide, Release 12.2 Tinjauan Penghindaran Kemacetan Teknik penghindaran kemacetan memonitor beban lalu lintas jaringan dalam upaya mengantisipasi dan menghindari kemacetan pada jaringan umum. Kemacetan Penghindaran kemacetan dicapai melalui packet dropping. Diantara mekanisme penghindaran kongesti yang umum digunakan adalah Random Early Detection (RED), yang optimal untuk jaringan transit berkecepatan tinggi. Cisco IOS QoS menyertakan implementasi RED yang, jika dikonfigurasi, dikendalikan saat router menjatuhkan paket. Jika Anda tidak mengkonfigurasi Weighted Random Early Detection (WRED), router menggunakan mekanisme drop packet default cruder yang disebut drop ekor. Untuk penjelasan tentang kemacetan jaringan, lihat bab quotQuality of Service Overview. quot Bab ini memberikan penjelasan singkat tentang jenis mekanisme penghindaran kemacetan yang disediakan oleh fitur Cisco IOS QoS. Ini membahas fitur berikut: Tail drop. Ini adalah perilaku menghindari kemacetan default saat WRED tidak dikonfigurasi. WRED. WRED dan distributed WRED (DWRED) yang keduanya merupakan implementasi Cisco dari REDcombine kemampuan algoritma RED dengan fitur IP Precedence. Pada bagian WRED, fitur terkait berikut dibahas: Flow-based WRED. Arus berbasis WRED meluas WRED untuk memberikan keadilan yang lebih besar pada semua arus pada antarmuka sehubungan dengan bagaimana paket dijatuhkan. DiffServ Compliant WRED. DiffServ Compliant WRED meluas WRED untuk mendukung Differentiated Services (DiffServ) dan Assured Forwarding (AF) Per Hop Behavior (PHB). Fitur ini memungkinkan pelanggan menerapkan AF PHB dengan mewarnai paket sesuai dengan nilai kode layanan terdiskripsikan (DSCP) dan kemudian menetapkan probabilitas drop preferensial ke paket tersebut. Untuk informasi tentang cara mengkonfigurasi WRED, DWRED, flow-based WRED, dan DiffServ Compliant WRED, lihat bab quotConfiguring Weighted Random Early Detectionquot dalam buku ini. Tail drop memperlakukan semua lalu lintas secara merata dan tidak membedakan antara kelas layanan. Antrian mengisi selama periode kemacetan. Bila antrian output penuh dan drop ekor berlaku, paket dijatuhkan sampai kemacetan dieliminasi dan antrian tidak lagi penuh. Deteksi Dini Teracak Random Bagian ini memberikan pengantar singkat tentang konsep RED dan alamat WRED, implementasi Cisco RED untuk platform Cisco IOS standar. WRED menghindari masalah globalisasi yang terjadi saat drop ekor digunakan sebagai mekanisme penghindaran kemacetan di router. Sinkronisasi global terjadi karena gelombang kemacetan hanya harus diikuti oleh palung dimana link transmisi tidak dimanfaatkan sepenuhnya. Sinkronisasi global host TCP, misalnya, dapat terjadi karena paket dijatuhkan sekaligus. Sinkronisasi global bermanifestasi ketika beberapa host TCP mengurangi tingkat transmisi mereka sebagai respons terhadap penurunan paket, kemudian meningkatkan tingkat transmisi sekali lagi ketika kemacetan berkurang. Tentang Deteksi Dini Random Mekanisme RED diusulkan oleh Sally Floyd dan Van Jacobson pada awal tahun 1990an untuk mengatasi kemacetan jaringan secara responsif dan bukan reaktif. Mendasari mekanisme RED adalah premis bahwa sebagian besar lalu lintas berjalan pada implementasi transportasi data yang sensitif terhadap kerugian dan akan melambat sementara ketika beberapa lalu lintas mereka turun. TCP, yang merespons dengan tepat, dengan penurunan lalu lintas yang melambat dengan memperlambat transmisi lalu lintasnya, secara efektif memungkinkan perilaku turunan lalu lintas RED berfungsi sebagai mekanisme pensinyalan penghindaran kemacetan. TCP merupakan transport jaringan yang paling banyak digunakan. Mengingat kehadiran TCP yang ada di mana-mana, RED menawarkan mekanisme penghindaran kemacetan yang luas dan efektif. Dalam mempertimbangkan kegunaan RED ketika transport yang kuat seperti TCP yang meresap, penting untuk mempertimbangkan juga implikasi negatif yang serius dalam menggunakan RED ketika persentase lalu lintas yang signifikan tidak kuat sebagai respons terhadap packet loss. Baik Novell NetWare maupun AppleTalk benar-benar tangguh dalam menanggapi packet loss, oleh karena itu sebaiknya Anda tidak menggunakan RED untuk mereka. 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